Skip to content Skip to sidebar Skip to footer

After Sorting Jsonarray,custom List View Not Changed?

I am sorting JSONArray and show them in a custom list view, but after sorting the data does not changed in custom list view. Here is my code for fab button to select which sort is

Solution 1:

Before set the data to Listview, you should sort the data using comparator class in java.

you create one Model class with all variable what you want (name,booth_id etc)and store the each object into the ArrayList.

Collections.sort(ArrayListObject,newNameComparator()); 

example

classNameComparatorimplementsComparator{  
public int compare(Object o1,Object o2){  
YourClassName s1=(YourClassName )o1;  
YourClassName s2=(YourClassName )o2;  

return s1.name.compareTo(s2.name);  
}  
} 

Solution 2:

In my case i got homeList(ArrayList of model 'Home') from JSONParser class so befor setAdapter

 Collections.sort(homeList, newComparator<Home>() {
                    publicintcompare(Home emp1, Home emp2) {
                        intprice1= emp1.getPrice();
                        intprice2= emp2.getPrice();



                        return Integer.compare(price1, price2);

                    }
                });
    Adapteradapter=newAdapter(getActivity(),homeList);
    listView.setadapter(adapter);

So this will first sort whole arraylist and then we need to setAdapter.

Try this i think this will help you.

Solution 3:

Instead of creating one object of data with string array for its fields. Create one object for each element of JsonArray. Create a list for objects from JsonArray. Pass that list in your Custom Adapter. Set the listview adapter as custom adapter.

Now whenever you want to sort the data by any field. Just use Java collections comparator or you can write your own custom comparator.

After that just call notifyDataSetChanged() on the adapter.

Edit -

You can create your model SearchItem like below

classSearchItem {
    privateString voterId;
    privateString boothNameId;
    privateString searchName;
    privateString houseNumber;
    privateString gender;

    publicvoidsetVoterId(String voterId) {
        this.voterId = voterId;
    }

    publicStringgetVoterId() {
        return voterId;
    }

    ......................(Addas many fields you want and their corresponding getter and setter methods)
}

