-1

Possible Duplicate:
Android global variable

I am working with an Android project. I have two activities. I am designing a file uploader. The first activity is to choose a file. The second one is used to uploading the selected file.

How can i make a global variable So the file path selected in the first activity can be used by the second activity.

Is SharedPreference suitable for this or what's the best solution for this?

Community
  • 1
  • 1
Pushpendra Kuntal
  • 6,118
  • 20
  • 69
  • 119

5 Answers5

3

You could do this from your file chooser activity:

Intent uploadActivity = new Intent(MyApp.this, UploadActivity.class);
uploadActivity.putExtra("filePath", filePath);
startActivity(uploadActivity);

And then read the extras from your UploadActivity:

String filePath = getIntent().getStringExtra("filePath");
Nicos
  • 303
  • 2
  • 19
2

Yes SharedPreference would be what i would suggest.

Just Map the File path to a key like this:

  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putString("filePath" filePath(Variable));
coder_For_Life22
  • 26,645
  • 20
  • 86
  • 118
2

SharedPreferences is one way of doing this. Another one is creating a Application class. You can access the singleton instance of Application class and share the data across the activities.

Pavan
  • 711
  • 2
  • 6
  • 17
2

You can use one of the below mentioned options

  1. Pass required data from one activity to other via intents (Preferred)
  2. Use shared preferences
Basavraj
  • 64
  • 2
1

as per give solution by vineet or pass result from one activity to second through

Intent i = new Intent(this, ToClass.class);
    i.putExtra("fname", Name_temp);
startActivity(i);

second side:

     Intent i1 = getIntent();
int lastscore4 =  i1.getIntExtra("fname", 1);
Nikunj Patel
  • 21,853
  • 23
  • 89
  • 133