user1330645
user1330645

Reputation:

Pass Integers and Strings trough Activities in Android?

How can I use Integers and Strings from ione Activity in an other?

Thanks

Upvotes: 1

Views: 160

Answers (2)

stefan bachert
stefan bachert

Reputation: 9608

It would be much easier to set values directly in intent

Intent supports putExtra (Name, Value);

        Intent intent = new Intent(Search.this, SearchResults.class);  
        EditText txt1 = (EditText) findViewById(R.id.edittext);
        EditText txt2 = (EditText) findViewById(R.id.edittext2);

        intent.putExtra("name", txt1.getText().toString());
        intent.putExtra("state", Integer.parseInt(txt2.getText().toString()));  

        startActivity(intent);  

....

      getIntent().getStringExtra("name"); 
      getIntent().getIntExtra("state", 0); // default 

http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20android.os.Bundle%29

Upvotes: 4

Ahmad
Ahmad

Reputation: 72533

In Activity 1:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

    Button search = (Button) findViewById(R.id.btnSearch);
    search.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            Intent intent = new Intent(Search.this, SearchResults.class);  
            Bundle b = new Bundle(); 

            EditText txt1 = (EditText) findViewById(R.id.edittext);
            EditText txt2 = (EditText) findViewById(R.id.edittext2);

            b.putString("name", txt1.getText().toString());
            b.putInt("state", Integer.parseInt(txt2.getText().toString()));  

            //Add the set of extended data to the intent and start it
            intent.putExtras(b);
            startActivity(intent);  
        }

    });
}

In the receiving Activity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_results);

    Bundle b = getIntent().getExtras(); 
    int value = b.getInt("state", 0);
    String name = b.getString("name");

    TextView vw1 = (TextView) findViewById(R.id.txtName);
    TextView vw2 = (TextView) findViewById(R.id.txtState);

    vw1.setText("Name: " + name);
    vw2.setText("State: " + String.valueOf(value));
}

But next Time search on SO before posting such a basic question. There are a lot of similar Questions out there.

Upvotes: 3

Related Questions