how to sort the data in RecyclerView

Devs picture Devs · Sep 14, 2015 · Viewed 23.5k times · Source

I might seems a repetition but i am really unable to find a better way to sort the data in recycler view containing cardview.

Below is the snippet of recyclerview in my mainactivity

 mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(linearLayoutManager);


    mAdapter = new PickUpPointAdapter(testData);
    mRecyclerView.setAdapter(mAdapter);
    mCardView=(CardView)findViewById(R.id.searchcard);


    mCardView.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {
            // item clicked
            Intent search = new Intent( AppController.getAppContext(), TabLayoutActivity.class);
            search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(search);
        }
    });

    Map<String,String> params = new HashMap<String,String>();
    JsonObjectRequest NearbyPickUpPointReq = new JsonObjectRequest (Request.Method.GET,url_searchNearBybusStopServlet,new JSONObject(params), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("Tag", response.toString());
            // hidePDialog();
            try {
                JSONArray obj1 = response.getJSONArray("pickuppoint");
                testData.clear();
                // Parsing json
                for (int i = 0; i < obj1.length(); i++) {


                    JSONObject obj = (JSONObject)obj1.get(i);
                    SearchResults srchresult = new SearchResults();
                    srchresult.setPickUpPoint(obj.getString("PickupPoint"));
                    srchresult.setRouteName(obj.getString("RouteName"));
                    srchresult.setLatitude(obj.getDouble("Latitude"));
                    srchresult.setLongitude(obj.getDouble("Longitude"));
                    srchresult.setWalkingTime(obj.getInt("WalkingTime"));
                    srchresult.setRoute2("-");
                    mapMarker( srchresult.getLatitude(), srchresult.getLongitude(),srchresult.getPickUpPoint());
                    String[] RouteArray = srchresult.getRouteName().split(",");
                    //  Log.e(TAG, "Error: " + RouteArray.length);
                    srchresult.setRoute1( RouteArray[0]);
                    if(RouteArray.length>1)
                        srchresult.setRoute2(RouteArray[1]);
                    testData.add(srchresult);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            // notifying list adapter about data changes
            // so that it renders the list view with updated data


            mAdapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //   VolleyLog.d(TAG, "Error: " + error.getMessage());
            // hidePDialog();

        }

    });

    // Adding request to request queue

    AppController.getInstance().addToRequestQueue(NearbyPickUpPointReq);


    }

Here is the customadapter

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

ArrayList<SearchResults> mItems;
public int TAG=0;


public PickUpPointAdapter(ArrayList<SearchResults> mItems) {
    this.mItems=mItems;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.nearby_busstop_list_layout, viewGroup, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
    final SearchResults routename = mItems.get(i);
    viewHolder.tv_pickuppointname.setText(routename.getPickUpPoint());
    viewHolder.tv_walkingtime.setText(String.valueOf(routename.getWalkingTime())+"min walk ");
    viewHolder.tv_allroutename.setText(routename.getRouteName());
    viewHolder.tv_route1.setText(routename.getRoute1());
    viewHolder.tv_route2.setText(routename.getRoute2());

    Log.e("TAG","i value="+ i);
   // if(i==mItems.size()-1)
      // viewHolder.seperator.setVisibility(View.INVISIBLE);
       viewHolder.mView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context context = v.getContext();
            Intent intent = new Intent(context,BusStopDetailsnew.class);
            intent.putExtra("pickup", routename.getPickUpPoint());
            intent.putExtra("route", routename.getRouteName());
            intent.putExtra("walk", routename.getWalkingTime());
            intent.putExtra("lat", routename.getLatitude());
            intent.putExtra("lon", routename.getLongitude());
            context.startActivity(intent);
        }
    });

}

@Override
public int getItemCount() {
    Log.e("TAG","item size"+ mItems.size());
    return mItems.size();

}

class ViewHolder extends RecyclerView.ViewHolder{


    public TextView tv_pickuppointname;
    TextView tv_walkingtime;
    TextView tv_allroutename;
    TextView tv_route1;
    TextView tv_route2;
    public View seperator;
    public View mView;

