从适配器重新加载片段/活动(或recyclerview)

时间:2016-04-19 20:38:28

标签: android android-recyclerview android-adapter

我有一个简单的应用程序,片段和活动托管一个recyclerview,vith数据从数据库,我有一个删除功能,但我不能刷新回收器视图,我尝试了一些方法,但因为我的longclick cardview是在适配器上,我无法使其正常工作

这是我的适配器:

public class LoyaltyCardRVAdapter extends RecyclerView.Adapter<LoyaltyCardRVAdapter.CardViewHolder> {

...

public LoyaltyCardRVAdapter(Context context, ArrayList<LoyaltyCardObject> cards) {
    this.context = context;
    this.cards = cards;
}

public void setData(ArrayList<LoyaltyCardObject> cards) {
    this.cards = cards;
}

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

@Override
public void onBindViewHolder(CardViewHolder holder, int position) {
    LoyaltyCardObject card = cards.get(position);

    holder.marque.setText(card.getMarque());
    ...
}

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


/**
 * Cette classe initialise chaque cardview avec l'object correspondant
 */
public static class CardViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
    CardView cardView;
    TextView mail, marque, code;
    ArrayList<LoyaltyCardObject> cards = new ArrayList<>();
    Context context;
    AlertDialog.Builder alertDialogBuilder;
    RequestQueue requestQueue;
    ImageView logo;

    public CardViewHolder(View view, Context context, ArrayList<LoyaltyCardObject> cards) {
        ...
    }

    @Override
    public void onClick(View v) { //Gère le clique sur une cardview

        int position = getAdapterPosition();
        LoyaltyCardObject card = this.cards.get(position);
        Toast.makeText(context, "Codebarre pour la carte " + card.getMarque(), Toast.LENGTH_SHORT).show();
        Intent intentcode = new Intent(this.context.getApplicationContext(), LoyaltyCardShowCodeActivity.class);
        intentcode.putExtra("code", card.getCode());
        this.context.startActivity(intentcode);
    }

    @Override
    public boolean onLongClick(View v) {

        int position = getAdapterPosition();
        final LoyaltyCardObject card = this.cards.get(position);
        requestQueue = Volley.newRequestQueue(context);


        alertDialogBuilder
                .setTitle("Effacer")
                .setMessage("Voulez-vous vraiment effacer cette carte ?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                        StringRequest request = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        Toast.makeText(context, "Carte n°" + card.getCode() + " chez " + card.getMarque() + " effacé", Toast.LENGTH_SHORT).show();
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.i("MYAPP", "onErrorResponse()");
                            }
                        }) { // Paramètres de la requete
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                Map<String, String> parameters = new HashMap<String, String>();
                                parameters.put("mail", card.getMail());
                                parameters.put("code", card.getCode());
                                return parameters;
                            }
                        };
                        requestQueue.add(request);
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                })
                .setIcon(R.drawable.ic_error_outline_black_24dp)
                .show();
        return false;
    }
}

}

我的片段在这个例子中:

public class LoyaltyCardListFragment extends android.support.v4.app.Fragment {

LoyaltyCardRVAdapter adapter;
ProgressDialog dialog;
TextView addCards;
UserSharedPreferences userSharedPreferences;
ArrayList<LoyaltyCardObject> cards = new ArrayList<LoyaltyCardObject>();
String url = ServerURL.CARD_GET;
AlertDialog.Builder builder;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.loyaltycard_list_fragment, container, false);
    RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.rv_cards);
    recyclerView.setHasFixedSize(true);
    adapter = new LoyaltyCardRVAdapter(getActivity(), cards);
    LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(llm);
    recyclerView.setAdapter(adapter);

    addCards = (TextView) rootView.findViewById(R.id.addCards);

    adapter.setData(cards);

    dialog = new ProgressDialog(getActivity());
    dialog.setMessage("Chargement");
    dialog.setCancelable(true);
    showDialog();

    addCards.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Ajout de carte");
            builder.setMessage("Comment ajouter ?");
            builder.setPositiveButton("Scanner", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Log.i("Alert", "YES");
                    Intent intent = new Intent(getActivity(), LoyaltyCardAddWithScannerActivity.class);
                    startActivity(intent);
                }
            });
            builder.setNegativeButton("Manuel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Log.i("Alert", "NO");
                    startActivity(new Intent(getActivity(), LoyaltyCardAddActivity.class));
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
    });

    getAndInitData();

    return rootView;
}

public void getAndInitData() { //Recupère les cartes de l'utilisateur et les affiches dans un recycler view sous forme de cardview

    userSharedPreferences = new UserSharedPreferences(getActivity());
    final UserObject user = userSharedPreferences.getLoggedInUser();

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url + user.mail,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    try {
                        for (int i = 0; i < response.length(); i++) {
                            JSONObject object = response.getJSONObject(i);
                            LoyaltyCardObject card = new LoyaltyCardObject();
                            card.setMail(object.getString("mail"));
                            card.setMarque(object.getString("marque"));
                            card.setCode(object.getString("code"));

                            cards.add(card);
                        }
                        hideDialog();
                        adapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            View view = getView();
            LinearLayout ll = (LinearLayout) view.findViewById(R.id.cardlist);
            Log.d("ERROR!!!", error.toString());
            hideDialog();
            Snackbar snackbar = Snackbar  //Si l'utilisateur n'a pas de carte de fidelite, affiche un snackbar qui propose d'ajouter une carte
                    .make(ll, "Aucune carte", Snackbar.LENGTH_LONG)
                    .setAction("Ajouter", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            builder = new AlertDialog.Builder(getActivity());
                            builder.setTitle("Ajout de carte");
                            builder.setMessage("Comment ajouter ?");
                            builder.setPositiveButton("Scanner", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    Log.i("Alert", "YES");
                                    Intent intent = new Intent(getActivity(), LoyaltyCardAddWithScannerActivity.class);
                                    startActivity(intent);
                                }
                            });
                            builder.setNegativeButton("Manuel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    Log.i("Alert", "NO");
                                    startActivity(new Intent(getActivity(), LoyaltyCardAddActivity.class));
                                }
                            });
                            AlertDialog alertDialog = builder.create();
                            alertDialog.show();
                        }
                    });
            snackbar.show();
        }
    });
    AppController.getInstance().getRequestQueue().add(jsonArrayRequest);
}

public void showDialog() {
    if (!dialog.isShowing())
        dialog.show();
}

public void hideDialog() {
    if (dialog.isShowing())
        dialog.hide();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    dialog.hide();
    dialog.dismiss();
}

}

2 个答案:

答案 0 :(得分:0)

当包含适配器的数据发生更改时,可以调用一种方法。例如:

  1. 创建ListView,RecyclerView,...
  2. 创建适配器。
  3. 将适配器设置为ListView,....
  4. 完成工作(更改数据,删除数据,等等......)
  5. 现在,如果要刷新链接到适配器的视图中的实际信息,请调用方法:

    adapter.notifyDataSetChanged();
    

    这将使用正确且最新的信息更新您的观看信息。

    希望有所帮助!

答案 1 :(得分:0)

从RecyclerView中删除项目有4个步骤

list.remove(position);
recycler.removeViewAt(position);
mAdapter.notifyItemRemoved(position);                 
mAdapter.notifyItemRangeChanged(position, list.size());

您必须在您的活动/片段代码中执行此操作。