Listview 不显示数据,但显示要显示值的空白位置

Posted

技术标签:

【中文标题】Listview 不显示数据,但显示要显示值的空白位置【英文标题】:Listview not showinng the data but showinng the blank position where the value is to be shown 【发布时间】:2019-04-15 21:22:23 【问题描述】:

我正在解析一个JSON 并用它膨胀listview。第一个列表视图显示正确的值,但是当我从我的贡献者按钮打开另一个活动时,第二个 listview 没有显示任何值,而是在要显示文本的地方显示一个空白区域。

这是我的代码...

主要活动

package com.example.pc.jbossoutreachapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;


public class MainActivity extends AppCompatActivity 


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    




    public void getStarted(View view)
    
        Intent intent = new Intent(this, repositories.class);
        startActivity(intent);
    


布局activity.main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:background="@drawable/background"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_
        android:layout_
        android:contentDescription="@string/ContentDescipt"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/logo" />

    <TextView
        android:id="@+id/textView"
        android:layout_
        android:layout_
        android:layout_marginBottom="1dp"
        android:gravity="center"
        android:text="@string/JBoss"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="@dimen/size"
        android:textStyle="bold"
        app:fontFamily="sans-serif-smallcaps"
        app:layout_constraintBottom_toTopOf="@+id/textView3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_
        android:layout_
        android:gravity="center"
        android:text="@string/JBoss_intro"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button"
        android:layout_
        android:layout_
        android:background="#f0e68c"
        android:onClick="getStarted"
        android:text="@string/Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

</android.support.constraint.ConstraintLayout>

存储库类

这里的代码工作正常,项目显示在列表视图中

HttpHandler 类进行服务调用并返回 Json 字符串。

package com.example.pc.jbossoutreachapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class repositories extends AppCompatActivity 

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog ProgDialog;
    private ListView listview;

    private static String url = "https://api.github.com/orgs/JBossOutreach/repos";

    ArrayList<HashMap<String,String>> RepoDetails;


    public void link(View view)
    
        TextView text = findViewById(R.id.Repolink);
        String url = text.getText().toString();

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(browserIntent);

    



    public void Contributors(View view)
    
        listview = findViewById(R.id.list);
        TextView name = findViewById(R.id.RepositoryName);
        String n = name.getText().toString();
        String url1 = "https://api.github.com/repos/JBossOutreach/"+n+"/contributors";
        Intent intent = new Intent(this, contributors.class);
        Bundle bundle = new Bundle();
        bundle.putString("url", url1);
        intent.putExtras(bundle);
        startActivity(intent);
    

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repositories);

        RepoDetails = new ArrayList<>();

        listview = (ListView)findViewById(R.id.list);

        new GetContacts().execute();
    


    private class GetContacts extends AsyncTask<Void, Void, Void>
    

        @Override
        protected void onPreExecute() 
            super.onPreExecute();

            ProgDialog = new ProgressDialog(repositories.this);
            ProgDialog.setMessage("Please wait...");
            ProgDialog.setCancelable(false);
            ProgDialog.show();
        

        @Override
        protected Void doInBackground(Void... voids) 

            HttpHandler sh = new HttpHandler();

            String Json_String = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + Json_String);

            if(Json_String != null)
            
                try
                
                  JSONArray array = new JSONArray(Json_String);
                    for(int i = 0; i < array.length(); i++)
                    
                        JSONObject ob = array.getJSONObject(i);

                        String name = ob.getString("name");

                        JSONObject owner = ob.getJSONObject("owner");
                        String link = owner.getString("html_url");

                        HashMap<String, String> contact = new HashMap<>();

                        contact.put("name", name);
                        contact.put("link", link+"/"+name);

                        RepoDetails.add(contact);
                    
                
                catch(final JSONException e)
                
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() 
                        @Override
                        public void run() 
                            Toast.makeText(getApplicationContext(),
                                    "Json Parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();                        
                    );
                
            

            else
            
                Log.e(TAG, "Couldn't get Json from server");
                runOnUiThread(new Runnable() 
                    @Override
                    public void run() 
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server ", Toast.LENGTH_LONG).show();
                    
                );
            

            return null;
        

        @Override
        protected void onPostExecute(Void aVoid) 
            super.onPostExecute(aVoid);
            if(ProgDialog.isShowing())
            
                ProgDialog.dismiss();
            

            ListAdapter adapter = new SimpleAdapter(
                    repositories.this, RepoDetails, R.layout.repo_list_item, new String[]
                    "name", "link", new int[]R.id.RepositoryName, R.id.Repolink);

            listview.setAdapter(adapter);
        

    


repositories.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:background="@drawable/background">

    <TextView
        android:id="@+id/textView2"
        android:layout_
        android:layout_
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="109dp"
        android:layout_marginLeft="109dp"
        android:layout_marginTop="0dp"
        android:text="@string/Heading1"
        android:textSize="24sp"
        android:textStyle="bold" />

    <ListView
        android:id="@+id/list"
        android:layout_
        android:layout_
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp" />

</RelativeLayout>

repo_list_itmen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical"
    android:padding="5dp">

    <TextView
        android:id="@+id/RepositoryName"
        android:layout_
        android:layout_
        android:paddingTop="15dp"
        android:paddingBottom="8dp"
        android:textColor="@color/NameRepo" />

    <TextView
        android:id="@+id/Repolink"
        android:layout_
        android:layout_
        android:onClick="link"
        android:paddingBottom="8dp"
        android:textColor="@color/colorAccent" />

    <Button
        android:id="@+id/button2"
        android:layout_
        android:layout_
        android:onClick="Contributors"
        android:text="@string/Contributors" />


