I am trying to start a new activity from a custom onclick listener. But its unable to access MainActivity instance from onclick listener. Also, its showing wrong constructor for intent. Here is my code:
public class ChartClickListener implements OnClickListener {
private String ChartLink;
public ChartClickListener(String chartLink){
this.ChartLink=chartLink;
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
startActivity(intent);
}
}
Thanks for the help in advance.
Modify your code as:
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(view.getContext(),ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
startActivity(intent);
}
try like this
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(view.getContext(),ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
view.getContext().startActivity(intent);//Changed Here
}
Hope It will work
pass activity context to custom onclick listener and use that context to startactivity
public class ChartClickListener implements OnClickListener {
private String ChartLink;
Context c;
public ChartClickListener(String chartLink,Context context){
this.ChartLink=chartLink;
this.c=context;
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(c,ChartImageActivity.class);
intent.putExtra("chartLink", ChartLink);
c.startActivity(intent);
}
}
set setOnClickListener as
ChartClickListener chartclicklistener=new ChartClickListener("chartLink",MainActivity.this);
b.setOnClickListener(chartclicklistener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With