Search Bar

cara reload data setelah aksi hapus diandroid studio menggunakan recyclerview







disini saya akan berbagi bagaimana cara agar list dari data load mysql server kereload saat menghapus salah satu data di android studio.


berikut sisipkan kode pada baris aksi/file anda, contohnya pada saat load data hapus. berikut sourcenya :



                                mItems.remove(getAdapterPosition());
                                notifyItemRemoved(getAdapterPosition());
                                notifyItemRangeChanged(getAdapterPosition(),mItems.size());

Penjelasan dari source diatas. mItems adalah list dari deklarasi model data anda.
kemudian baris kedua adalah untuk menghilangkan data yang sudah dihapus.
dan baris terakhir mencari range terbaru dari data tersebut atau data yang belum dihapus.


 Berikut class,adapter dan layout contohnya :

CLASS :

public class Menu_pengumuman extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener  {
    RecyclerView mRecyclerview;
    RecyclerView.Adapter mAdapter;
    RecyclerView.LayoutManager mManager;
    List<ModelData> mItems;
    Button btnInsert, btnDelete;
    ProgressDialog pd;
    private SharedPreferences prefssatu;
    private SharedPreferences prefpwd;
    private SharedPreferences preftahunn;
    public static final String TAHUNN = "taun_preff";
    public static final String KEY_TAHUNN = "key_tahunn";
    private EditText ambilnidn,ambilpwd;
    private TextView sks;
    private ArrayList<Category> tahunlist;
    private ProgressDialog pDialog;
    private Spinner tahunspinner;
    private EditText kodetahun;
    private static final String TAG_MESSAGE = "message";
    private ImageView langit;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView jadwalid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.p_menupengumuman);
        // Inflate the layout for this fragment

        mRecyclerview = (RecyclerView) findViewById(R.id.recyclerviewTemp);
        jadwalid=(TextView)findViewById(R.id.jadwalid);
//        btnInsert = (Button) findViewById(R.id.btn_insert);
//        btnDelete = (Button) findViewById(R.id.btn_delete);
        pd = new ProgressDialog(Menu_pengumuman.this);
        mItems = new ArrayList<>();
        mManager = new LinearLayoutManager(Menu_pengumuman.this, LinearLayoutManager.VERTICAL,false);
        mRecyclerview.setLayoutManager(mManager);
        mAdapter = new Adapter_menupengumuman(Menu_pengumuman.this,mItems);
        mRecyclerview.setAdapter(mAdapter);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setEnabled(false);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.a, R.color.b, R.color.c, R.color.d);

        Intent data = getIntent();
        final int update = data.getIntExtra("update", 0);
        String jadwalidnya = data.getStringExtra("jadwaid");
        if (update == 1) {
            jadwalid.setText(jadwalidnya);
        } else {

        }




        swipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        swipeRefreshLayout.setRefreshing(true);
                                        loadJson();
                                    }
                                }
        );

    }
    private void loadJson()
    {
//        pd.setMessage("Mengambil Data");
//        pd.setCancelable(false);
//        pd.show();
        String jwd=jadwalid.getText().toString();
        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.GET, "URL_ANDA",null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        swipeRefreshLayout.setRefreshing(false);
//                        pd.cancel();
//                        langit.setVisibility(View.GONE);
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNamaMK(data.getString("judul"));
                                md.setHari(data.getString("isi"));
                                md.setRuangID(data.getString("tanggal"));
                                md.setId_jadwal(data.getString("id"));




                                mItems.add(md);


                            } catch (JSONException e) {
                                e.printStackTrace();
                                System.out.println("data kosong");
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        swipeRefreshLayout.setRefreshing(false);
                        Toast.makeText(Menu_pengumuman.this, "Opss..cobalah lagi nanti", Toast.LENGTH_LONG).show();
//                        langit.setVisibility(View.VISIBLE);
                    }
                });
        MyApplication_p.getInstance().addToRequestQueue(reqData);
    }

    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(false);
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}



ADAPTER NYA :

