Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Use Shared Preferences. Like so:

Create these methods for use, or just use the content inside of the methods whenever you want:

publicStringgetPrefValue()
{
  SharedPreferences sp = getSharedPreferences("preferenceName", 0);
  String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
  return str;
}

publicvoidwriteToPref(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
}
elseif (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.

Solution 2:

You can use SharedPreference to save your data in Android.

To write your information

SharedPreferencespreferences= getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editoreditor= preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit(); 

To read above information

SharedPreferencesprfs= getSharedPreferences("PREF", Context.MODE_PRIVATE);
Stringusername= 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.

Post a Comment for "How To Keep Information About An App In Android?"