How to call another intent without losing previous data? - android

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.

Related

How to save viewpager page position as bookmark?

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);

Save Position of RecylerView when we go to Detail Activity by clicking from list of items in RecyclerView and restore it when we back to RecylerView

How to Save Scroll Position of RecylerView Activity when we go to next Detail Activity by using itemclicklistener from list of items(these items are retrieved from Firebase JSON) in RecyclerView and restore position when we come back to Recylerview Activity and i am Using LinearLayoutManager
Please Help Me
Thanks in Advance
I am not really clear with your question. I assumed you current activity was destroyed when you go to next detail, thus recreating the activity when you go back. Do not call finish when you go to next detail and just call onBackPressed to go back to your previous activity. This will maintain your recyclerView state and position.
Anyway, you can use Shared Preferences to save the position before go to next detail and get it back on onResume.
Problem statement is unclear. Still I am trying to answer.
Assuming you starting new Activity on click of list. As per the Lifecycle of activity background activity will stay in the same state with scroll. When you finish new activity back activity will on same state.
This might happening due to below reasons
You reloading data on onResume method. You should load data on
onCreateView.
You are starting background activity from second activity.
save state on Activity on onPause method and restore it on onResume() method
See the code
public class Activity extends AppCompatActivity
{
private final String STATE = "recycler_state";
private RecyclerView mRecyclerView;
private static Bundle mBundle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);//set to whatever view id you use
// don't forget to set your adapter
}
#Override
protected void onPause()
{
super.onPause();
// save RecyclerView state
mBundle = new Bundle();
Parcelable listState = mRecyclerView.getLayoutManager().onSaveInstanceState();
mBundle.putParcelable(STATE, listState);
}
#Override
protected void onResume()
{
super.onResume();
// restore RecyclerView state
if (mBundle != null) {
Parcelable listState = mBundle.getParcelable(STATE);
mRecyclerView.getLayoutManager().onRestoreInstanceState(listState);
}
}
}
You can use this trick:
int firstItemPos = mLayoutManager.findFirstVisibleItemPosition();
View v = mLayoutManager.findViewByPosition(firstItemPos);
int offsetPixel = 0;
if(v != null) offsetPixel = v.getTop();
And then when you restore position:
mLayoutManager.scrollToPositionWithOffset(firstItemPos, offsetPixel)
firstItemPos and offsetPixel you can save in extra bundle of activity. mLayoutManager in my example I use ordinary LinearLayoutManager and set it to my Recycle View:
mLayoutManager = new LinearLayoutManager(getActivity())

PreferenceActivity listpreference value resets to default on reload

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!

How to link a favorite button to a new activity?

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.

Back Button pressed

I have TabActivity which contains 4 Tabs. Each tab have one FragmentActivity and 2-3 Fragments.
From Fragment, I am going to a Activity which is not the part of Tabs.
While clicking the Back button from that Activity, I want come back to previous Fragment,
without destroying that Activity.
I am overriding the public boolean onKeyDown(int keyCode, KeyEvent event) method, but problem is that it displays the previous fragment without Tabs. I want Tabs to be displayed...
Use onBackPressed method in your activity class.
#Override
public void onBackPressed(){
if(you wanto go back){
super.onBackPressed();
}else{
//if you dont want to go back
// do what you need hear....
}
}
What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}

Categories

Resources