public class Adapter_menupengumuman extends RecyclerView.Adapter<Adapter_menupengumuman.HolderData> {
    private List<ModelData> mItems;
    private Context context;
    private SharedPreferences prefssatu;
    private SharedPreferences prefpwd;
    public Adapter_menupengumuman(Context context, List<ModelData> items) {
        this.mItems = items;
        this.context = context;
    }
    @Override
    public Adapter_menupengumuman.HolderData onCreateViewHolder(ViewGroup parent, int viewType) {
        View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.p_listmenupengumuman, parent, false);
        Adapter_menupengumuman.HolderData holderData = new Adapter_menupengumuman.HolderData(layout);

        return holderData;
    }
    @Override
    public void onBindViewHolder(Adapter_menupengumuman.HolderData holder, int position) {
        ModelData md = mItems.get(position);
        holder.judul.setText(md.getNamaMK());
        holder.tanggal.setText(md.getRuangID());
        holder.isi.setText(md.getHari());
        holder.idjadwal.setText(md.getId_jadwal());

        holder.md = md;

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

    class HolderData extends RecyclerView.ViewHolder {
        TextView judul, isi, tanggal, idjadwal, pwd, user;
        Spinner kehadiran;
        ImageView delete;
        Button detail, tambah;
        ModelData md;
        ProgressDialog pd;
        private SharedPreferences prefssatu;
        private SharedPreferences prefpwd;

        public HolderData(View view) {
            super(view);
            judul = (TextView) view.findViewById(R.id.hari);
            tanggal = (TextView) view.findViewById(R.id.ruang);
            isi = (TextView) view.findViewById(R.id.mk);
            delete = (ImageView) view.findViewById(R.id.delete);
            idjadwal = (TextView) view.findViewById(R.id.id);
            pwd = (TextView) view.findViewById(R.id.pwd);
            user = (TextView) view.findViewById(R.id.user);
            pd = new ProgressDialog(context);

            prefssatu = context.getSharedPreferences(
                    Login.SATU,
                    Context.MODE_PRIVATE +
                            Context.MODE_PRIVATE | Context.MODE_PRIVATE);
            prefpwd = context.getSharedPreferences(
                    Login.Pwd,
                    Context.MODE_PRIVATE +
                            Context.MODE_PRIVATE | Context.MODE_PRIVATE);
            user.setText(prefssatu.getString(
                    Login.KEY_SATU, "NA"));
            pwd.setText(prefpwd.getString(
                    Login.key_pwd, "NA"));

            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                   delete();
                }
            });
        }
        public void delete() {
            pd.setMessage("Menyimpan Data");
            pd.setCancelable(false);
            pd.show();
            StringRequest sendData = new StringRequest(Request.Method.POST,
                    "URL_ANDA",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            pd.cancel();
                            try {
                                JSONObject res = new JSONObject(response);
                                Toast.makeText(context, "" + res.getString("message"), Toast.LENGTH_SHORT).show();
                                mItems.remove(getAdapterPosition());
                                notifyItemRemoved(getAdapterPosition());
                                notifyItemRangeChanged(getAdapterPosition(),mItems.size());

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            pd.cancel();
                            Toast.makeText(context, "Gagal Hapus Data", Toast.LENGTH_SHORT).show();
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String, String> map = new HashMap<>();
                    String id = md.getId_jadwal();
                    map.put("id", id);
                    map.put("dosenid", user.getText().toString());
                    map.put("pwd", pwd.getText().toString());
                    System.out.println(id);

                    return map;
                }
            };
            MyApplication_p.getInstance().addToRequestQueue(sendData);
        }
        public void cek() {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);
            alertDialogBuilder.setTitle("Delete");
            alertDialogBuilder
                    .setMessage("Apakah anda yakin ingin menghapus?")
                    .setCancelable(false)
                    .setPositiveButton("Iya", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            delete();
                        }
                    })
                    .setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }

    }

}



Berikut screenshootnya :



Post a Comment

0 Comments