</LinearLayout>

贡献者类

问题从这里开始,不显示任何项目,但只显示项目的空白区域。

package com.example.pc.jbossoutreachapp;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class contributors extends AppCompatActivity 


    private String TAG = contributors.class.getSimpleName();
    ArrayList<HashMap<String, String>> names;
    ListView lv;
    private ProgressDialog progressDialog;
    static String url;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contributors);
        names = new ArrayList<>();
        lv = findViewById(R.id.list2);

        Bundle bundle = getIntent().getExtras();
        System.out.print(url);
        url = bundle.getString("url");

        new contributors.getcontrib().execute();
    


    private class getcontrib extends AsyncTask<Void, Void, Void> 

        @Override
        protected void onPreExecute() 
            super.onPreExecute();

            progressDialog = new ProgressDialog(contributors.this);
            progressDialog.setMessage("Please wait...");
            progressDialog.setCancelable(false);
            progressDialog.show();
        

        @Override
        protected Void doInBackground(Void... voids) 

            HttpHandler hd = new HttpHandler();
            String Json_result = hd.makeServiceCall(url);
            Log.e(TAG, "Response from url: " + Json_result);

            if (Json_result != null) 
                try 
                    JSONArray array = new JSONArray(Json_result);
                    for (int i = 0; i < array.length(); i++) 
                        JSONObject obj = array.getJSONObject(i);
                        String contributor_name = obj.getString("login");

                        HashMap<String, String> hashMap = new HashMap<>();
                        hashMap.put("name", contributor_name);


                        names.add(hashMap);
                    
                 catch (final JSONException e) 
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() 
                        @Override
                        public void run() 
                            Toast.makeText(getApplicationContext(),
                                    "Json Parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        
                    );
                
            


            return null;
        

        @Override
        protected void onPostExecute(Void aVoid) 
            super.onPostExecute(aVoid);
            if (progressDialog.isShowing()) 
                progressDialog.dismiss();
            

            ListAdapter adapter = new SimpleAdapter(
                    contributors.this, names, R.layout.contributor_list_items, new String[]
                    "contributors", new int[]R.id.ContributorsName);
            ((SimpleAdapter) adapter).notifyDataSetChanged();
            lv.setAdapter(adapter);
        

    


contributors.xml

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_
        android:layout_
        android:background="@drawable/background">

        <TextView
            android:id="@+id/textView2"
            android:layout_
            android:layout_
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="109dp"
            android:layout_marginLeft="109dp"
            android:layout_marginTop="0dp"
            android:text="@string/Heading2"
            android:textSize="24sp"
            android:textStyle="bold" />

        <ListView
            android:id="@+id/list2"
            android:layout_
            android:layout_
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="0dp"
            android:layout_marginTop="0dp" />

    </RelativeLayout>

contributors_list_items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical"
    android:padding="5dp">

    <TextView
        android:id="@+id/ContributorsName"
        android:layout_
        android:layout_
        android:paddingTop="15dp"
        android:paddingBottom="8dp"
        android:textColor="@color/colorPrimaryDark" />

</LinearLayout>

【问题讨论】:

看来你是 android 开发世界的新手。第一步,我建议您检查是否收到 API 响应。 是的,我刚刚开始。如何检查? hashMap.put("name", contributor_name); 这会将所有值写入 hashmap 中的单个条目,因为 hashmap 不允许不同值使用相同的键。 @Dbuiss 放置断点并调试它。或者最好只检查logcat 窗口,您会发现日志,因为您已经在打印Log.e(TAG, "Response from url: " + Json_result); @KaranMer 但这对于第一个列表视图效果很好 【参考方案1】:

更改您的 AsyncTask 调用

new contributors.getcontrib().execute();

new getcontrib().execute();

编辑:

另外,更改您的适配器初始化代码:

ListAdapter adapter = new SimpleAdapter(
                    contributors.this, names, R.layout.contributor_list_items, new String[]
                    "contributors", new int[]R.id.ContributorsName);

ListAdapter adapter = new SimpleAdapter(
                    contributors.this, names, R.layout.contributor_list_items, new String[]
                    "name", new int[]R.id.ContributorsName);

注意:您在“name”键中添加了您的贡献者姓名,而不是在“contributors”键中

【讨论】:

嘿,你复制我的方法很好 ListAdapter 适配器 = new SimpleAdapter(contributors.this, names, R.layout.contributor_list_items, new String[] "name", new int[]R.id.ContributorsName); 新的 int[]R.id.ContributorsName);添加同名 "name", new int[]R.id.ContributorsName)【参考方案2】:

首先检查你的响应。

          String url1 = "https://api.github.com/repos/JBossOutreach/"+n+"/contributors";

你的 Json 响应

          
         "message": "Not Found",
          "documentation_url": "https://developer.github.com/v3/repos/#list-contributors"
        

【讨论】:

n 是用于存储名称的字符串变量。 我在 logcat 中得到响应。 如何查看你的消息 “消息”:“未找到”, 你如何回应“消息”:“未找到”,

以上是关于Listview 不显示数据,但显示要显示值的空白位置的主要内容,如果未能解决你的问题,请参考以下文章

带有集合(ListView)的Android小部件不显示项目

如何使用 listview 显示用户列表

空ListView显示另一个活动

在winform中,怎么做到一个按钮,,点击一下在listview显示一组新数据,然后点一下listview显示原来的数据.

ListView 不显示默认视图

列表视图中的文本块不显示绑定数据 - WPF XAML