简体   繁体   中英

How to sort custom array list adapter in descending android

I have an 4 array list which i used in my custom adapter class. I want it to be in descending form depending on their ratings. i used collection.sort(ratings.Collection.reverseOrder()); it works fine it is arranging the ratings in descending form depending on their ratings but the other array list retain the same. i want them to be specify depending on their position.

i am using this code.

Collections.sort(mRatings,Collections.reverseOrder());
                adapterz = new SummaryAdapter(MapsActivity.this, mNames, 
mAddress, mRatings, mDistance);
                recyclerView.setAdapter(adapterz);
                adapterz.notifyDataSetChanged();

I have edited my answer to purposely clear anyone. im sorry im not much familiar in java. so hmm you suggested ill work on with comparable i tried it but it doesnt work well how am i going to deal with it? this is where i add data in my array list. btw i am using google nearby places and this is i add place details to the respective array list.

in my GetNearbyPlace class

                else if (MapsActivity.x == "pStore") {
                 for (int i = 0; i < nearbyPlaceList.size(); i++) {
                MarkerOptions markerOptions = new MarkerOptions();
                HashMap<String, String> googlePlace = nearbyPlaceList.get(i);

                 placeName = googlePlace.get("place_name");
                 vicinity = googlePlace.get("vicinity");


                String rating = googlePlace.get("rating");

                double lat = Double.parseDouble(googlePlace.get("lat"));
                double lng = Double.parseDouble(googlePlace.get("lng"));


                String snippet = "Address: " + vicinity + "\n" +
                       // "Phone Number: " + formatted_phone_number + "\n" +
                       // "Website: " + url + "\n" +
                        "Place Rating: " + rating + "\n";

                LatLng latLng = new LatLng(lat, lng);
                markerOptions.position(latLng);

                markerOptions.title(placeName);
                markerOptions.snippet(snippet);








             markerOptions.icon
            (BitmapDescriptorFactory.fromResource(R.drawable.ic_pstore));

                mMap.addMarker(markerOptions);
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(10));

                MapsActivity.mNames.add( googlePlace.get("place_name"));
                MapsActivity.mAddress.add(googlePlace.get("vicinity"));
                int x = 0;
                try {
                    x = Integer.parseInt(googlePlace.get("rating"));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                float results[] = new float[10];
                Location.distanceBetween(MapsActivity.latitude, 
                 MapsActivity.longitude,lat,lng,results);

                int rate= 0;
                try {
                    rate = new Integer(googlePlace.get("rating"));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                MapsActivity.mRatings.add(rate);


                MapsActivity.mDistance.add(results[0]);

and in my MainActivity

I declare arraylist as global

           public static ArrayList<String> mNames = new ArrayList<>();
           public static ArrayList<String> mAddress = new ArrayList<>();
           public static ArrayList<Integer> mRatings = new ArrayList<>();
           public static ArrayList<Float> mDistance = new ArrayList<>();

//and then added it in to the adapter

                    Collections.sort(mDistance);
                     adapterz = new SummaryAdapter(MapsActivity.this, mNames, 
                     mAddress, mRatings, mDistance);

           recyclerView.setAdapter(adapterz);
           adapterz.notifyDataSetChanged();

//My adapter

      public class SummaryAdapter extends 
      RecyclerView.Adapter<SummaryAdapter.ViewHolder> {

private static final String TAG = "RecyclerViewAdapter";

//vars
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mAddress = new ArrayList<>();
private ArrayList<Integer> mRatings = new ArrayList<>();
private ArrayList<Float> mDistance = new ArrayList<>();

private Context mContext;

public SummaryAdapter(Context context, ArrayList<String> name, ArrayList<String> address , ArrayList<Integer> ratings , ArrayList<Float> distance  ) {
    this.mNames = name;
    this.mAddress = address;
    this.mRatings = ratings;
    this.mDistance = distance;

    mContext = context;

}



@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.summaryadapter, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {




    holder.name.setText(mNames.get(position));
    holder.address.setText(mAddress.get(position));
    holder.distance.setText("Distance: "+mDistance.get(position)+"meters");


    Toast.makeText(mContext,mImage.toString(),Toast.LENGTH_LONG).show();


    float  w = 0;
    try {
        w = new Float(mRatings.get(position));
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }


    holder.rtnbar.setRating(w);




}

@Override
public int getItemCount() {
    return mNames.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {


    TextView name,address,distance;
    RatingBar rtnbar;
    ImageView img;
    View mView;

    public ViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        address = itemView.findViewById(R.id.addresslist);
        name = itemView.findViewById(R.id.namelist);
        distance = itemView.findViewById(R.id.distancelist);
        img=itemView.findViewById(R.id.imagelist);
        rtnbar=itemView.findViewById(R.id.ratinglist);
    }
}

}

Question, how am i going to switch my array list items in to a custom class where in ill put on my array list like names,rating etc.

Create a class like this:

public class Person implements Comparable<Person> {
    private String mName;
    private String mAddress;
    private int mRating;
    private int mDistance;

    Person(String name, String address, int rating, int distance) {
        this.mName = name;
        this.mAddress = address;
        this.mRating = rating;
        this.mDistance = distance;
    }

    @Override
    public int compareTo(Person p) {
        return -Integer.valueOf(mRating).compareTo(p.mRating);
    }
}

and store all your data in 1 array persons of Person objects. Then you sort the array: Arrays.sort(persons); and use it in your adapter.

Take one class define all the variable like rating,name ,etc and that class pass into list and that list pass into adapter.. after that if your rating value as long then perfrom decending order sorting like below ..

        Collections.sort(indexResponsesList, new Comparator<UserData>() {
        @Override
        public int compare(UserData userData, UserData t1) {
            Long idea1 = new Long(userData.getCreatedAt());// here pass rating value.
            Long idea2 = new Long(t1.getCreatedAt());// here pass rating value.
            return idea2.compareTo(idea1);
        }
    });
    if (indexItemAdapter != null)
        indexItemAdapter.notifyDataSetChanged();

anb if integer then replace Long data type as integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM