Reputation: 27
This is in Adapter.Java
public void onClick(View v) {
String name=listItemData.get(i).getName();
Intent intent = Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("NAME", name);
}
I have now idea how to use MainActivity.this when I'm not in MainActivity class..
Upvotes: 0
Views: 100
Reputation: 6622
Try following code.
Solution 1
You have to pass context
while you initialized Adapter in MainActivity
.
In MainActivity.this
:
XyzAdapter adapter = new XyzAdapter(MainActivity.this, .. ..)
In your Adapter
:
private Context mContext;
public XyzAdapter(Context context .. ..){
mContext = context;
}
And then you can do like below:
public void onClick(View v) {
String name=listItemData.get(i).getName();
Intent intent = Intent(mContext, SecondActivity.class);
intent.putExtra("NAME", name);
mContext.startActivity(intent);
}
Solution 2
Another option is interface
Create one interface
like below:
public interface AdapterInterface {
public void buttonPressed();
}
Now in your adapter:
AdapterInterface buttonListener;
public XyzAdapter(Context context, AdapterInterface buttonListener)
{
super(context,c,flags);
this.buttonListener = buttonListener;
}
public void onClick(View v) {
buttonListener.buttonPressed()
}
In your Activity
:
AdapterInterface buttonListener;
public MainActivity extends AppCompactActivity implements AdapterInterface{
in onCreate
buttonListener = this;
XyzAdapter adapter = new XyzAdapter(MainActivity.this, buttonListener .. ..)
@Override
public void buttonPressed(){
// here you have to do once your click perform
}
Upvotes: 1
Reputation: 15
You can have a member variable of type Activity
in your Adapter class (e.g. private Activity mActivity;
) and pass your MainActivity instance to your Adapter class in the constructor of your Adapter class and assign it to mActivity
. Some thing like this:
public Adapter(Activity activity) {
this.mActivity = activity;
}
Then in your onClick
method:
public void onClick(View v) {
String name=listItemData.get(i).getName();
Intent intent = new Intent(mActivity, SecondActivity.class);
intent.putExtra("NAME", name);
mActivity.startActivity(intent);
}
Upvotes: 0