user2465510 user2465510 - 4 months ago 10
Android Question

Confused what is wrong with Intent constructor

I'm trying to create a button that opens a second activity. I've looked over the tutorials that I could find on Intents, and I've though I was following them correctly, but clearly I'm not.

NewScreenActivity is a completely blank activity. What is wrong with the Intent constructor and how can I do it correctly?

//NewScreenActivity in same package
package com.example.intri.firstexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

TextView userText;
Button buttonToNewScreen;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userText = (TextView) findViewById(R.id.userText);
buttonToNewScreen = (Button) findViewById(R.id.buttonToNewScreen);
userText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = userText.getText().toString();
Intent toNewScreen = new Intent(this, NewScreenActivity.class);

}
});
}
}


Thanks

Answer
userText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = userText.getText().toString();
                Intent toNewScreen = new Intent(this, NewScreenActivity.class);

            }
        });

You cannot use "this" in new Intent() in this case, because "this" refers to the new OnClickerListener anonymous class. Instead of "this" you should call something like getApplicationContext(). If you want to refer to your activity, write a method named openNewActivity() (or something like that) and start it from there.

Comments