I'm not sure how to word this but I'm having issues accessing Shared Preferences under MODE_PRIVATE.
I'm implementing a Spinner like so:
setSessions = (Spinner)findViewById(R.id.numSessions);
setSessions.setOnItemSelectedListener(new CustomOnItemSelectedListener());
The Custom listener is like so:
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
SharedPreferences defaultPrefs;
defaultPrefs = getSharedPreferences("Defaults", MODE_PRIVATE);
String savedSessions = defaultPrefs.getString("tcpCapSessions", "None Set");
if (savedSessions != parent.getItemAtPosition(pos).toString()) {
final Editor defaultEdit = defaultPrefs.edit();
defaultEdit.putString("tcpCapSessions", parent.getItemAtPosition(pos).toString()); // Writes the key "Default Server" along with Server Name chosen (as the value).
defaultEdit.commit();
}
Toast.makeText(parent.getContext(),
"Sessions set to: " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I'm getting an error on the "MODE_PRIVATE" when getting SharedPreferences....
I simply want to update a preference depending on the users selection. I've tried extending the Activity which gets rid of the error but the app will still crash on first launch.
I've checked out Use sharedpreferences inside class but it hasn't helped me resolve the issue, may be it's missing something as it appears like the same issue as myself.
MODE_PRIVATE is a static member of Context. It's actually described pretty good here.
change it to Context.MODE_PRIVATE
Hi Genius try this..
Shared Preferences allow you to save and retrieve data in the form of key,value pair.
You have to call a method getSharedPreferences() that returns a SharedPreferences instance pointing to the file that contains the values of preferences.
SharedPreferences sharedpreferences = getSharedPreferences(YOUR_PREFERENCE_NAME, Context.MODE_PRIVATE);
The first parameter is the Name and the second parameter is the MODE.
Name:
Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
Mode:
(Operating Mode)
0 or MODE_PRIVATE for the default operation.
MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
MODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file.
Example:
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
//Initialize SharedPreferences.
public static SharedPreferences.Editor editUserSelection;
public static SharedPreferences prefUserSelection;
public static final String GET_USER_PREF = "get_my_user";
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
//save user selected position.
prefUserSelection = getApplicationContext().getSharedPreferences(GET_USER_PREF, 0);
editUserSelection= prefUserSelection.edit();
editUserSelection.putInt("user", pos);
editUserSelection.commit();
}
For retrieve the user position,
prefUserSelection = getApplicationContext().getSharedPreferences(GET_USER_PREF, 0);
int userSelected = prefUserSelection .getInt("user", 0); //0 is the default value
Toast.makeText(getActivity(), "User Selected Position: "+userSelected ,Toast.LENGTH_SHORT).show();
Related
In my backupagent class I have this:
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
public class TheBackupAgent extends BackupAgentHelper {
// The names of the SharedPreferences groups that the application maintains. These
// are the same strings that are passed to getSharedPreferences(String, int).
static final String RECIPE_NAMES = "MyRecipeNames";
static final String TEST = "testSave";
// An arbitrary string used within the BackupAgentHelper implementation to
// identify the SharedPreferencesBackupHelper's data.
static final String MY_PREFS_BACKUP_KEY = "myprefs";
// Simply allocate a helper and install it
public void onCreate() {
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(this, TEST);
addHelper(MY_PREFS_BACKUP_KEY, helper);
}
}
I then have code to store a string into the testSave Shared Preferences and request a backup of the preferences:
public void requestBackup() {
BackupManager bm = new BackupManager(this);
bm.dataChanged();
}
public void saveRecipe (View v) {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("testSave", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("testString", "This is my saved data.");
editor.apply();
requestBackup();
}
I then try to uninstall and reinstall the app and the saved data is gone. I have added the required code to the Manifest but it is not working. Does my app need to be on the play store? I really have no idea why it won't work.
You can test your Backup agent using the bmgr tool which is part of your Android SDK (it's a command in adb). See here how it can be used.
I've kept a static shared preference to access the values from multiple activities.
Now, I've set an alarm to go off at a certain time. Now in that Broadcast Receiver, I'm trying to access the shared pref variable.
It has already been initialized in another activity and returns the proper value there.
But in this Broadcast Receiver it doesn't give the actual value. It gives the uninitialized value.
Since it is static shouldn't the value remain same?
Here is the shared preference class.
package com.footballalarm.invincibles;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class SessionManagement {
// Shared Preferences
public static SharedPreferences pref;
// Editor for Shared preferences
public static Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared pref file name
private static final String PREF_NAME = "invincibles_alarm";
// All Shared Preferences Key
public static final String PREF_MATCH = "match";
// Constructor
public SessionManagement(Context context){
this._context = context;
pref = _context.getSharedPreferences(getPrefName(), PRIVATE_MODE);
editor = pref.edit();
editor.commit();
Log.e("Pref Match Value-constructor for pref", getValueMatch());
}
public static void fillValues(String match){
try{// Storing login value as TRUE
editor.putString(PREF_MATCH, match);
// commit changes
editor.commit();
Log.e("Pref Match Value-in fill values", getValueMatch());
}
catch(Exception e)
{Log.e("fillValues", e.toString());}
}
public static String getValueMatch(){
return pref.getString(PREF_MATCH, "Loading Match");
}
public static String getPrefName() {
return PREF_NAME;
}
}
I tried to log the output in other activities and it returns properly.
When I run the app and then close it before the alarm takes place, the program crashes with null-pointer exception since the Broadcast Receiver cannot access the shared pref.
I have tried this solution - SharedPreferences in BroadcastReceiver seems to not update? but I'm only using name in the manifest for the recievers.
This only happens if I close my app in ICS via the minimize menu.
Check this link:
Static variable loses value
Maybe static variables are loosing its value in your case .
static variables can loose value in the following cases:
1) Class is unloaded.
2) JVM shuts down.
3) The process dies.
Instead of using static variables and functions , try using a public class instead.
Hope it helps
EDIT 1:
Example code of using a public class for preferences instead of static methods
public class PreferenceForApp {
Context context;
SharedPreferences prefs;
public PreferenceForApp(Context context) {
this.context = context;
prefs = context.getSharedPreferences(AllConstants.PREFS_NAME, 0);
}
public Boolean getIsDeviceValidated() {
return prefs.getBoolean("Validated", false);
}
public void setIsDeviceValidated(Boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("Validated", value);
editor.commit();
}
}
In your code add:
PreferenceForApp myPref = new PreferenceForApp(contxt);
myPref.getIsDeviceValidated();
Useful related links:
Android static object lifecycle
Why are static variables considered evil?
Android : Static variable null on low memory
EDIT 2
TEST when is your static variable loosing value :
You can test this with a few lines of code:
print the uninitialized static in onCreate of your activity -> should print null
initialize the static. print it -> value would be non null
Hit the back button and go to home screen. Note: Home screen is another activity.
Launch your activity again -> the static variable will be non-null
Kill your application process from DDMS(stop button in the devices window).
Restart your activity -> the static will have null value.
I referred to this link Android static object lifecycle
Ok i'm following an android book and they are adding settings to a sudoku game using a class that extends PreferenceActivity, this class is called by an intent and all it does is addPreferencesFromResource(R.xml.settings), this approach has been deprecated and its not working anymore, here is the code from the book:
package org.example.sudoku;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
}
}
Now i have looked into this matter and found that you have to instance a PreferenceManager in order to do this, but in the example i found they extends the Prefs class from PreferenceFragment (not PreferenceActivity as in the book), i managed to work on the code as follows:
/*
* this is for use from API version 11 and after...
*
*/
package org.example.sudoku;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
public class Prefs extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
PreferenceManager.setDefaultValues(getActivity(),
R.xml.settings, false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
}
}
But this doesn´t do the job, i don´t know if its because i am calling this class from an intent and this class extends PreferenceFragment instead of PreferenceActivy or this is not the way of doing this thing, can someone help me out to understand this?
final String PREF_SETTINGS_FILE_NAME = "PrefSettingsFile";
To read the values of your preference variables.
SharedPreferences preferences = getSharedPreferences(PREF_SETTINGS_FILE_NAME, MODE_PRIVATE);
prefSettingsValue1= preferences.getInt("value1", 1); // default value of prefSettingsValue1 will be 1 in case you are trying to read a non-existent value. You can specify it according to your wish. (like I have done for the next value)
prefSettingsValue2= preferences.getInt("value2", 0);
prefSettingsValue3= preferences.getInt("value3", 1);
To write values into your preference variables.
SharedPreferences preferences = getSharedPreferences(PREF_SETTINGS_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("vaule1", prefSettingsValue1);
editor.putInt("value2",prefSettingsValue2);
editor.putInt("value3",prefSettingsValue3);
editor.commit();
Note : No need to use any XML file to store the preferences. Just save the values in the Preference variables and read them later in you application. Not just integers, you can also get and put Strings by using getString and putString functions to read and write, respectively. Also, you do not need to extend any Preference Activity/Fragment.
I want to store three strings as user preferences for my app. I have a nice layout already set up, it's just a matter of saving the strings to the SharedPreferences. I would also like to know how I can retrieve these strings in the next activity. Below is my current code, I would greatly appreciate it if someone could show me how I can add this functionality to the code. This is a roadblock in my app I have been trying to get past for a few days now.
Code for main activity:
package com.amritayalur.mypowerschool;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
String str;
String username;
String password;
String url;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
textViewTitle = (TextView) findViewById(R.id.textViewTitle);
textViewDesc = (TextView) findViewById(R.id.textViewDesc);
editTextURL = (EditText) findViewById(R.id.editTextURL);
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPass);
//Start TextView
textViewTitle.setText("MyPowerSchool");
//button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if ( ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) )
{
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
// TODO Auto-generated method stub
//Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);
//startActivity(i);
}
};
});}}
Just set up these class variables in the Activities you want to use SharedPreferences:
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
And then to store string values:
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3");
editor.commit(); // persist the values
To read them in another Activity/class:
mySharedPreferences = getSharedPreferences(MY_PREFS, prefMode);
String string1 = mySharedPreferences.getString("key1", null);
String string2 = mySharedPreferences.getString("key2", null);
This is not hard to look up and find examples of. By going to the documentation in Android Developers you will find a link to this useful site on how to use data storage on Android phones.
Somehow define your preference fields names. It is common practive to do it via final static field. It can be done in your activity class in some separate class. Give them some uniq names.
public static final String MY_PARAM_1 = "com.amritayalur.mypowerschool.PARAM_1";
public static final String MY_PARAM_2 = "com.amritayalur.mypowerschool.PARAM_2";
Get shared preference instance
// "this" is your activity or context
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
To put your strings in preferenes you need to create an editor
SharedPreferences.Editor editor = prefs.edit();
Then put your values
editor.putString(MY_PARAM_1, "First string");
editor.putString(MY_PARAM_2, "Second string");
Then you are done, commit your changes
editor.commit();
To get your values back use the getString method
// specify default value in case if preferences are empty or current key is not set
prefs.getString(MY_PARAM_1, "default value");
You can add multiple values like this:
preferences.edit()
.putLong(DAYS_LEFT, premiumStatus.getDaysLeft())
.putString(KEY, premiumStatus.getKey())
.putString(ID, premiumStatus.getId())
.apply();
First setup shared preference. For this, set this line before on create :
private Context mContext;
then put this in oncreate :
mContext = this;
Then store your value on SharedPreferece:
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(mcontext);
SharedPreferences.Editor editor = settings.edit();
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
editor.putString("kye1", url);
editor.putString("kye2", username);
editor.putString("kye3", password);
Then retrieve your Value from another class (or from any where ) :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mcontext);
String value1=settings.getString("key1",""); // for url
String value2=settings.getString("key2",""); // for name
String value3=settings.getString("key3",""); // for password
Then set this "value1/2/3" any where.
I have a list view. I am getting check box when I check it.
But I want to get same status when I restart the application. If is there any way to do it please reply me.
I am really new to android.
my code is follows:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//I am getting status of check box here. If I click on file check box is appearing to me. //I want to be store always for true.
String keyword = value[position];
mediaPlayer.reset();
try
{
mediaPlayer.setDataSource("/sdcard/"+keyword+".mp4");
mediaPlayer.prepare();
mediaPlayer.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
thanks in advance.
You may use SharedPreference for your values to stay even if your application gets closed. Use a default value in your constants file.
For eg:
Create a class for storing all SharedPreferences.
In that give,
private static SharedPreferences sharedPref;
public static final String PREFERENCE_DATA = "some data";
Inside constructor give,
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
Add setter/getter methods for each preference value.
public static void setPreferenceData(String data) {
if (sharedPref != null) {
Editor editor = sharedPref.edit();
editor.putString(PREFERENCE_DATA, data);
editor.commit();
}
}
public static String getPreferenceData() {
String data = "data";
if (sharedPref != null) {
status = sharedPref.getString(PREFERENCE_DATA,your variable name stored in constants);
}
return data;
}
So when you want to set any data, use setPreferenceData and when you want to fetch value use getPreferenceData.
You need to save the state of the checkbox in the onPause method of your activity. After onPause was called the system can close your application without any further warning as described in the Activity Documentations
To save the checked items your onPause method would look something like this:
#Override
protected void onPause() {
super.onPause();
long[] checkedBoxes = getListView.getCheckedItemIds();
setPreferenceData(checkedBoxes);
}
You only have to modify Mathews Code in a way that allows you to save long Arrays.
Now you can get these values from the sharedPreferences file in the onCreate method and set the checkboxes accordingly in your Adapter code.