How to pre populate data between the screens in android - android

I have an app with 3 screens.
For each screens i have next button in each screen to go to the next screen.
problem:
Scenario 1:
--> I filled the data in first screen
--> I go to the second screen.
--> When i come back to the first page i am able to see the data what i filled.
-->But when i again go to the second page i am not able to see the data what i filled in the second form.
How can i manage this in android?
Thanks in advance...

You can save the data in Shared preferences. Check this : Shared Preferences Android and Example
Hope this helps.

You need to save the state yourself using your activities' lifecycle methods. Read this: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

You can save temporary data in application data. Once in the onCreate method, you can reuse that data, or you can use an activity flag to ensure that there's only one instance of your activity in the backstack.

try
{
//in first run app. go to catch and in other go to try
SharedPreferences pref = getSharedPreferences("pref",0);
SharedPreferences.Editor edit = pref.edit();
String x= pref.getString("login", null);
edit.commit();
if(x.equals("first"))
{
//here you can fill editbox by value you entered before
edt1.setText(x);
//and make this way to all edittext
}
}
catch(Exception e)
{
SharedPreferences pref = getSharedPreferences("pref",0);
SharedPreferences.Editor edit = pref.edit();
edit.putString("login",edt1.getText().toString());
//edt1.getText().toString() value(s) you want to save
edit.commit();
Intent intent = new Intent(getApplicationContext(), First.class);
startActivity(intent);
}

Related

Android Value of SharedPreferences is not updating while app is running

I have 2 activity say for e.g MainActivity and PlayActivity.
I am retrieving value of currentLevel from SharedPreferences in MainActivity using following code.
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
// comment this to see if value is saved or not
currentLevel=sharedPreferences.getInt("currentlevel",1);
and I am Updating value of currentLevel in PlayActivity using following code.
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("currentlevel",currentLevel+1);
editor.apply();
Now my problem is while running app i am not able to update its value. For e.g while i am in PlayActivity and i won a level and i updated value of Shared Preference but while running app if i go back to MainActivity and try to retrieve CurrentLevel value, i got previous value not updated one.
Please Help. One more thing if i push updated of my app in future will sharedPrefrence also get updated with default 1 value or it will retain its previous value.
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("currentlevel",currentLevel+1);
editor.commit();
I have created a quick sample for you to inspect. It's a "Empty Activity" project (as per the latest Android Studio template) with all defaults (in Kotlin).
After the project was created, I added a second Empty Activity (via the same template), and then I modified their layouts to have an Edit Text and a button.
What do Activities do when they start?
Load any existing Shared Preference value.
Populate the EditText with the existing value (which defaults to 0)
What does button click do?
Save existing value into shared preferences.
Launches next (or previous) activity.
Activity 1 goes to Activity 2, and Activity 2 goes back to 1.
Notice how no matter what number and what activity you use, the other picks it right away.
Here's where I left the project for your inspection:
https://github.com/Gryzor/MySharedPreferences
If you don't want to bother with a git clone, here's what Activity 1 does:
// Obtain our private Shared Preferences
// This comes from ContextWrapper.
val sharedPreferences = getSharedPreferences("sample", Context.MODE_PRIVATE)
// restore existing value
val current = sharedPreferences.getInt("A_NUMBER", 0)
editText.setText("$current")
button.setOnClickListener {
val text = editText.text.toString()
val value = try {
text.toInt()
} catch (e: NumberFormatException) {
0
}
// Save the current value
sharedPreferences.edit().putInt("A_NUMBER", value).apply()
// ... and go to the next activity
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
finish()
}
The other activity is identical, sans the intent line:
val intent = Intent(this, MainActivity::class.java)
Conclusion
What I wanted to point out with all this nonsense, is that you are mismanaging your instances and not correctly using something. It's hard to tell because we haven't seen your source code.
Good luck :-)

Saving Fragment's State Through out the application

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

SharedPreferences in Android saving the visibility of an ImageView

