Question

I am new to java and android. Here I am trying to set up my onclicklistener so when clicked, it will show another activity, i.e. ActivityB.class. The problem is with Intent i = new Intent(context, ActivityB.class); I am not sure what to put there for context. I tried to use this and context, and both are wrong.

Could you please kindly explain when and why I should use this and when to use other terms for the context?

public class MainActivity extends Activity {

Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b = (Button) findViewById(R.id.button1);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(context, ActivityB.class);
            startActivity(i);
            }
        }); 

}
Was it helpful?

Solution

Change the code to.

b.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i = new Intent(MainActivity.this, ActivityB.class);
        startActivity(i);
        }
    }); 

As you need to pass context while using intent.

OTHER TIPS

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
    startActivity(new Intent(MainActivity.this, ActivityB.class));
    }
}); 

Fastest method! Hope it helps! :D

1) Replace context with getApplicationContext()

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
  Intent intent = new Intent(getApplicationContext(),ActivityB.class);

           startActivity(intent);

    }
}); 

2) Replace context with MainActivity.this

button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
  Intent intent = new Intent(MainActivity.this,ActivityB.class);

           startActivity(intent);

    }
}); 

Hope it will help you!

Try this..

If you declare ActivityB.class in manifest this should work.

Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top