Saving information after closing the app - android

I've been trying to create a user profile section for my app where the user enters his information (Name, DoB, height, weight etc) and clicks submit. After this he's taken to the main menu of the app.
The problem I have is that if I close the app and run it again, this will obviously result in the app displaying the user profile section again and asks the user to enter his information.
I've been trying to look for a way in which the app saves the information that the user enters and remembers it. So for example when the user first uses the app, he gets the user profile section and enters his information. When the user closes the app and opens it again it should take him straight away to the main menu.
I know I could achieve this slightly with Preferences, but I'd rather use a normal layout(LinearLayout) so that it gives me more options such as TextView etc.
Is there a way where I could achieve this using just LinearLayout instead of Preferences?
I've also been looking at creating custom Preferences, but none of the things I found was particularly useful.
Thanks in advance.

Use SharedPreferences.
Check the application for First Run and display layout which you want to enter user's profile.
After store boolean flag for first Run in shared Preference which will prevent your Profile Screen to display again.
Look at Check if application is on its first run
Update:
Put this FirstRun() code in your onCreate() of Main Activity.
private void FirstRun()
{
SharedPreferences settings = this.getSharedPreferences(MainActivity.PREFS_NAME, 0);
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun)
{
// Checks to see if we've ran the application b4
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun", false);
e.commit();
// Display User Profile Screen
}
}

use sharedPreference to store information by this way..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("userid", "success");
editor.commit();
and to get the value from it use below code..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("userid", null);
or try to use SqliteDatabase or may be Application Class..this will store the information as you want.

#Override
public boolean saveUserData(UserModel userModel, Context context) {
email = userModel.getEmail();
firstName = userModel.getFirstName();
lastName = userModel.getLastName();
twitterId = userModel.getTwitterId();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor setUserDataPreference = userData.edit();
setUserDataPreference.putString(EMAIL, email);
setUserDataPreference.putString(FIRST_NAME, firstName);
setUserDataPreference.putString(LAST_NAME, lastName);
setUserDataPreference.putString(TWITTER_ID, twitterId);
setUserDataPreference.commit();
return true;
}
#Override
public UserModel getUserData(Context context) {
UserModel userModel = new UserModel();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
email = userData.getString(EMAIL, "");
firstName = userData.getString(FIRST_NAME, "");
lastName = userData.getString(LAST_NAME, "");
twitterId = userData.getString(TWITTER_ID, "");
userModel.setEmail(email);
userModel.setFirstName(firstName);
userModel.setLastName(lastName);
userModel.setTwitterId(twitterId);
return userModel;
}

Related

How to display saved textview onto image button

Functionality Description:
Image Button(calls on a secondary application) that allow users to enter and input text, handwritten as well as keyboard input. User will then have the option to save the text. When, user exit the secondary application, the image button is supposed to displayed the saved text.
Genuine Issue:
Have intended to use shared preferences method but the saved text is still not displayed. Can anyone please help. Following is the code used.
Code:
//EDITED VERSION TO CALL OUT THE SECONDARY APPLICATION FOR USER TO INPUT TEXTandr
private void addListenerOnButtonMyScript() {
// TODO Auto-generated method stub
imageButton = (ImageButton) findViewById(R.id.imageButton_myscript);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("SingleViewActivity:onCreate:addListenerOnButtonMyScript" + ":onKey" , "Initiate myScript:");
final Intent intent = new Intent();
intent.setClassName("com.visionobjects.textwidget.sample", "com.visionobjects.textwidget.sample.SampleActivity");
startActivity(intent);
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
Log.i("Calling on Shared Preferences" , "Shared Preferences to pref_text:" + getString(R.string.pref_text) );
SharedPreferences.Editor editor = pref.edit();
editor.putString(getString(R.string.pref_text),"");
editor.commit();
}
});
}
//EDITED VERSION TO CALL ON SHARED PREFERENCES FUNCTION TO DISPLAY EDITED TEXT FROM MY_SCRIPT-20/10/2014
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();
editor.commit();
}
Strings.xml
<resources>
<string name="app_name">SalesBase</string>
<string name ="pref_text">StandardPreferences</string>
<string name="contacts_default">Contacts Details\n名字:HARRY\n公司:BARTENDER\n路名:123, Road Name\nZip:Zip\nState:State\nMobile:012-345-6789\nOffice:12-345-678\n</string>
</resources>
You are using wrong code to load the data. If loadSavedPreferences() is your final code to get data then you will not get any data. Try this
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
String data = prefs.getString(getString(R.string.pref_text), "");
}
However, I would suggest you to use different keys for preference name and the data you are trying to save.
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Use a different key where you are saving the data in this line and obviously value is the data you want to save. Use something like this.
editor.putString(key,value);
editor.commit();
And when you want to show the data then use the same key to get the data.
String data = prefs.getString(key, "");
Have a look at this as well.
Android Shared preferences example

