Search code examples
javaandroidsetcontentview

Android: how to pass multiple values to setContentView() method from an activity class?


I have some problems passing and displaying values from the MainActivityClass to another MyActivityClass. So I learned here how to pass values from one class to another. Here's the method of MainActivity class which contains the intent to the other activtiy:

Intent intent = new Intent(this, AddAptActivity.class);
Bundle extras = new Bundle();

EditText editText = (EditText) findViewById(R.id.edit_address);
String message = editText.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.edit_name);
String message2 = editText2.getText().toString();

extras.putString(EXTRA_MESSAGE, message);
extras.putString(EXTRA_MESSAGE1, message2);

intent.putExtras(extras);
startActivity(intent);

and then in MyActivityClass receiving the values:

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

    Intent intent = getIntent();

    Bundle extras = intent.getExtras();

    String message = extras.getString(MainActivity.EXTRA_MESSAGE);
    String message2 = extras.getString(MainActivity.EXTRA_MESSAGE2);

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

    TextView textView2 = new TextView(this);
    textView2.setTextSize(40);
    textView2.setText(message2);

    setContentView(textView, textView2); 
}

but the setContentView() method doesn't want to accept more than one value. How can I display the other value in another textview and then display it???

I think I don't understand how to display values with setContentView... Please help me, as I am new in Android programming (just finished the 1st tutorial one week ago).


Solution

  • You can use a ViewGroup such as a LinearLayout or RelativeLayout then add TextViews to the same and then setContenView(linearlayout);

     LinearLayout ll = new LinearLayout(this); 
     ll.setOrientation(LinearLayout.VERTICAL);
     TextView textView = new TextView(this);
     TextView textView2 = new TextView(this);
     ll.addView(textView);
     ll.addView(textView2);
     setContenView(ll);