I have a menu activity that acts as a level selector. When the user finishes a level (activity) and returns to the menu, I want it to set an image visible in the menu to show that said level has been completed. Also, I want this info to save from a session to another.
My aproach has been to try SharedPreferences. This is the code from the level activity that writes the save:
private int levelNumber
SharedPreferences save = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = save.edit();
editor.putInt("levelComplete",levelNumber);
editor.commit();
GameActivity.this.finish();
This is the relevant code from the menu that reads the save and sets the image visible based on the levelNumber:
clear_stage = new ImageView[clear];
clear_stage[0] = (ImageView)findViewById(R.id.clear1);
clear_stage[1] = (ImageView)findViewById(R.id.clear2);
clear_stage[2] = (ImageView)findViewById(R.id.clear3);
clear_stage[3] = (ImageView)findViewById(R.id.clear4);
clear_stage[4] = (ImageView)findViewById(R.id.clear5);
SharedPreferences save = getApplicationContext().getSharedPreferences("SaveGame", MODE_PRIVATE);
clear = save.getInt("levelComplete", 0);
clear_stage[clear].setVisibility(View.VISIBLE);
I have the visibility set to "gone" in the xml, by the way.
Now, my main problem is that the visible image changes every time that a level is completed, and the last image goes invisible again (gets overwritten).
Is there a way to store the clear value each time a level is complete?
I tried with:
SharedPreferences saveall = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = saveall.edit();
editor.putInt("clear_stage",clear);
editor.commit();
But it isn't working, and I don't really know what I should do next. Ask me anything if the post wasn't clear enough.
I think your problem is that your'e loading as an int, not an array. I would look here for a better explanation. Is it possible to add an array or object to SharedPreferences on Android particularyly sherifs' answer

How to maintain Session Timeout handling in Android Application

I am new to Android App development.I have a small issue.Working on my Android Application suddenly hit "Home" Button so it goes to background after some time again go to "Home" and click my app icon it again getting started from my first screen instead of this i have keep the last viewed Activity and should show message like "Your Session timed out So Please Loging again the box with two EditText boxes" Then check the credentials and Allow the user to continue or redirect to Login Screen.How to achieve this.
Thanks in advance..
Its simple in Android. you need to maintain SharedPreferences.
Read this for better understanding of the concept.
This will work as
==> when ever you are trying to maintain login concept save user name in the sharedpreference.
==> once data is edited in prefernces.xml , the data in it can be check in any Activity.
For example, to save username, password and session ID, you can:
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putString("User Name", username);
edit.putString("Password", password);
edit.putInt("Session ID", session_id);
edit.commit();
and get them
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
username = pref.getString("User Name", "");
password = pref.getString("Password", "");
session_id = pref.getInt("Session ID", 0);
SharedPreferences is definately the way to go, but to go into more detail for the timeout:
Save the current timestamp in onPause() (-> SharedPreferences)
Then in onResume() compare it, to check for a timeout
If you did not time-out just continue, otherwise show that nice screen, simply logout, self-destruct the device, or whatever you would like to do in that case :-)
Also you might consider implementing some kind of session manager class, to handle it on a higher level:
Nice example/tutorial from android hive
See this diagram for an explanation of the Activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Override the appropriate methods in your activity to keep track of when it loses/regains focus.
If you want to maintain the user login session then instead of having the preference in all the activities we can have handler inplace to do this.
Create Handler after the user logsin
Set sendMessageAtTime(Message, long), long is millisecond value. This will call the logout function that defined.

android Shared Preferences issue

i want to force use to fill Settings Page in two cases
1) when user first launch Application
2) when database version is change i want that setting page should be filled first before proceding
in my Setting class i set shared preferences "false" , and then i check it in below code
class setting //main class
String flag = sharedPreferences.getString("CreatedFlag","");
if(flag.equals("true"))
{
// Move to second activity
Intent i =new Intent();
i.setClass(someclass.this,otherPage.class );
startActivity(i);
finish();
}
else
{ // Stay on Settings page }
Problem : it run fine when user first launch application ,it show setting page and fill tht page ,
but when user run application second time it show setting page again ,coz shared preference still have true value ,
thn again user run app 3rd time Shared Preference have update value which is false ,and show other page
what i want is tht Setting page show only once if its there is no setting define ,other wise it goes to home page
need help ,
I dont shee here where you're actually saving the preferences, I assume its in the otherPage activity??
If not add this to the first activity
SharedPreferences prefs = this.getsharedPreferences("myApp",0);
//check for the Created value in the shared preferences
String createdFlag = prefs.getString("Created","false"); // set default value == false
if(createdFlag == "false){
goToSettingsPage(); // to the settings page we go...
}
Then on your settings page:
SharedPreferences prefs = this.getSharedPreferences("myApp",0);
SharedPreferences.Editor ed = prefs.edit(); // create the editor
ed.putString("Created","true"); // put the value to the prefs
ed.commit(); // commit the changes
After the first run, the shared prefs file will be persisted, and then should not goto the settings page the second time its run.

Categories

Resources