How to keep information about an app in Android?

I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.

Android login at once

How do I code for login in some app in android that I do not need to login in it again next time I open the application ?
I tried a lot, but no success. If possible please provide me code.
In my app I created a base class for all my activities which checks in oncreate if the user is logged in with shared preferences. If not I show the login screen and continue my app after a successful login.
If this login is local:
First time when you login,
Editor editor= YourSharedPreference.edit();
editor.put(nameOfAccount,name);
editor.put(passwordOfAccount,password);
editor.commit();
Then every time you open the APP,
if(YourSharedPreference.contain(nameOfAccount)&&YourSharedPreference.contain(passwordOfAccount))
{//do not need login}
else
{//do login thing}
An easy way it to store it in the shared preferences.
Basicaly you request a shared preference then you can get string value from it (load).
Using the a SharedPreferences.Editor you can put string value into it (save).
Checking if the value is set (null) will tell you if the user already logged in your app or not.
Here an exemple:
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences("LOGIN_PREF", 0);
String login = settings.getString("login", null);
String password = settings.getString("password", null);
if(login == null || password == null){
// Do stuff for login user
}else{
// Do stuff for not logged user
}
}
public void saveLogin(String password, String login){
SharedPreferences settings = getSharedPreferences("LOGIN_PREF", 0);
SharedPreferences.Editor loginEditor = settings.edit();
loginEditor.putString("login", login);
loginEditor.putString("password", login);
loginEditor.commit();
}

How to pass a parameter through all activities?

I am developing a mobile application where I need the user object to be available through all the activities and I don't want to send it using the Intent from each activity to the other.
Can anyone help me please ?
If you could store it in:
SharedPreferences or
SQLite
I think the SharedPreferences would be much simpler to implement.
Here is an example, how you could create a static function, wich you can access from all your activities:
public class UserCreator
{
public static User getUser(Context context)
{
SharedPreferences prefs = context.getSharedPreferences("Name", Context.MODE_PRIVATE);
//Check if the user is already stored, if is, then simply get the data from
//your SharedPreference object.
boolean isValid = prefs.getBoolean("valid", false);
if(isValid)
{
String userName = prefs.getString("username", "");
String passWord = prefs.getString("password", "");
...
return new User(userName, passWord,...);
}
//If not, then store data
else
{
//for example show a dialog here, where the user can log in.
//when you have the data, then:
if(...login successful...)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "someusername");
editor.putString("password", "somepassword");
editor.putBoolean("valid", true);
...
editor.commit();
}
// Now, if the login was successful, then you can recall this function,
// and it will return a valid user object.
// if it was not, then it will show the login-dialog again.
return getUser(context);
}
}
}
And then from all your activites:
User user = UserCreator.getUser(this);
Just make that object 'public static'.
Then access it in other activities like:
PreviousActivity.userobj
Write a class which extends Application class. And put global parameters there. Those parameters will be valid in application context.

How can i save the config of my app without using a database??? (using simple textfile)

i need to save a simple field to configurate my APP, cause this, i wont use a database (it's only a field...), i need to save true or false value for this field on a file, and everytimes a section of my app wanna check if it is true they have to check this textfile, and not to open a connexion to a database
i need to save the config for ever... i mean that when i exit from my app, and for example, i shut down my android device, when i start my device again and start my app, the config have to be saved
is this possible? how can i do it? i can't find any information about that
EDIT: i have problems with the first answer... this code is on my oncreate method:
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
if (settings.getBoolean("showMeCheckBox", true))
showMeCheckBox.setChecked(true);
else
showMeCheckBox.setChecked(false);
applyButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if (showMeCheckBox.isChecked()) {
configEditor.putBoolean("showMeCheckBox", true);
} else {
configEditor.putBoolean("showMeCheckBox", false);
}
}
});
ok, but this doesn't works... allways is selected... always true, like the default value... doesn't matter if i checked or unchecked it.... :S
i suggest not to use a textfile but the Preference Editor.
static SharedPreferences settings;
static SharedPreferences.Editor editor;
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
editor = settings.edit();
//store value
editor.putString("Preference_name_1", "1");
//get value
//eill return "0" if preference not exists, else return stored value
String val = settings.getString("Preference_name_1", "0");
Edit: you have to initialize the configEditor and after setting a value, you have to commit
editor = settings.edit();
editor.putBoolean("name",true);
editor.commit();

Categories

Resources