I want to add a favorite button in a layout which can save the layout and apply it to another activity. I'll show you an image bellow to understand exactly the way I want to do it..
I created the favorite button, and the activity for this button to save the layout, but the app is still crashing when I press the favorite button and the activity which should open the layout, which I have saved, is blank. Here are the code:
public void onClick(View v){
SharedPreferences prefs = this.getSharedPreferences(
getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
prefs.edit().putString("activity", "YourActivityName");
}
public void onClick(View v){
SharedPreferences prefs = this.getSharedPreferences(
getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
String activityToRun = prefs.getString("activity", "noFavorites");
if(activityToRun.equals("noFavorites")
return null;
if(activityToRun.equals("YOUR FIRST ACTIVTY")
//code for launching activity
}
I added this to Favorite.java, and I created another activity, called Favorite2.java which should be open the layout saved by the favorite button, but what I don't understand is how I can link the saved layout to the activity Favorite2.java?
And please, if someone can tell me exactly the explanation for getString and putString and the way that they should be implemented.
Related
I have MainActivity where i define viewpager and i also define button on toolbar.
I want when i click on button it save the viewpager page position with title in another activity in listview.
Provide complete example.
Try saving position of viepager in a shared preference.
save when going away from activity
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("viepager_position", postion);
editor.apply();
retrieve when user comes back to activity
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int position = prefs.getInt("viepager_position",default_position);
I open a selection fragment using androidx.navigation, but I cannot find a way to return data to the previous fragment.
In one parent activity.. just use global variable that able to access inside same parent activity or
Other trick you can try preference, so that preference will able to read anywhere you want.
Data share active fragment
sharedPref = context.getSharedPreferences(context.getPackageName(),MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putString(sKey, sValue);
prefEditor.apply();
Data read from other fragment
sharedPref = context.getSharedPreferences(context.getPackageName(),MODE_PRIVATE);
sValue = sharedPref.getString(sKey,defValue);
I am facing two problems in my app.
In my app i am using preferenceActivity that contains simple settings for the app (checkboxpreference and listpreference), i have three activities mainActivity,secondActivity and settingsActivity which is prefrenceActivity, in secondActivity i am showing a form that lets user choose a value from a spinner view , what i want to do is user can select a default value of that spinner from settingsActivity so user dont have to manually select the value of spinner everytime.
Now my first problem is: whenever i reopen my settingsActivity(preferenceActivity) the summery of the listPreference is resets to default it only shows selected value while settingsActivity is open, when i go back to mainActivity and i again open the settingsActivity the summery of listPreferece shows default value(if i open list of values,it shows last selected value checked).
Second problem is: Whenever i close the app and open again the preference value gets destroyed means the secondActivity dosent show user selected default value instead it shows the first value of spinner.
here is my code
settingsActivity:
public class settingsActivity extends PreferenceActivity
{
MainActivity mainActivity = new MainActivity();
ListPreference listpref;
#Override
public void onCreate(Bundle savedInstenceState)
{
super.onCreate(savedInstenceState);
addPreferencesFromResource(R.xml.settings);
getActionBar().setDisplayHomeAsUpEnabled(true);
listpref = (ListPreference)findPreference("prefDefaultCurrency");
listpref.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
// TODO Auto-generated method stub
listpref.setSummary(value.toString());
mainActivity.pref_default_currency_index = listpref.findIndexOfValue(value.toString());
return true;
}
});
CharSequence curenttext = listpref.getEntry();
mainActivity.pref_default_currency_index = listpref.findIndexOfValue(curenttext.toString());
}
pref_default_currency_index is a static int variable declared in mainActivity,
i retrive this variable to set the value of spinner in secondActivity, when user clicks a button to open an alertdialoug that contains spinner.
Please help me, thanks in advance.
I got the solution to both of my problems.. i was making it too difficult when it as very easy!!
My first problem was to get back the option user selected from listPreference from PreferenceActivity, i realized that preferenceActivity automatically saves information to SharedPrererences so what i have to do is just retrieve that information in onCreate() method and save it in a local variable.
SharedPreferences sharedPrefs= PreferenceManager.getDefaultSharedPreferences(this);
pref_default_currency_index = Integer.parseInt(sharedPrefs.getString("prefDefaultCurrency","0"));
Second problem was that whenever i open settings activity (preferenceActivity) the summery of listPreference was not showing last chosen value, to solve that problem i just have to set the summery of listPreference in setOnPreferenceChangeListener() method
listpref = (ListPreference)findPreference("prefDefaultCurrency");
listpref.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
// TODO Auto-generated method stub
listpref.setSummary(value.toString());
return true;
}
});
thats it, it was easy!
I have a tab-host with three activities and in each activity I have 4 buttons.
On each button press I am changing the background drawable resource like this
case R.id.button1:
if (isclick) {
b1.setBackgroundResource(R.drawable.icon4hlt);
} else {
b1.setBackgroundResource(R.drawable.icon4);
}
So now How can I save the pressed state of each button in all three child activities so that when I move from one activity to the other the button pressed state will be reflected on moving back.
first activity -> all 4 buttons pressed -> go to 2nd activity -> come back to first activity -> all buttons in first activity should be in pressed state
even on home button and back button press also It should work.
I know shared preferences is a good Idea and I went through related threads but I didnt get any Idea how to do this.
Any help is always appreciated,Thanks
You can keep ids of pressed buttons in shared preferences as you mentioned. You'll store a set of ids for every activity. Something like this:
public void onStop() {
SharedPreferences pref = // getPreferences;
Set<String> ids = new HashSet<String>();
for (Button button : buttons) {
if (button is pressed) {
ids.add(String.valueOf(button.getId()));
}
}
pref.edit().putStringSet(CURRENT_ACTIVITY_NAME, ids).commit();
}
public void onStart() {
SharedPreferences pref = // get preferences;
Set<String> ids = pref.getStringSet(CURRENT_ACTIVITY_NAME, Collections.emptySet<String>());
for (String id : ids) {
Button button = findViewById(Integer.parseInt(id));
set button pressed
}
}
But I still think pressed states should not reset when you switch between tabs because activity aren't recreated.
I have 2 pages in my application. From Page A I am calling Page B. On page B I have a ListView which is filled by users. Now when User clicks on Back Button of the phone he comes back to Page A. But when he clicks menu and select Add Items again, it opens Page B but my ListView is empty. How can I get back to Page B without losing data in ListView?
Override the onBackPressed in page B, and save your data some where..
then in the onStart of page B reload the data..
One way to accomplish this is to use the SharedPreferences:
public void onStop(Bundle bundle)
{
SharedPreferences mySharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("myBool",true);
//Continue saving all the data you need to recreate the listView
}
Then when you restart the activity, you can reload the preferences in the OnCreate() method like this:
public void onCreate(Bundle bundle)
{
SharedPreferences mySharedPreferences = getPreferences(MODE_PRIVATE);
// Retrieve the saved values.
boolean myBool = mySharedPreferences.getBoolean("myBool");
//Recreate the ListView here
}
It might not be the cleanest way to do so. But since onSavedInstanceState can't be used in your case, it will have to do :)
You can use SharedPreferences to save and load the data in a list
I.e
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settingsActivity.edit();
prefEditor.putString(LISTFROMB, savedItems);
prefEditor.commit();
}
return super.onKeyDown(keyCode, event);
}
And then load it in A like :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.list);
ArrayList<String> selectedItems = new ArrayList<String>();
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
String savedItems = settingsActivity.getString(LISTFROMB, "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
[CALL YOUR ADAPTER HERE WITH THE SELECTED ITEMS LIST]
}
Thanks for your help. I solved the problem just by declaring the ArrayList in Page A. So now when I go back to Page B the source of the ListView is in Page A so easy to load it back.
Don't know if this approach is wrong. Please leave your comment if you think this shouldn't be done.