如何使用baseadapter显示获取JSON数据到列表视图 [英] how to display fetched json data into listview using baseadapter

查看:154
本文介绍了如何使用baseadapter显示获取JSON数据到列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和java.Recently我有问题,显示获取JSON数据到列表视图使用baseadapter。 起初,我已经使用这个code

I am new to android and java.Recently I am having problem with displaying fetched json data into listview using baseadapter. At first I have used this code

  @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;
}
  }

这code显示器取出JSON数据成功地。但它只显示只有一排。我需要在列表视图多个(二)行。所以,我已经试过这code 而这是行不通的,它显示了一个空白屏幕。

This code displays fetched json data sucessfully. But it only displays only one row. I need more than one (two) rows in listview. So I have tried this code and it does not work, it shows a blank screen .

我的code是低于,

 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");
    } 


}

据我意识到,问题就在这里。

As far I am realizing that , the problem is here

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();
            }
        }

据我guesing的提取JSON数据被存储在字符串数组,但它不是以后使用。如果我尝试使用这样的,然后我得到的错误

As far I am guesing that extracted json data is storing in stringArray but its not used later. If I try to use it like this , then I get error

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

如果我尽量不使用     ArrayList的字符串数组=新的ArrayList();

If I try to not to use ArrayList stringArray = new ArrayList();

和使用
    ArrayList的=新的ArrayList();相反,这样的话,我也得到错误。

and use
arrayList=new ArrayList(); instead , like this then I also get error.

    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();
            }
        }

我不能找出如何解决这个疑难问题已经看到网上很多教程,但这些不是我有帮助。请帮我。

I can not finding out how to solve this problem.I have seen many online tutorials but those was not helpful for me. Please help me.

推荐答案

首先u需要牛逼创建<​​code> row_listitem.xml 文件,如:

First u need t create row_listitem.xml file like:

<?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>

现在,U盘需要创建自定义BaseAdapter 这样的:

Now, u need to create Custom BaseAdapter like:

  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;

}

}

现在,U可以设置您的主要活动这样的:

Now, u can set up your main activity like:

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");
    }

}
}

 }

这篇关于如何使用baseadapter显示获取JSON数据到列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