    public ViewHolder(View itemView) {
        super(itemView);
        mView=itemView;
        tv_pickuppointname = (TextView)itemView.findViewById(R.id.BusstopName);
        tv_walkingtime = (TextView) itemView.findViewById(R.id.walktime);
        tv_allroutename = (TextView) itemView.findViewById(R.id.allbusRoute);
        tv_route1 = (TextView) itemView.findViewById(R.id.RouteName1);
        tv_route2 = (TextView) itemView.findViewById(R.id.RouteName2);
        seperator=(View)itemView.findViewById(R.id.seperator);
    }
    }

And finally the getter and setters method

public class SearchResults {
private String PickUpPoint="";
private int WalkingTime=0;
private String RouteName = "";
private String Route1="";
private String Route2="";
private Double Latitude = null;
private Double Longitude = null;




//walking time
public int getWalkingTime() {
    return WalkingTime;
}

public void setWalkingTime(int WalkingTime) {
    this.WalkingTime = WalkingTime;
}

//Route1
public String getRoute1() {
    return Route1;
}

public void setRoute1(String Route1) {
    this.Route1 = Route1;
}

//Route2
public String getRoute2() {
    return Route2;
}

public void setRoute2(String Route2) {
    this.Route2 = Route2;
}

//PickUpPoint
public void setPickUpPoint(String PickUpPoint) {
    this.PickUpPoint = PickUpPoint;
}

public String getPickUpPoint() {
    return PickUpPoint;
}
//RouteName ArrayList
public void setRouteName(String RouteName) {
    this.RouteName = RouteName;
}

public String getRouteName() {
    return RouteName;
}
//Latitude
public void setLatitude(Double Latitude) {
    this.Latitude = Latitude;
}

public Double getLatitude() {
    return Latitude;
}
//Longitude
public void setLongitude(Double Longitude) {
    this.Longitude = Longitude;
}

public Double getLongitude() {
    return Longitude;
}
}

I want to sort the list according to the walking time. Can anyone help me with this?

Answer

Ashish Agrawal picture Ashish Agrawal · Sep 14, 2015

//you can use comparable interface in bean and compare with particular field

public class SearchResults implements Comparable{

    private int id;

    public int getId() {
        return id;
    }

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

    @Override
    public int compareTo(Object another) {
        if(((SearchDetail)another).getId() > id){
            return 1;
        }if(((SearchDetail)another).getId() == id){
            return 0;
        }else{
            return -1;
        }
        return 0;
    }
}

please compare that field to which you want to compare

Edited-

mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);


mAdapter = new PickUpPointAdapter(testData);
mRecyclerView.setAdapter(mAdapter);
mCardView=(CardView)findViewById(R.id.searchcard);


mCardView.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick(View v) {
        // item clicked
        Intent search = new Intent( AppController.getAppContext(), TabLayoutActivity.class);
        search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(search);
    }
});

Map<String,String> params = new HashMap<String,String>();
JsonObjectRequest NearbyPickUpPointReq = new JsonObjectRequest (Request.Method.GET,url_searchNearBybusStopServlet,new JSONObject(params), new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Log.d("Tag", response.toString());
        // hidePDialog();
        try {
            JSONArray obj1 = response.getJSONArray("pickuppoint");
            testData.clear();
            // Parsing json
            for (int i = 0; i < obj1.length(); i++) {


                JSONObject obj = (JSONObject)obj1.get(i);
                SearchResults srchresult = new SearchResults();
                srchresult.setPickUpPoint(obj.getString("PickupPoint"));
                srchresult.setRouteName(obj.getString("RouteName"));
                srchresult.setLatitude(obj.getDouble("Latitude"));
                srchresult.setLongitude(obj.getDouble("Longitude"));
                srchresult.setWalkingTime(obj.getInt("WalkingTime"));
                srchresult.setRoute2("-");
                mapMarker( srchresult.getLatitude(), srchresult.getLongitude(),srchresult.getPickUpPoint());
                String[] RouteArray = srchresult.getRouteName().split(",");
                //  Log.e(TAG, "Error: " + RouteArray.length);
                srchresult.setRoute1( RouteArray[0]);
                if(RouteArray.length>1)
                    srchresult.setRoute2(RouteArray[1]);
                testData.add(srchresult);
            }
        Collections.sort(testData);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // notifying list adapter about data changes
        // so that it renders the list view with updated data


        mAdapter.notifyDataSetChanged();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //   VolleyLog.d(TAG, "Error: " + error.getMessage());
        // hidePDialog();

    }

});

// Adding request to request queue

AppController.getInstance().addToRequestQueue(NearbyPickUpPointReq);


}