1

Could I pass a string to another activity in Android without using intents? I'm having troubles with intent extras... They don't always seem to work! So, is there any other way?

What I've tried with intents:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");

But it gets two kinds of string every time I start the activity. The first time is different from the other times. Can I pass that second activity any other things without using intents?

mange
  • 3,172
  • 18
  • 27
Amin Keshavarzian
  • 3,646
  • 1
  • 37
  • 38
  • 1
    Other than using `SharedPreferences` or a database to save the strings, the answer is no, there isn't another way. Also if you can't get things to work using the extras in the `Intent` used to start an `Activity` then you're doing something wrong - it's not the fault of the way `Intents` work. Post code and explain what is happening - the two lines you've shown tell us nothing. – Squonk Jun 24 '13 at 23:56
  • try using shared preferences. Check this out, it will help a lot. http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values – lolliloop Jun 25 '13 at 00:10
  • Squonk, the problem was, my code was over 2000 lines, so i couldn't share it here, but i asked it here cause i thought there might be better ways than using intent, which as you said is not true ... – Amin Keshavarzian Jun 28 '13 at 00:55

1 Answers1

5

There are other ways, but the Intent's extras are the way to go. They actually work fine always :) It's better to stay on this path and learn how to use the Intents right.

An example on sending a String to another activity:

    Intent intent = new Intent(this, SecondActivity.class);
    intent.putExtra("aKey", value);
    startActivity(intent);

and retrieving it in the second activity.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
    Intent i = getIntent();
    if (i.hasExtra("aKey")){
         String value = i.getStringExtra("aKey");   
    }
}

Just keep trying to get this right.

Plato
  • 2,338
  • 18
  • 21
  • thanks, I guess that IS the only way to go, and I have to get that right. the problem is, now that my code is really long and complicated it is very difficult to debug why intent is not working right and more importantly, why it doesn't work right only first time ! – Amin Keshavarzian Jun 25 '13 at 12:25