Reputation: 1973
I have two activity in my app say A & B. Activity A needs the data Stored by B (currently Shared Preferences). But to query the data in Activity A i need the context of B. But, Activity A does not have any way to get the context of Activity B(according to the application flow). Is there any way around or using database will be a better option??
Upvotes: 0
Views: 500
Reputation: 40734
Why do you need Activity A's context? You could just use getApplicationContext().getSharedPreferences()
within each activity to store/retrieve SharedPreferences.
Also, depending on what data you're storing, you may want to look into using an Intent to pass data from Activity A to Activity B. For example, to start Activity B from A you would use something like this:
Intent i = new Intent(getApplicationContext(), ActivityB.class);
i.putExtra("someIntData",1234);
i.putExtra("someStringData","yourdata");
startActivity(i);
And then wherever you need the data in ActivityB you could do:
int yourIntData = getIntent().getIntExtra("someIntData",0);
String yourStringData = getIntent().getStringExtra("someStringData");
This would be a faster because you don't have to hit the filesystem with SharedPreferences or a database.
Upvotes: 4
Reputation: 234795
You can use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
with either activity and it will return a SharedPreferences
object tied to your app's package name, regardless of which activity you pass as a context.
Alternatively, you can pick a name for your shared preferences and pass it to the activity's getSharedPreferences
method (as Sam_D and Graham point out in their answers).
Upvotes: 2
Reputation: 249
You can store all your data in SharedPreferences and you have access on them from every activity in your application.
Just do it like its explained here: http://developer.android.com/guide/topics/data/data-storage.html#pref
Upvotes: 1
Reputation: 25757
If you are storing in SharedPreferences then you do not need Activity B's context. Activity A's context can access the app's SharedPreferences as they are 'global' to the app.
Code Example
ActivityA.this.getSharedPreferences("SOMETHING", MODE_PRIVATE);
As to define if you need a database, you did not say what the data was you are storing. Therefore it is impossible to tell.
Upvotes: 5