Thomas Kowalski Thomas Kowalski - 5 months ago 75
Android Question

getIntent returning null

In android when I try to use the getIntent(); method in android, it returns null,which is causing the application to crash. Here is my code :

public class MainActivity extends AppCompatActivity {

public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText textbox = (EditText) findViewById(R.id.edit_message);
String message = textbox.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message.toString());
startActivity(intent);
}
}


This first activity calls the second:

public class DisplayMessageActivity extends AppCompatActivity {

Intent intent = getIntent();


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_mesage);

String message = "";

if (intent == null) {
Log.d("Intent", "Intent is null :(");
}

try {
message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
} catch (Exception e) {
Log.d("Message", "Message is null");
}


TextView textView = new TextView(this);
textView.setText(message);
textView.setTextSize(40);

RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
layout.addView(textView);
}
}


I don't understand why it returns null, since I call it myself using an intent that... is not null.

EDIT : I also tried to use something else than a constant for the key, like "message", rather than EXTRA_MESSAGE, it leads to the same result.

Answer

There are two causes of null . 1) if you had not declared activity in manifest.xml file in andorid . 2) You must use getIntent() inside oncreate() method ,the code for that thing is here :-

public class DisplayMessageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_mesage);

        Intent intent = getIntent();


        String message = "";

        if (intent == null) {
            Log.d("Intent", "Intent is null :(");
        }

        try {
            message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        } catch (Exception e) {
            Log.d("Message", "Message is null");
        }


        TextView textView = new TextView(this);
        textView.setText(message);
        textView.setTextSize(40);

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
        layout.addView(textView);
    }
}   
Comments