I have one Textbox in Main activity and one edit textbox in Create Activity. I used the create activity to generate my text to the textbox in main activity. This part works.
However, when i switched back to create activity, the text in texbox in main activity is gone.
I want to save the text in textbox even after switching activities
Have a look at SharedPreferences to save the value of your String across the activities.
In MainActivity, read from the SharedPreferences. Get the String value from the SharedPreferences (default value is set to be the String "Default Value") and set that value to the TextView.
SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE);
// read from SharedPreferences
// get the string value using the key "string" set when writing to the shared preferences
// return string default otherwise
String string = sharedPreferences.getString("string", "Default Value");
// get the TextView
TextView textView = (TextView) findViewById(R.id.textView);
// setText on TextView
textView.setText(string);
In CreateActivity, write to the SharedPreferences. In the lifecycle method onPause() of your activity, write to the SharedPreferences by getting the value from the EditText using the getText() method.
#Override
protected void onPause() {
super.onPause();
// write to SharedPreferences with edit
getSharedPreferences("sharedPrefs", MODE_PRIVATE).edit()
.putString("string", editText.getText().toString())
.apply();
}
Quick note: When getting SharedPreferences using getSharedPreferences(), be sure to use the same name - in our case "sharedPrefs".
Tried and tested just now - so feel free to ask questions!
There are some project for you:
1.Make the text as cache, and when you switch to main activity, you take the text from cache and set text to the textbox, you can use SharePrefrence or DiskCache to save the cache
2.make main activity Single, like set the launchMode="singleTask" in AndroidManifest.xml ,you should make that main activity would not be finish when you switch to create activity
There are my idea, you can try, good luck!
Related
I have an application where app has both online & offline mode.
Once the fragment is loaded a network call is made and data is set.
The user makes some changes into fragment UI like adding buttons, Editing TextBoxes etc. I have to maintain that state throughout the application.
I have next & previous buttons, when i press on previous button on the fragment is reloading even though i tried to adding it to back stack while replacing it and calling getActivity().onBackPressed();.
Things I have Tried :
1) saving the values into bundles is too much data & hard ti retrieve due to bulk of data/values.
If you use viewpager, you can keep the last state of the fragments and it will not reload untill the offscreen limit u set as below.
mViewPager.setOffscreenPageLimit(limit); //limit: integer value >=1
If you have large number of data you want to save, use SQLite, otherwise you can use Shared Preferences
For more info visit this link
First get the reference to your shared preferences file
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
after this write to Shared Preferences with
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "value");
//use editor.apply() if you want to save your data imedialtly
editor.commit();
when you want to retrieve the data (onCreateView/onViewCreated)
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
EditText editex = (EditText) view.findViewById(R.id.your_view_id);
editext.setText(sharedPref.getString("key", defaultValue))
}
But keep in mind, Shared Preferences will save and keep your data even if your app is killed/destoyed
I have 2 fragments.
Fragment 1
Loads sharedpreference to display string
Fragment 2
Saves sharedprefence for string
Is it possible to retrieve that string in my first Fragment without running the second Fragment?
Yes, this is possible. You just need to make sure you are reading with the same key you used to write with:
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
// Reading from SharedPreferences
String value = prefs.getString("myKey", "defaultValue");
Log.d(LOG_TAG, value);
Note that we've assigned a defaultValue as the return value here. If there is no value with the key "myKey" in your shared prefs, it will instead return "defaultValue". This is a nice safeguard, think of it like a null pointer check - you will always get a value from getString(), even if it's just the default.
You don't need to be in the same activity for this to work, you just need to make sure that 1) your preferences name is the same and 2) the key used to store the value is the same in both spots.
First, don't get confuse between Activity and Fragment.
And yes, you can.
I want to display the server response on multiple screen in header bar in Android? Please, tell me how to do that? I created an abstract class and defined the Asynctask class. In onPostExecute method i am using the textview for displaying the result. Now my question is how all the activities access this textview?
I am new with Android. Please, give me the proper way to solve this?
May be you can use the shared preference feature of android to save the response.
References are How to use SharedPreferences in Android to store, fetch and edit values and http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
On each activity, you can set the header by referring the value from shared preference.
Create one base activity and extend that created base activity instead of activity. Create one xml file in base activity, in it only declare your header. nothing else, now to display use that xml and for the other contents you can use your actual xml file. So this one is for to set global header. Now, save your response to Shared preferences and use it throughout the app whenever you need.
Store the value into Shared preferences
SharedPreferences sharedPref = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
// saving
sharedPref.edit().putString("key", "value").commit();
// reading
sharedPref.getString("key", "default");
You need to store the response values in Stringbuffer
StringBuffer value =new StringBuffer("your response value");
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Identifier",value);
editor.commit(); //important, otherwise it wouldn't save.
Get the value in next activity
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
final String myVariable = prefs.getString("Identifier", "value");
I have an application which has a Prefernces Class and I want to know how could i make so that when the application is started the settings to be applied even before entering the preferences ( settings ) class. I have a getPrefs() void method which is called when i press "Save" Button in preference activity.
So, could you help me and tell what should I do the "default" preferences to be applied when entering the application ? (I need getprefs method from another class )
I would be grate if you could give me some advices or tips.Thank you !
To get an instance of the SharedPreferences from anywhere in your application use:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPrefences(context);
To set a value in the preferences, you need to call the editor for those preferences, then set the value for a key and finally commit the result. It can all be done in a single line:
prefs.edit().putString("myKey","myValue").commit();
This would store the string value myValue on a key named myKey and it will be accessible (after you commit) to any class if it has the application's context when it calls getDefaultSharedPreferences.
To retrieve the stored value you specify the key and a fallback value in case there is no preference set with that key:
prefs.getString("myKey","oops no value found");
I have multiple views that come and go as the application runs. I want each view to have its own personal preferences that are stored as the ID tag of the view. Above these is the "General Preferences" that the sub prefs reference to get their default values when a view it is created.
Right now I have it set up that the General Preferences are the default SharedPreferences. But I have no Idea how to create the new preferences and set up an activity UI so the user can change them. Is it pretty much the same as setting up the SharedPreferences?
this may not be exactly what you're asking for, but here's what I do:
in my main activity, when I call the preferences activity, I pass it the name of the custom preference file as extra data in the intent:
static final String EXTRA_PREFERENCES_NAME = "android.intent.extra.PREFERENCES_NAME";
...
Intent intent = new Intent(this, Preferences.class);
intent.putExtra(EXTRA_PREFERENCES_NAME, preferencesName);
startActivity(intent);
then, in my preferences activity, I get the custom preferences name and set it like this:
public class Preferences extends PreferenceActivity {
private String preferencesName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the custom preferences name from the extra data in the intent
preferencesName = getIntent().getExtras().getString(MainActivity.EXTRA_PREFERENCES_NAME);
// set the preferences file name
getPreferenceManager().setSharedPreferencesName(preferencesName);
// get the default preferences from XML
addPreferencesFromResource(R.xml.preferences);
}
lastly, in my main activity, I get specific preferences like this:
SharedPreferences preferences = getSharedPreferences(preferencesName, MODE_PRIVATE);
String somePreference = preferences.getString("somePreference", defaultValue);
Somehow I am not worthy to comment but to write an answer, so here we go:
I'd really like to know how to use sharedPreferences with PreferencesActivity instead of DefaultSharedPreferences.
One way I can think of to accomplish this is letting the preferenceActivity save the values to defaultSharedPreferences and then read these values out and save them into a sharedPreferences associated with a name that would match the kind of values saved.
But this seems very wrong. So how do you guys do this? Or do you save all your values from any PreferencesActivties into defaultSharedPreferences?
You can use PreferenceManager to achieve the objective.