Ramesh Ramesh - 5 months ago 24
Android Question

How Can I use Same Adapter of a GridView on Different activities

Let say I have two Activities, Activity A and Activity B.

Activity A displays a list of images using the Adapter Z.

When user clicks on any image in Activity A, they will be taken to Activity B to show the full image. I'm passing image path and grid position to Activity using Intent.

Now in Activity B, I place a delete button which should delete the imagepath from the gridview adapter.

Problem is:
How can I access the Activity A adapter in activity B to call remove(position) method in my adapter.

So I can call notifyDataSetChanged in onResume of Activity A to update the gridview images.

Activity A

MyGridView = (GridView) findViewById(R.id.gridview);
adapter = new MyAdapter(this);
MyGridView .setAdapter(adapter );

Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
fullImageActivity.putExtra("position", position);
fullImageActivity.putExtra("path", mediaPath);
startActivity(fullImageActivity);


Activity B

Intent i = getIntent();
// I'm getting position and path from setOnItemClickListener
position = i.getExtras().getInt("position");
path = i.getExtras().getString("path");

// I want to remove path from my adapter after clicking delete button in Activity B


Adapter

public ArrayList<String> images;

public void remove(int position){
images.remove(position);
}

Answer

use startActivityForResult.

Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
    fullImageActivity.putExtra("position", position);
    fullImageActivity.putExtra("path", mediaPath);

   startActivityForResult(fullImageActivity, 2);

check if deleted at particular position in Activity B . here I override onBackPressed() (For Ex.) method

public void onBackPressed(){

   super.onBackPressed()

Intent intent=new Intent();  
                    intent.putExtra("isdeleted",true);  
intent.putExtra("pos",position);
                    setResult(2,intent);  
                    finish();
}

Handle it in onActivityResult in Activity A.

 @Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
                 super.onActivityResult(requestCode, resultCode, data);  
                  // check if the request code is same as what is passed  here it is 2  
                   if(requestCode==2)  
                         {  
                            if(data.getBooleanExtra("isdeleted")){   
                           remove from position array and notify dataset change. // pos = data.getIntExtra("pos") 
                            }
                         }  
     } 

Sorry for TYPO.

Comments