简体   繁体   中英

how to delete an item in recycleview from another activity?

I am working on an expense tracker app. When I click on item in recycleview, it takes me to another activity where I have two buttons: update and delete. The issue is I don't get the idea how to delete item from recycleview, which is in another activity, when delete button in that activity is pressed. Actually, I also searched and looked up other similar questions and answers on stack overflow however that didn't help me. If someone can help me on this, I will appreciate it greatly.

This is my code where I am passing the position of my item:

final int pos = holder.getAdapterPosition();
        holder.date.setText(MyModel.getDate());
        holder.note.setText(MyModel.getNote());
        holder.Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context,Update_transaction.class);
                i.putExtra("key",myViewsList.get(pos).getId());
                i.putExtra("pos",holder.getAdapterPosition());
                context.startActivity(i);

            }
        });

This is the code where I am retrieving the data in another activity:

Bundle bundle = getIntent().getExtras();
        Update_db = new DataSaver(this);
        if(bundle != null)
        {
            id = bundle.getString("key");
            pos = bundle.getString("pos");
            Toast.makeText(this, "pos : " + pos, Toast.LENGTH_SHORT).show();
        }

For interaction between activities, you can use the LocalBroadcastManager. You can send a broadcast from one activity and receive it in another.

Send broadcast

val intent = Intent("ACTION")
intent.putExtra("needUpdate", true)
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent)

Receive broadcast

1.Create a listener

val myBroadcastReceiver = object : BroadcastReceiver() {
   override fun onReceive(context: Context?, intent: Intent?) {
       println("Your value: " + intent?.getStringExtra("needUpdate"))
   }
}

Register

override fun onResume() {
   // …
   val filter = IntentFilter("ACTION")
   LocalBroadcastManager.getInstance(applicationContext).registerReceiver(myBroadcastReceiver, filter)
}

Cancel registration

override fun onPause() {
   // …
   LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(myBroadcastReceiver)
}

More details: https://developer.android.com/guide/components/broadcasts

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