Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting intent from onclicklistener

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.

like image 925
Sourabh Avatar asked Oct 19 '13 08:10

Sourabh


3 Answers

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);
    }
like image 159
Anchit Mittal Avatar answered Nov 01 '22 01:11

Anchit Mittal


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

like image 23
Amit Gupta Avatar answered Nov 01 '22 02:11

Amit Gupta


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);
like image 4
Shijil Avatar answered Nov 01 '22 01:11

Shijil