0

My goal is to put the fetched JSON in my ArrayList<Object> to be able to display my ListView I'm searching for syntax how to do it but I'm confuse on how to do it correctly.

here's my code

public class MyListActivity extends ActivityWithTabBar implements
    OnGestureListener, OnTouchListener {

  private String searchText = null;
  private ArrayList<ListItems> itemsArray = null;
  private MyArrayAdapter myArrayAdapter;
  private ListView lv = null;

  public void onCreate(Bundle savedInstanceState) {
  searchText = intent.getStringExtra(Constants.SEARCH).trim();
  performSearch();

  }

  private void performSearch() {
    searchText = editTextSearch.getText().toString();
    loadDataViaWS();
  }

  private void loadDataViaWS(){
    itemsArray = new ArrayList<ListItems>();
    lv = (ListView) findViewById(R.id.listViewSearch);
    this.myArrayAdapter = new MyArrayAdapter(this,
            R.layout.listview_row_2rows_subtitle, itemsArray);
    lv.setAdapter(this.myArrayAdapter);

    new GetValues().execute();
}

Here is my AsyncTask

class GetValues extends AsyncTask<Void, Void, ArrayList<ListItems>> { 
 private final String URL_STRING = url;
HttpClient httpclient = new DefaultHttpClient();
 HttpGet httpget = new HttpGet(URL_STRING);
String jsonData = null;

@Override 
 protected ArrayList<ListItems> doInBackground(Void... params){
 try {
            HttpResponse response = httpclient.execute(httpget);
            jsonData =  EntityUtils.toString(response.getEntity());
            Log.d(TAG, String.format("JSON:", jsonData));

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

itemsArray = new ArrayList<ListItems>();
        JSONObject object = null;
        try {
            object = new JSONObject(jsonData);
            JSONArray jArray  = object.getJSONArray("DATA");

            for(int i = 0; i < jArray.length(); i++){
                JSONObject jObj = jArray.getJSONObject(i);

                String Id = jObj.getString("id");
                String Name = jObj.getString("name");
                String Description = jObj.getString("description");


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


        return null;
}

As you can see in my doInBackground inside the for loop how will I put the JSONObject I fetched in my itemsArray where itemsArray is equal to ArrayList<ListItems> ?

Edit

Here is my ListItems

public class ListItems implements Serializable {
 private int id;
 private String name;
 private String description;

 public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
natsumiyu
  • 3,217
  • 7
  • 30
  • 54

5 Answers5

1

You've got almost everything working here all you need to do is create a new ListItems like so:

for(int i = 0; i < jArray.length(); i++){
    JSONObject jObj = jArray.getJSONObject(i);

    String Id = jObj.getString("id");
    String Name = jObj.getString("name");
    String Description = jObj.getString("description");

    ListItems item = new ListItems();
    item.setId(id);
    item.setName(Name);
    item.setDescription(Description);

    itemsArray.add(item);
}
Abbas
  • 3,529
  • 5
  • 36
  • 64
  • should I return `itemsArray` after the `for` loop instead of null in `doInBackground` ? – natsumiyu Sep 06 '16 at 05:39
  • 1
    @mori You should, and you should be able to retrieve it in `onPostExecute()` form there you can pass it on to your ListView via CallBack. – Abbas Sep 06 '16 at 06:10
1

Override the postExecute Method like, For adding the items to the arraylist follow the previous answers

@Override
protected void onPostExecute(ArrayList<ListItems> items)
{
  myArrayAdapter = new MyArrayAdapter(this,R.layout.listview_row_2rows_subtitle, itemsArray);
//Declare Listview as global
listView.setAdapter(myArrayAdapter);
}

This should work for you.

Ashik Vetrivelu
  • 1,021
  • 1
  • 9
  • 24
1

Here I've modified your code look into it

    class GetDealsByNameDescAdd extends AsyncTask<Void, Void, ArrayList<ListItems>> { 
     private final String URL_STRING = url;
    HttpClient httpclient = new DefaultHttpClient();
     HttpGet httpget = new HttpGet(URL_STRING);
    ArrayList<ListItems> itemsArray;
    String jsonData = null;

    @Override 
     protected ArrayList<ListItems> doInBackground(Void... params){
     try {
                HttpResponse response = httpclient.execute(httpget);
                jsonData =  EntityUtils.toString(response.getEntity());
                Log.d(TAG, String.format("JSON:", jsonData));

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

    itemsArray = new ArrayList<ListItems>();
            JSONObject object = null;
            try {
                object = new JSONObject(jsonData);
                JSONArray jArray  = object.getJSONArray("DATA");

                for(int i = 0; i < jArray.length(); i++){
                    JSONObject jObj = jArray.getJSONObject(i);

                    ListItems item=new ListItems();

                    //String Id = jObj.getString("id"); //replce this with following code
                    item.setId(jObj.getString("id"));

                    //String Name = jObj.getString("name");  //replce this with following code
                    item.setName(jObj.getString("name"));

                    //String Description = jObj.getString("description");   //replce this with following code
                    item.setDescription(jObj.getString("description"));

                    itemsArray.add(items);

                }
            } catch (JSONException e) {
                e.printStackTrace();
                //if there is an exception in parsing json then it returns null
                return null;
            }


            return itemsArray;
    }
    public void onPostExecute(ArrayList<ListItems> items){
        if(items!=null){
            //here you will receive valid set of data 
            //and you can add it to your adapter
        }else{
            //this part will execute, If we are having JSON exception
            // so we need to check the JSON response 
            //and here we should handle this NPE

            //show toast that we are receiving BAD JSON response
        }
    }
}

Here is your POJO class

class ListItems{
private id,name,description;

public ListItems(){}

public void setId(String id){
this.id=id;
}

public String getId(){
return id;
}

public void setName(String name){
this.name=name;
}

public String getName(){
return name;
}

public void setDescription(String description){
this.description=description;
}

public String getDescription(){
return description;
}
}

Hope this will help you.

Madhan
  • 495
  • 2
  • 10
  • 22
0

Assuming your model class ListItems is having setter methods like setId(String id), setName(String name) and setDescription(String desc).

Your for loop should look like

    for(int i = 0; i < jArray.length(); i++){
            JSONObject jObj = jArray.getJSONObject(i);

            String Id = jObj.getString("id");
            String Name = jObj.getString("name");
            String Description = jObj.getString("description");

            ListItems items = new ListItems();
            items.setId(Id);
            items.setName(Name);
            items.setDescription(Description);

            itemsArray.add(items);
    }
// Notify your adapter here.. after adding data into your `ArrayList`. You should do that stuff in `PostExecute()` method of an `AsyncTask`.

Hope this helps!

Paresh P.
  • 6,677
  • 1
  • 14
  • 26
0

For the ListView you will have to implement a BaseAdapter that binds your arraylist items to your list of views. Once you call the adapter with the ArrayList, it renders the views onto your ListView. If you fetch items again and there are newer elements from before, just call the notifyDataSetChanged().

This could help : Android. How does notifyDataSetChanged() method and ListViews work?

Community
  • 1
  • 1
Arjun Issar
  • 672
  • 4
  • 13
  • 32