napster
napster

Reputation: 717

can we call startActivityForResult from adapter?

is it possible to have method onActivityResume within adapter & call startActivityForResult?

Upvotes: 40

Views: 37108

Answers (4)

Apu Pradhan
Apu Pradhan

Reputation: 101

//First Do
public Activity context;
public int REQUEST_CODE = 111;

public Adapter(Activity context, Data data) {
    this.context = context;
}

///Second Do
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, NextActivity.class);
            context.startActivityForResult(intent, REQUEST_CODE);
        }
    });
}

If you follow this code then you don't need to write it - ((Activity) context) - every time, before - .startActivityForResult(intent, REQUEST_CODE); - when you use startActivityForResult in Adapter.

Upvotes: 3

Ali Nawaz
Ali Nawaz

Reputation: 2500

Offcource...

((Activity) context).startActivityForResult(intent, 911);

Caution !!

Only pass MyActivity.this from activity to adapter as context.

Only pass getActivity(); from fragment to adapter as context.

Upvotes: 2

eugeneek
eugeneek

Reputation: 1430

Not necessarily pass to pass context in adapter's constructor. You can get context from parent ViewGroup. Sample for RecyclerView adapter:

 Context mContext;
 @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        ...
    }

Sample for ListView BaseAdapter

 Context mContext;
 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        mContext = parent.getContext();
        ...
}

And use it wherever you want

((Activity) mContext).startActivityForResult(intent, REQUEST_FOR_ACTIVITY_CODE);

Upvotes: 9

user936414
user936414

Reputation: 7634

Yes. Just pass the context of the activity to the adapter in the adapter's constructor (here stored as mContext). In getView, just call

((Activity) mContext).startActivityForResult(intent,REQUEST_FOR_ACTIVITY_CODE);

Upvotes: 104

Related Questions