Your Json parse class can be modified like this (You have to populate all the fields of SearchItem class.

classParseJsonData {

    publicstaticArrayList<SearchList> parseSearchresult(String jsonResponse) {
        try {
            JSONObject searchData = newJSONObject(jsonResponse);
            JSONArray searchArray=searchData.getJSONArray(SEARCH_VOTER_ARRAY);
            ArrayList<SearchItem> searchList = newArrayList<SearchItem>();
            for(int index = 0; index < searchArray.length(); index++) {
                JSONObject searchItem = searchArray.get(index);
                SearchItem item = newSearchItem();
                item.setVoterId(searchItem.optString(KEY_VOTER_ID, null);
                item.setBoothNameId(searchItem.optString(KEY_BOOTHNAME_ID, null);
                item.setSearchName(searchItem.optString(KEY_SEARCH_NAME, null);
                item.setHouseNumber(searchItem.optString(KEY_SEARCH_HOUSE_NUMBER, null);
                item.setGender(searchItem.optString(KEY_SEARCH_GENDER, null);
                searchList.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return searchList;
    }
}

Now you can create your own custom adapter as follows

classCustomSearchListextendsBaseAdapter {
    ArrayList<SearchItem> mSearchList;
    Context mContext;

    publicCustomSearchList(Context context, ArrayList<SearchItem> searchList) {
        mContext = context;
        mSearchList = searchList;
    }

    ..........................(Implement methods for BaseAdapter or other methods you want to write)
}

Here searchList is passed as reference, so any update in that list followed by notify call to adapter will reflect the change.

Your listview class can be modified like this. parseSearchList() method returns an arraylist of all searchlist.

privatevoidgetList(String json) {
    ArrayList<SearchItem> searchList = ParseJsonData.parseSearchresult(json);
    CustomSearchList adapter = newCustomSearchList(this, searchList);
    searchlistView.setAdapter(adapter);

    mBtn.setOnClickListener(this, newOnClickListener() {
        @OverridepublicvoidonClick(....) {
            //Suppose when some button click happens for sortingCollections.sort(searchList, <yourCustomComparator>);
            notifyDataSetChanged();
        }
    });
}

It would be better if you can make searchList as a Member variable not the local one.

Solution 4:

Yes , i think you have to use model class. Here is example with onPostExecute.

@OverrideprotectedvoidonPostExecute(String s) {
        super.onPostExecute(s);
        pd.dismiss();

        try {
            JSONObjectobject = newJSONObject(s.toString());
            YourModelNameList = newArrayList<>();

            if (object.getString("status").equalsIgnoreCase("true")) {
                JSONArray array = object.getJSONArray("data");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonProduct = array.getJSONObject(i);
                    YourModelName home = newHome();
                    String special = jsonProduct.getString("special_price");
                    home.setId(jsonProduct.getString("product_id"));
                    home.setName(jsonProduct.getString("product_name"));
                    home.setPrice(jsonProduct.getString("price"));
                    YourModelArrayList.add(home);
                }
            } 
            Collections.sort(YourModelArrayList, newComparator<YourModelName>() {
                public int compare(YourModelName emp1, YourModelName emp2) {
                    int price1 = emp1.getPrice();
                    int price2 = emp2.getPrice();



                    returnInteger.compare(price1, price2);

                }
            });


            adapter = newYourModelArrayListAdapter(getActivity(), YourModelArrayList);
            recyclerView.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } 

Try this if this will help you. Thank you.

Solution 5:

I have sort the arraylist named ArrayList> addressaray; add response data to arraylist using

JSONObjectobject = newJSONArray(s.toString());
JSONArray arr1 = newJSONArray(object.getString("data").toString()).getJSONArray(0);
for (int i = 0; i < arr1.length(); i++) {
 JSONObject jsonObject = arr1.getJSONObject(i);
 HashMap<String, String> data = newHashMap<String, String>();
 data.put("id", jsonObject.getString("id"));
 data.put("date_inspected_details", jsonObject.getString("date_inspected_details"));
 addressaray.add(data);
    }
    adapter = newPropertiesEvaluatedFragmentAdapter(getActivity(), addressaray, getActivity().getSupportFragmentManager());
  listView.setAdapter(adapter);
  adapter.notifyDataSetChanged();
}

 @OverridepublicvoidonItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String item = parent.getItemAtPosition(position).toString();
 if(addressaray.size() > 0){
                sortListView(item);
                adapter.notifyDataSetChanged();
            }else{
                Toast.makeText(getActivity(), "No Record found.", Toast.LENGTH_SHORT).show();
            }

}

  privatevoidsortListView(String option) {
        switch (option) {
            case"Date":

Collections.sort(addressaray, newComparator<HashMap<String, String>>() {
                    final staticStringCOMPARE_KEY = "date_inspected_details";

                    @Overridepublic int compare(HashMap<String, String> lhs,
                                       HashMap<String, String> rhs) {
                        StringDate1 = lhs.get(COMPARE_KEY);
                        StringDate2 = rhs.get(COMPARE_KEY);
                        Log.e("Date1", Date1);
                        Log.e("Date2", Date2);
                        // Do your comparison logic here and retrn accordingly.returnDate1.compareTo(Date2);
                    }
                });
  break;
}
}JSONObjectobject = newJSONArray(s.toString());
JSONArray arr1 = newJSONArray(object.getString("data").toString()).getJSONArray(0);
for (int i = 0; i < arr1.length(); i++) {
 JSONObject jsonObject = arr1.getJSONObject(i);
 HashMap<String, String> data = newHashMap<String, String>();
 data.put("id", jsonObject.getString("id"));
 data.put("date_inspected_details", jsonObject.getString("date_inspected_details"));
 addressaray.add(data);
    }
    adapter = newPropertiesEvaluatedFragmentAdapter(getActivity(), addressaray, getActivity().getSupportFragmentManager());
  listView.setAdapter(adapter);
  adapter.notifyDataSetChanged();
}

 @OverridepublicvoidonItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String item = parent.getItemAtPosition(position).toString();
 if(addressaray.size() > 0){
                sortListView(item);
                adapter.notifyDataSetChanged();
            }else{
                Toast.makeText(getActivity(), "No Record found.", Toast.LENGTH_SHORT).show();
            }

}

  privatevoidsortListView(String option) {
        switch (option) {
            case"Date":

Collections.sort(addressaray, newComparator<HashMap<String, String>>() {
                    final staticStringCOMPARE_KEY = "date_inspected_details";

                    @Overridepublic int compare(HashMap<String, String> lhs,
                                       HashMap<String, String> rhs) {
                        StringDate1 = lhs.get(COMPARE_KEY);
                        StringDate2 = rhs.get(COMPARE_KEY);
                        Log.e("Date1", Date1);
                        Log.e("Date2", Date2);
                        // Do your comparison logic here and retrn accordingly.returnDate1.compareTo(Date2);
                    }
                });
  break;
}
}

Post a Comment for "After Sorting Jsonarray,custom List View Not Changed?"