I have activity and service, I would like to get a reference to Service integer, that is being updated from time to time in Service. My problem is that in my Activity I only get that integer first declared Value (for instance 0).
My main goal is to know Services' updated value every time I start my program.
Main activity:
if(Service.doesCounter>0){
//do something
//in this state Service.doesCounter always is 0(checked by log)
}
Service:
public static int doesCounter=0; // declared after class as class memeber
//code where I start my method does();
.....
public void does(){
doesCounter++;
Log.e("cccccc","Service Counter "+doesCounter); // everything ok, value is changing as suppose to.
}
Edit
my Shared Preferences class:
public class AppPreferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private static final String APP_SHARED_PREFS = "com.aydabtu.BroadcastSMS_preferences"; // Name of the file -.xml
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPreferences(Context context)
{
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean getAnything() {
return appSharedPrefs.getBoolean("Anything", false);
}
public void setAnything(Boolean text) {
prefsEditor.putBoolean("Anything", text);
prefsEditor.commit();
}
Then from Main Activity:
public class MainActivity extends Activity {
protected AppPreferences appPrefs;
appPrefs = new AppPreferences(getApplicationContext());
appPrefs.setAnything(fasle);
Then from Service:
appPrefs = new AppPreferences(getApplicationContext());
And when this happens all earlier made changes are reseted, how to make service and MainActivity use same prefs? Maybe I can somehow make AppPrefs class static?
Using static class fields is considered a bad practice in android.
Your app's resources may be revoked by the os and another process of your app may be re-initialized whenever the user gets back to it. In this case you will loose doesCounter updates. I don't know if this is the case (it should work in a common scenario where your app is foregrounded, unless you are running your service in another process (using the flag isolatedProcess) .
The easiest way to achieve what you are trying to do "the android way" is to store the doesCounter in SharedPreferences.
One way to achieve that is having a static class like this:
public class PrefUtils {
private final static String NUM_DOES = "NumDoes";
public static int getNumDoes(Context c)
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = c.getSharedPreferences(PREF_NAME, mode);
return mySharedPreferences.getInt(NUM_DOES, 0);
}
public static void setNumDoes(int numDoes , Context c)
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = c.getSharedPreferences(PREF_NAME, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt(NUM_DOES, numDoes);
editor.commit();
}
And you are done. Just call PrefUtils.getNumDoes / setNumDoes
Related
I am an android beginner and tried almost every method to use Shared Preferences but when I try to get value in nonactivity class method doesn't work ONLY IF APP REMOVED FROM RECENT APPS.
My Scenario is like:
Class LocationRequestHelper.java
import android.content.Context;
import android.preference.PreferenceManager;
public class LocationRequestHelper {
...
...
public static String getUserId() {
return MainActivity.preferences.getString("userId","");
}
public static void setUserId(String userId) {
MainActivity.preferences.edit().putString("userId", userId ).commit();
}
}
MainActivity
public class MainActivity extends FragmentActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
public static SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
LocationRequestHelper.setUserId("1");
....
....
Utils
public class Utils {
public static void getLocationUpdates(final Context context, final Intent intent, String broadcastevent){
LocationResult result = LocationResult.extractResult(intent);
if (result != null) {
List<Location> locations = result.getLocations();
Location firstLocation = locations.get(0);
accuracy = firstLocation.getAccuracy();
LocationData data = new LocationData();
// MY FUNCTION DOESN'T WORK HERE
data.setUsrid(LocationRequestHelper.getUserId());
updateServer(data);
}
}
getLocationUpdates is called from BroadcastReceiver
Now problems appears after I try to get userID using
LocationRequestHelper.getUserId();
EDITED : Added Broadcast code
LocationUpdatesBroadcastReceiver
public class LocationUpdatesBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "LUBroadcastReceiver";
public static final String ACTION_PROCESS_UPDATES ="PROCESS_UPDATES";
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_PROCESS_UPDATES.equals(action)) {
Utils.getLocationUpdates(context,intent,"PROCESS_UPDATES");
}
}
}
}
NOTE:: THIS WORKS FINE IF APP IS IN BACKGROUND. BUT CRASHES AFTER I KILL FROM RECENT APPS.
Please tell me how I can send saved user id in my api call?
sorry for caps but this is main problem :P
The reason the app is crashing is that when it is killed any static variables become null. However you are still trying to access the SharedPreferences from the broadcast receiver and as such are getting a NPE.
The first thing you can do is update your LocationRequestHelper class to accept a context in the method rather than using the static SharedPreferences:
public class LocationRequestHelper {
//...
public static String getUserId(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString("userId","");
}
public static void setUserId(Context context, String userId) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("userId", userId ).commit();
}
}
Then update you MainActivity to get rid of the SharedPrefs business and change the call to:
LocationRequestHelper.setUserId(this, "1");
And the Utils class to:
data.setUsrid(context, LocationRequestHelper.getUserId());
I've come across an issue with trying to append a settings preference string onto another string I have.
Currently I have:
public class MyApp extends Application {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
public static final String USER_LOGIN = "https://example.com";
#Override
public void onCreate(){
super.onCreate();
myFunction(USER_LOGIN);
}
What I'm trying to achieve this with:
public class MyApp extends Application {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
public static final String USER_LOGIN = "https://" + preferences.getString(SettingsFragment.USER_SITE, "");
#Override
public void onCreate(){
super.onCreate();
myFunction(USER_LOGIN);
}
However, Android Studio is telling me "non-static field 'preferences' cannot be referenced from a static context". How would I be able to reference this field?
Since "SharedPreferences preferences" is a Object's member, it can not be used by a static member. So change :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
to
static SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Just assign them inside onCreate :
public class MyApp extends Application {
SharedPreferences preferences;
private String USER_LOGIN;
#Override
public void onCreate(){
super.onCreate();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
USER_LOGIN = "https://" + preferences.getString(SettingsFragment.USER_SITE, "");
myFunction(USER_LOGIN);
}
}
Is your function in the same activity? If yes try not to pass the static var?
Instead access it directly in the "myfunction"..
I see no point to call that way and make it static at the same time.
I want to get a string from my shared preference file and use for more classes, but I don't know why not work.
My reader class is:
import android.app.Activity;
import android.content.SharedPreferences;
public class A {
public static String url2;
public void execute() {
String URLPref = "URL";
SharedPreferences prefs = getSharedPreferences("com.exam.search_preferences",Activity.MODE_PRIVATE);
url2 = prefs.getString(URLPref , "");
}
private SharedPreferences getSharedPreferences(String string,
int modePrivate) {
return null;
}
}
And the second class that uses the string
public class SearchHome extends Activity {
static String url2;
A cls2= new A();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
cls2.execute();
url2 = A.url2;
Toast.makeText(getApplicationContext(),"URL:" + url2 ,
Toast.LENGTH_LONG).show();
...
Sorry for my bad english, I never learned.But I'm trying!
You need to pass the Context to your class A, because you can get the SharedPreferences from a Context object. NOTE, an Activity is a Context to some extend
public class A {
public static String url2;
/** #param context used to get the SharedPreferences */
public void execute(Context context) {
String URLPref = "URL";
SharedPreferences prefs = context.getSharedPreferences("com.exam.search_preferences",Activity.MODE_PRIVATE);
url2 = prefs.getString(URLPref , "");
}
}
And then pass the Context to your execute method
public class SearchHome extends Activity {
static String url2;
A cls2= new A();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
// pass context 'this' to the execute function
// This works, because SearchHome extends Activity
cls2.execute(this);
url2 = A.url2;
...
if your data is not confidential it would be a lot easier if you can make a class specially for shared preference and have other activities access it. you will save a lot of time and code will be a lot simpler to follow up
public class HelperShared {
public static final String score = "Score";
public static final String tag_User_Machine = "tag_User_Machine",
tag_Machine_Machine = "tag_Machine_Machine",
tag_Draw_Machine = "tag_Draw_Machine",
tag_Total_Machine = "tag_Total_Machine";
public static SharedPreferences preferences;
public static Editor editor;
public HelperShared(Context context) {
this.preferences = context.getSharedPreferences(score,
Activity.MODE_PRIVATE);
this.editor = preferences.edit();
}
/*
* Getter and Setter methods for Machine
*/
public void setUserMachine(int UserMachine) {
editor.putInt(tag_User_Machine, UserMachine);
editor.commit();
}
public void setMachineMachine(int MachineMachine) {
editor.putInt(tag_Machine_Machine, MachineMachine);
editor.commit();
}
public void setDrawMachine(int DrawMachine) {
editor.putInt(tag_Draw_Machine, DrawMachine);
editor.commit();
}
public void setTotalMachine(int TotalMachine) {
editor.putInt(tag_Total_Machine, TotalMachine);
editor.commit();
}
public int getUserMachine() {
return preferences.getInt(tag_User_Machine, 0);
}
public int getMachineMachine() {
return preferences.getInt(tag_Machine_Machine, 0);
}
public int getDrawMachine() {
return preferences.getInt(tag_Draw_Machine, 0);
}
public int getTotalMachine() {
return preferences.getInt(tag_Total_Machine, 0);
}
}
private SharedPreferences getSharedPreferences(String string,
int modePrivate) {
return null;
}
problem is here.
return null;
you have to return valid SharedPreferences object. otherwise you will always get NullPointerException.
Call this when you want to put a pref:
putPref("myKey", "mystring", getApplicationContext());
Call this when you want to get a pref:
getPref("myKey", getApplicationContext());
You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
Different Modes:
1 MODE_APPEND
This will append the new preferences with the already exisiting preferences
2 MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default
3 MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference instance has already been loaded
4 MODE_PRIVATE
By setting this mode , the file can only be accessed using calling application
5 MODE_WORLD_READABLE
This mode allow other application to read the preferences
6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
Read More
You just need to make shared prefrences object in class where you want to have data
SharedPreferences prefrences = getSharedPreferences("my prefs",MODE_PRIVATE)
Editor editor = prefrences.edit();
String s = edit.getString("your key",value);
hope it helps !
When using a thread/task within an android service that implements the OnSharedPreferenceChangeListener interface, the changes made in the preference screen aren't reflected back to the thread/task object within the android service.
I want to accomplish two things:
SharedPreference data should be loaded when MyTask is constructed and initialized.
When preference change occurs, MyTask object must be updated with the new preference values set in the preference screen.
The problem is: preference initialization and preference changes are not reflected to the MyTask object.
This is my setup (only essential parts are mentioned):
MyService.class:
public class MyService extends Sevice {
private MyTask myTask;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!serviceStarted) {
serviceStarted = true;
myTask = new MyTask(this);
Thread t = new Thread(myTask);
t.start();
}
return Service.START_STICKY;
}
#Override
public void onDestroy() {
myTask.cancel();
super.onDestroy();
}
}
MyTask.class:
public MyTask implements Runnable, OnSharedPreferenceChangeListener {
private Context mContext;
private boolean mCancelled;
public MyTask(Context context) {
mContext = context;
}
#Override
public void run() {
while(!mCancelled) {
// do something
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// FIXME: DOESN'T GET CALLED after change in preference!!!!
Log.d(TAG, "Key= " + key);
}
public void cancel() {
mCancelled = true;
}
}
preference_devices.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:key="pref_category_devices"
android:title="#string/pref_category_devices_title" >
<CheckBoxPreference
android:defaultValue="true"
android:key="pref_devices_server"
android:title="#string/pref_devices_server_title" />
</PreferenceCategory>
</PreferenceScreen>
I have tried coding a SharedPreferences listener object as a member field of the MyTask class and register/unregister the listener from the provided context, but that didn't work either. These changes also didn't work:
MyTask.class (using SharedPreference listener as field member of class):
public MyTask implements Runnable {
private Context mContext;
private boolean mCancelled;
private boolean mServerEnabled;
private SharedPreferences mPrefs;
private SharedPreferences.OnSharedPreferenceChangeListener
mPreferenceListener;
public MyTask(Context context) {
mContext = context;
mPrefs = mContext.getSharedPreferences("pref_category_devices",
Context.MODE_PRIVATE);
mPreferenceListener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
// FIXME: DOESN'T GET CALLED after change in preference!!!!
Log.d(TAG, "Key= " + key);
}
};
mPrefs.registerOnSharedPreferenceChangeListener(mPreferenceListener);
// set the initial value of the preference setting
mServerEnabled = mPrefs.getBoolean("pref_devices_server", false);
}
#Override
public void run() {
while(!mCancelled) {
// do something
}
}
public void cancel() {
mCancelled = true;
}
}
I have now reached the point of throwing my computer out of the window :(
Any help in the right direction is highly appreciated :)
EDIT: In the code
mPrefs = mContext.getSharedPreferences("pref_category_devices", Context.MODE_PRIVATE);
I assumed that the first argument should be the preference category name of the preference file, like: "pref_category_devices". THIS IS INCORRECT! The first argument must be a shared preference file name. That didn't solve the problem, but at least now you know to not fall for this pitfall.
=== SOLUTION: === See answer of Mr_and_Mrs_D + code below this line:
Change in MyTask:
mPrefs = mContext.getSharedPreferences("pref_category_devices",
Context.MODE_PRIVATE);
into:
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mPreferenceListener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("preference_name_here")) {
mPrefValue = sharedPreferences.getBoolean(key, false);
// do something with boolean pref value
}
}
};
mPrefs.registerOnSharedPreferenceChangeListener(myPreferenceListener);
Where mPrefValue is a field member of type boolean in MyTask that needs to be set when the "preference_name_here" preference changes.
Change :
private volatile boolean mCancelled; //otherwise the myTask thread may never stop
For your problem :
if (!serviceStarted) {
serviceStarted = true;
myTask = new MyTask(this);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.registerOnSharedPreferenceChangeListener(myTask); //err, you must register
Thread t = new Thread(myTask); t.start();
}
Docs :
These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity.
[emphasis mine]
Edit : your second snippet probably fails cause you get the wrong shared prefs - you must get the default ones - I thought it was failing because of :
SharedPreferences.onSharedPreferenceChangeListener not being called consistently
Hi i have a class (MyCustomForm.xml) which i use as a LoginForm for the user.
Now i want to save and load the value from the username(EditText) from the LoginForm using SharedPreferences but i do not know how to set the value of username saved by SharedPreferences into the EditText in LoginForm(MyCustomForm.xml).
I was thinking to save the value in OnPause in my Main.xml and load the value through OnCreate in the class MyCustomForm.xml
Generaly i would like to use SharedPreferences globaly.
How would this look like?
Can somebody please help me to get on the right track?
It was thinking something like this Main.xml:
public class AndroidLogin extends Activity implements OnClickListener {
#Override
protected void onPause() {
super.onPause();
Editor e = mPrefs.edit();
e.putString(USERNM, username);
e.commit();
}
}
Code MyCustomForm (LoginForm):
public class MyCustomForm extends Dialog {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
userTest.setText(USERNM);
}
}
You can do something like this :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(YouActivity.this);
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
server.setText(servername); // EditText
And you store data like this :
SharedPreferences.Editor editor = settings.edit();
editor.putString("server", "serverName");
EDIT :
This piece of code should do the trick for you :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
You need to use the Prefs & Editor
SharedPreferences spOptions;
SharedPreferences.Editor spOptionEditor;
spOptions = getSharedPreferences("yourKey", 0);
spOptionEditor = spOptions.edit();
string username = spOptions.getString("USERNM", null)
null represents the default value if you don't have anything stored yet
You store the data like this:
spOptionEditor.putString("USERNM", txtUsername.getText().toString());
spOptionEditor.commit();
Generally I would recommend you to save the username on a valid login, and not in any lifecycle method.
Then change myForm to this:
public class MyCustomForm extends Dialog {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
String s = getContext().getSharedPreferences("prefName", Mode.PRIVATE).getString(USERNM);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
userTest.setText(s);
}
}
public void sharedPrefernces() {
sh_Pref = getSharedPreferences("Login Credentials", MODE_PRIVATE);
toEdit = sh_Pref.edit();
toEdit.putString("Username", username);
toEdit.putString("Password", password);
toEdit.commit();
}
Read more: http://mrbool.com/how-to-implement-shared-preferences-in-android/28370#ixzz34ymRp6mN
Just create a file called preferences... and store the value to it using different methods.
Use the methods people have suggested to put and get data from them...
public class Settings extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
public static final String PREFS_PRIVATE = "PREFS_PRIVATE";
public static final String MASTERKEY = "!##$%^&*";
public static final String KEYA = "KEYA";
public static final String KEYB = "KEYB";
public static final String KEYC = "KEYC";
--- the create and get methods for getting and sharing data in the prefs... .....
public static void createPreference(Context context){
getPrefs(context).edit().putString(KEYA, "Default");
getPrefs(context).edit().putInt(KEYB, 0);
getPrefs(context).edit().putLong(KEYC, 0);
getPrefs(context).edit().putBoolean(KEYD, false);
getPrefs(context).edit().commit();
}
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREFS_PRIVATE, 0);
}
public static String getUsername(Context context) {
getPrefs(context).getString(USERNAME, "default");
}
public static void setUsername(Context context, String value) {
getPrefs(context).edit().putString(USERNAME, value).commit();
}
}
..... so on and so forth..... Just implement it if you find any doubt or any thing that you need in more specific please let me know.