Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we call startActivityForResult from adapter?How to get the response?

Tags:

android

is it possible to have method startActivtyForResult within an adapter?Then how to get the response? Where to execute the call back function?

like image 266
user Avatar asked Nov 16 '13 07:11

user


People also ask

Can we call startActivityForResult from adapter?

Yes. You can call startactivityforresult() from adapter.

How can I get result of startActivityForResult?

First you use startActivityForResult() with parameters in the first Activity and if you want to send data from the second Activity to first Activity then pass the value using Intent with the setResult() method and get that data inside the onActivityResult() method in the first Activity .


1 Answers

Yes, it's possible. You need a reference for the Context in the adapter and call the activity:

Intent intent = new Intent(context, TargetActivity.class); ((Activity) context).startActivityForResult(intent, REQUEST_FOR_ACTIVITY_CODE); 

Beware that context must be an activity context or this code will fail.

You get the result in the enclosing activity using onActivityResult as usual.

So, for example:

In your adapter:

MyAdapter(Context context) {     mContext = context; }  public View getView(int position, View convertView, ViewGroup parent) {     …     open.setOnClickListener(new View.OnClickListener() {         @Override         public void onClick(View v) {             …             Activity origin = (Activity)mContext;             origin.startActivityForResult(new Intent(mContext, SecondActivity.class), requestCode);         }        });     … }  public  void onActivityResult(int requestCode, int resultCode, Intent data) {     Log.d("MyAdapter", "onActivityResult"); } 

In your second activity, do as usual with setResult and finish.

In your main activity, capture the result and pass to the adapter callback:

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     mAdapter.onActivityResult(requestCode, resultCode, data); } 
like image 99
Douglas Drumond Kayama Avatar answered Sep 23 '22 01:09

Douglas Drumond Kayama