Pramith S
Pramith S

Reputation: 13

how to get and display the EXTRA_TEXT in an activity that is send by another activity with its Intent?

I made a Login activity and on successful login, I sent the username with Intent as EXTRA_TEXT to start Home activity. But my app is crashing when i tried to get the username and display it in TextView.

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.home);
    TextView textView = new TextView(getApplication().getApplicationContext());
    Intent intent = getIntent();
    String user = intent.getStringExtra(Login.EXTRA_TEXT);
    textView.setText(user);
    relativeLayout.addView(textView);
    setContentView(R.layout.activity_home);
}

Upvotes: 1

Views: 75

Answers (3)

Anitha Manikandan
Anitha Manikandan

Reputation: 1170

      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    //View should be set first
        setContentView(R.layout.activity_home);


        RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.home);
        TextView textView = new TextView(getApplication().getApplicationContext());
        Intent intent = getIntent();
        String user = intent.getStringExtra(Login.EXTRA_TEXT);
        textView.setText(user);
///////////////modified/////////////////////////////
        relativeLayout.addView(textView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
    }

Upvotes: 1

Eduardo Ewerton
Eduardo Ewerton

Reputation: 11

setContentView(R.layout.activity_home);

is when you link your layout to your class

RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.home);

is when you try to reach RelativeLayout from your layout.

If you don't link your layout to your class, how can you reach your RelativeLayout?

Link your layout to your class first and after call your component, in this case, RelativeLayout.

Upvotes: 1

JoeyJubb
JoeyJubb

Reputation: 2321

You need to do

setContentView(R.layout.activity_home);

before

findViewById(R.id.home)

Upvotes: 0

Related Questions