Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display fetched json data into listview using baseadapter

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

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 .

My code is below,

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

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

If I try to not to use ArrayList stringArray = new 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.

like image 583
Mushfiqul Tuhin Avatar asked Dec 15 '22 01:12

Mushfiqul Tuhin


1 Answers

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>

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;

}

}

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

}
}

 }
like image 102
M D Avatar answered May 16 '23 05:05

M D