android - 如何使用 baseadapter 将获取的 json 数据显示到 ListView 中

标签 android json listview

我是 android 和 java 的新手。最近我在使用 baseadapter 将获取的 json 数据显示到 ListView 时遇到问题。 一开始我用过这段代码

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

   new TheTask().execute();
  }
     class TheTask extends AsyncTask<Void,Void,String>
  {

@Override
protected String doInBackground(Void... params) {
    String str = null;
    try
    {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
      HttpResponse response = httpclient.execute(httppost);
      str =  EntityUtils.toString(response.getEntity());     
    } 
    catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

    return str;

  }



@Override
    protected void onPostExecute(String result) {

    super.onPostExecute(result);

    String response = result.toString();
    try {


        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);

        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }




        ArrayAdapter<String> adapter = new ArrayAdapter<String>   (MainActivity.this,R.layout.test_tuh,stringArray);            
        ListView list= (ListView) findViewById(R.id.listView1);
        list.setAdapter(adapter);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //tv.setText("error2");
    } 


}
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
  }

此代码成功显示获取的 json 数据。但它只显示一行。我在 ListView 中需要不止一(两)行。所以我试过这段代码 它不起作用,显示空白屏幕。

我的代码如下,

 class TheTask extends AsyncTask<Void,Void,String>
  {

    @Override
    protected String doInBackground(Void... params) {
    String str = null;
    try
    {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
      HttpResponse response = httpclient.execute(httppost);
      str =  EntityUtils.toString(response.getEntity());     
    } 
    catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

    return str;

  }


@Override
    protected void onPostExecute(String result) {


    // TODO Auto-generated method stub
    super.onPostExecute(result);

    String response = result.toString();
    try {
         arrayList=new ArrayList<get_set>();

        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);



        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }



   ListView listView;
    adap= new BaseAdapter() {
        LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        @Override
        public View getView(int position, View view, ViewGroup viewgroup) {
            if (view==null) {
                view=inflater.inflate(R.layout.bsdi, null);
            }
            TextView title_tuh=(TextView) view.findViewById(R.id.title1);
            TextView notice_tuh=(TextView) view.findViewById(R.id.notice1);


            title_tuh.setText(arrayList.get(position).getTitle());
            notice_tuh=.setText(arrayList.get(position).getNotice());
            return view;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return arrayList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return arrayList.size();
        }
    };


    listView=(ListView) findViewById(R.id.listView1);
    listView.setAdapter(adap);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //tv.setText("error2");
    } 


}

据我所知,问题出在这里

ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);



        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

到目前为止,我猜测提取的 json 数据存储在 stringArray 中,但以后没有使用。如果我尝试像这样使用它,则会出现错误

title_tuh.setText(stringArray .get(position).getTitle());
notice_tuh=.setText(stringArray .get(position).getNotice());

如果我尽量不使用 ArrayList stringArray = new ArrayList();

并使用
数组列表=新数组列表();相反,像这样我也会得到错误。

    arrayList=new ArrayList<get_set>();


        JSONArray new_array = new JSONArray(response);


        //JSONArray jsonArray = new JSONArray();
        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                arrayList.add(jsonObject.getString("title").toString());
               // String in = mInflater.inflate(R.layout.custom_row_view, null);

            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

我找不到解决这个问题的方法。我看过很多在线教程,但对我没有帮助。请帮助我。

最佳答案

首先你需要创建 row_listitem.xml 文件,如:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="@drawable/list_selector"
android:orientation="vertical"
android:padding="5dp" >

<ImageView
    android:id="@+id/iv_icon_social"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_centerVertical="true"
    android:background="@drawable/image_border"
    android:src="@drawable/sms_t"
    android:visibility="gone" />

<LinearLayout
    android:id="@+id/thumbnail"
    android:layout_width="fill_parent"
    android:layout_height="85dp"
    android:layout_marginRight="50dp"
    android:layout_marginTop="0dp"
    android:layout_toRightOf="@+id/iv_icon_social"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:padding="5dip"
    android:visibility="visible" >

    <TextView
        android:id="@+id/txt_ttlsm_row"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:text="Sample text"
        android:textSize="18dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txt_ttlcontact_row2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="3dp"
        android:paddingLeft="10dp"
        android:maxEms="20"
        android:maxLines="2"
        android:singleLine="false"
        android:ellipsize="end"
        android:text="Sample text2"
        android:textColor="#808080"
        android:textSize="15dp"
        android:textStyle="normal"
        android:visibility="visible" />


</LinearLayout>

</RelativeLayout>

现在,您需要创建Custom BaseAdapter,例如:

  public class BaseAdapter2 extends BaseAdapter {

private Activity activity;
// private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;

public BaseAdapter2(Activity a, ArrayList b, ArrayList bod) {
    activity = a;
    this.title = b;
    this.notice=bod;

    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return title.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.row_listitem, null);

    TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title
    String song = title.get(position).toString();
    title2.setText(song);


    TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice
    String song2 = notice.get(position).toString();
    title22.setText(song2);

return vi;

}

现在,您可以设置您的主要 Activity ,例如:

public class MainActivity extends Activity {

ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
BaseAdapter2 adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView1);
    new TheTask().execute();
}

class TheTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String str = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://10.0.2.2/BSDI/show.php");
            HttpResponse response = httpclient.execute(httppost);
            str = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;

    }



@Override
protected void onPostExecute(String result) {

    super.onPostExecute(result);

    String response = result.toString();
    try {


        JSONArray new_array = new JSONArray(response);

        for (int i = 0, count = new_array.length(); i < count; i++) {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                title_array.add(jsonObject.getString("title").toString());
                notice_array.add(jsonObject.getString("notice").toString());

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        adapter = new BaseAdapter2(MainActivity.this, title_array, notice_array);
        list.setAdapter(adapter);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        // tv.setText("error2");
    }

}
}

 }

关于android - 如何使用 baseadapter 将获取的 json 数据显示到 ListView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21662673/

相关文章:

java - Async doInBackground 会崩溃,并强制关闭

android - 如何在 ViewPager 中为 ImageView 设置不同的动画

json - 如何使用控制台在 aws SNS 中发送 json 消息正文

android - 内容在 Android fragment 中不可见

android - listview setItemChecked 无法正常工作

android - 尝试在 Activity 中打开时 Recycler View 崩溃

java - 使用 asynctask 进行网络连接

java - 从 Android 站点获取特定内容

iphone - 解析具有从 JSON 消息生成的单个值的 NSArray

android - 未正确构建 ListView 项目