web-dev-qa-db-ja.com

RecyclerViewでデータを並べ替える方法

繰り返しのように見えるかもしれませんが、cardviewを含むリサイクラービューでデータを並べ替えるより良い方法を見つけることができません。

以下は私のメインアクティビティのrecyclerviewのスニペットです

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


    }

これが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);
    }
    }

そして最後にゲッターとセッターの方法

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

歩行時間でリストを並べ替えたい。誰かがこれで私を助けることができますか?

5
Devs

// Beanで同等のインターフェースを使用して、特定のフィールドと比較できます

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

比較したいフィールドを比較してください

編集済み-

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


}
6
Ashish Agrawal

より効率的なSortedListを実装できます。 SortedListは、サポートライブラリV7(Android.support.v7.util)で利用できます。ドキュメントに基づく:

SortedList.Callback.compare(Object、Object)メソッドを使用してアイテムの順序を保持し、バイナリ検索を使用してアイテムを取得します。

それはより効率的であり、ソートされたリストでの追加、挿入、および削除をより適切に制御できます。アダプターでリストをSortedListに切り替えて、3つのアダプターコールバックメソッド(compare()、areContentsSame()、areItemsSame())をオーバーライドするだけです。あなたはその使用法についてのより多くの詳細を見つけることができます ここ

1
Sagar