Android Studio - Can't Read preferenceSettings - java

I am trying to save user's language using SharedPreference. MainActivity is my main activity and SettingsActivity is where I ask and save user's language.
Saving:
private SharedPreferences preferenceSettings;
private SharedPreferences.Editor preferenceEditor;
private static final int PREFERENCE_MODE_PRIVATE = 0;
public void save(String lg){
preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("language", lg);
preferenceEditor.commit();
finish();
}
Reading:
preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
String LanguageS = preferenceSettings.getString("language", "0");
with this code, I can successfully save and read from same activity(SettingsActivity) but when I return to my main activity, I can't read.
I am using this code to read from my main activity but it always returns "0".
private SharedPreferences preferenceSettings;
private SharedPreferences.Editor preferenceEditor;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static String Lang = "0";
preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
Lang = preferenceSettings.getString("language", "0");
What am I doing wrong? I am controlling these lines for almost 1 hour but couldn't find any mistakes.

This is happening beacuse, the method that you're using getPreferences(PREFERENCE_MODE_PRIVATE)
returns the preferences saved by Activity's class name as described here :
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
So, when you're saving the prefs in SettingsActivity it's being saved under the name "SettingsActivity"
but when you're getting the prefs in MainActivity it's returning you the prefs saved under name "MainActivity"
So, you should use getSharedPreferences (String name, int mode) method with the same name instead.

Instead of using getPreferences(int mode), you should use the getSharedPreferences(String name, int mode)
If you read the java doc on the getPreferences(int mode) it says:
Retrieve a {#link SharedPreferences} object for accessing preferences
that are private to this activity.
This simply calls the underlying
{#link #getSharedPreferences(String, int)} method by
passing in this activity's class name as the preferences name. #param
mode Operating mode.
Use {#link #MODE_PRIVATE} for the default
operation, {#link #MODE_WORLD_READABLE} and {#link
MODE_WORLD_WRITEABLE} to control permissions.
#return Returns the single SharedPreferences instance that can be used
to retrieve and modify the preference values.

Related

Calling a function in another class in Android Java

I have been looking around for an answer to this question and found a number of similar questions but none seemed to be quite similar enough and none of the solutions I found around the web solved the problem.
For an Android app I am writing, I need to save the Android preferences to a database. In order to do this I wanted to create a separate class with functions that I can call to sync, update etc the preferences. So this is the problem
Call initiateSaveSettings() in the syncSettings class from the mainActivity
The way I try to do this now is by calling:
syncSettings sync = new syncSettings();
sync.initiateSettingSave();
Into the syncSettings class:
public class syncSettings extends Context {
public void initiateSettingsSave(){
PreferenceManager.setDefaultValues(syncSettings.this, R.xml.root_preferences, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
}
etc.
The problem is that the SharedPreferences requires the extends Context and in order for that to work Android Studio gives the error to change syncSettings to
public abstract class syncSettings extends Context {
Doing this gives an error for new syncSettings() when calling the function, taking the abstract away gives the error in the syncSettings class. What can I do to make this work? If you need more information please let me know.
Thank you in advance.
Edit: I am very much new to Android development so if I say or ask something dumb, that may very well be why...
Try this:
public class syncSettings {
private Context context;
public syncSettings(Context context){
this.context = context;
}
public void initiateSettingsSave(){
PreferenceManager.setDefaultValues(syncSettings.this, R.xml.root_preferences, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
}
And in your activity:
syncSettings sync = new syncSettings(this);
sync.initiateSettingSave();
I don't understand your reason for extends Context Ten. But you can use this class.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class PrefUtils {
/**
* Called to save supplied value in shared preferences against given key.
* #param context Context of caller activity
* #param key Key of value to save against
* #param value Value to save
*/
public static void saveToPrefs(Context context, String key, String value) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString(key,value);
editor.commit();
}
/**
* Called to retrieve required value from shared preferences, identified by given key.
* Default value will be returned of no value found or error occurred.
* #param context Context of caller activity
* #param key Key to find value against
* #param defaultValue Value to return if no data found against given key
* #return Return the value found against given key, default if not found or any error occurs
*/
public static String getFromPrefs(Context context, String key, String defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
try {
return sharedPrefs.getString(key, defaultValue);
} catch (Exception e) {
e.printStackTrace();
return defaultValue;
}
}
/**
*
* #param context Context of caller activity
* #param key Key to delete from SharedPreferences
*/
public static void removeFromPrefs(Context context, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = prefs.edit();
editor.remove(key);
editor.commit();
}
}

Save values in non activity class

I have a public class named "Values", I have values from my SettingsActivty stored inside this class. I have noticed that once I reset/close the app the values reset to default. I expected this to happen just like it does in activities.
Here is the code:
public class Values {
//General Values
public boolean vibrationEnabled = true;
//Single Player Values
public static float SPBackgroundNumber = 0;
public static boolean resetScoreSP = false;
}
How would I be able to save these values and reopen them since it's not part of an activity?
Use sharedPreferences to save and retrieve values.
To save values:
SharedPreferences sharedPref=getSharedPreferences(FileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPref.edit();
editor.putString("key_value", data);
editor.apply();
To retrieve values:
SharedPreferences sharedPref=getSharedPreferences(FileName, Context.MODE_PRIVATE);
name1=sharedPref.getString("key_value","default_value");
You need to declare FileName outside the class. Each data is identified the specified key_value

How can I add methods that I often use to android studio?

For example,
public void show_message(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
I want this method add auto Activity.java when create new activity or java class.
I want to save different methods like this and include it in the my project quickly where it is needed.
What you should do is create a BaseActivity and make your activity extend this BaseActivity. Add all the default methods in this activity so you can use them everywhere. You can refer this Github project for reference. It uses MVP.
Here is direct link to BaseActivity.
You just need to make a Common Utilities class. Just copy and paste the class in whatever project you are using it. Just make its method access specifiers as public staic so that you can easily access it.
For e.g.
CommonUtilities.showToastMessage(String text);
What I would do is create a config class and store all these small things in it. For example have a look at this :
public class Config {
public Context context;
public String sharedPrefsName;
public String carTablesName, carsTableCarColumn, databaseName;
public int databaseNewVersion, databaseOldVersion;
public boolean showNotificationsToCustomer;
public String customerNotificationState;
public String userMobile;
public SharedPreferences preferences;
public String customerChatTableName;
public String customerChatMessageColumn;
public String customerChatSentByCustomerColumn;
public String customerChatTimeColumn;
public String loggedInUserId;
public String loggedInUserName;
public String customerChatSupportNotifyingUrl;
public Config(Context context) {
this.context = context;
customerChatSupportNotifyingUrl = "";
customerChatTableName = "customerChat";
customerChatMessageColumn = "customerMessage";
customerChatTimeColumn = "sentOn";
customerChatSentByCustomerColumn = "isSentByCustomer";
sharedPrefsName = context.getString(R.string.shared_prefs_login_validator);
preferences = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
customerNotificationState = context.getString(R.string.customer_notification_state);
showNotificationsToCustomer = preferences.getBoolean(customerNotificationState, true);
carTablesName = context.getString(R.string.user_car_table);
carsTableCarColumn = context.getString(R.string.user_car_table_car_column);
databaseName = context.getString(R.string.user_db);
databaseNewVersion = 3;
databaseOldVersion = 1;
loggedInUserId = preferences.getString(context.getString(R.string.user_db), "");
userMobile = preferences.getString(context.getString(R.string.user_mobile), "");
loggedInUserName = preferences.getString(context.getString(R.string.user_name), "");
}
}
I've placed all the constants in a single file so you need not look at them always. If your app grows in size this would be extremely useful.
For using a progress dialog I use a class like this :
public class MyProgressDialog extends ProgressDialog {
String title, message;
public MyProgressDialog(Context context, String title, String message) {
super(context);
if (!title.equals("")) this.setTitle(title);
this.setMessage(message);
this.setCancelable(false);
this.setIndeterminate(false);
}
}
This is nothing but a single class that extends ProgressDialog.So you can aquire all the functionalities of the progress dialog class.
Similarly for toast you could do the same. If you want them to appear when the activity gets created simply keep this:
MyProgressDialog dialog=new MyProgressDialog(this,"title","message");
dialog.show();
in your activity's onCreate() method. You can do the same for toast too.
In case if it is a java class just create a constructor and keep that snippet in that constructor..
You need to read about "File Templates" https://riggaroo.co.za/custom-file-templates-android-studio/ this a large topic, but this is worth it.

Permanent Objects passed from one Activity to another

I must pass an ArrayList from one Activity A to another Activity B.
I did it using getSerializableExtra and putExtra methods. I already know the meaning of these methods, but I don't know if stuff that I passed using them is stored permanently in the new activity or if it is necessary to reload activity A in order to retrieve my data in B.
So the question is: how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?
Don't use Preference Class! Preferences are only used for settings values. For passing data to another Activity use Serializable or Parcelable. Remember that all the objects which will be passed to another activity have to implement Serializable or Parcelable. So you extend the ArrayList to a custom Class which implements Parcelable or Serializable.
You do this like this:
Intent intent = new Intent(getContext(), SomeClass.class);
intent.putSerializableExtra("value", <your serializable object>);
startActivity(intent);
and receive them like
YourObject yourObject = getIntent().getSerializableExtra("value")
or look here for Parcelable
Help with passing ArrayList and parcelable Activity
Data processed in Activity A does not need to process again in Activity B. If the data is computed in A and you send it to B computed, B receives it computed already.
Here are some ways to do it right: http://developer.android.com/guide/topics/data/data-storage.html
You can use Preference class, in which you can define its static instance. Than create variable according your desire datatype (even ArrayList). Make property for get and set of this variable.
Set the value on splash screen and get anywhere in application where you need.
Try this, if you need , I will upload code also.
I have written some code regarding that, it would help other activities to fetch data easily, use this when the data is not confidential,
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);
}
}
if your question is "how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?" Than I have better solutions for you.
Create a Class Memdata.java
public class Memdata{
private static Memdata instance = null;
private String userobject;
public static Memdata getInstance(){
if ( instance == null){
instance = new Memdata();
}
return instance;
}
public String getuserobject() {
return userobject;
}
public void setuserobject(String userobject) {
this.userobject= userobject;
}
}
on You Splash Screen' onCreate method, set the value
Memdata obj = Memdata.getInstance();
obj.setuserobject("hello");
Than in any activity, where you want to access this variable, just make its object and get value.
Like in MyActivity class
Memdata obj = Memdata.getInstance();
String str = obj.getuserobject()
You can define any type of variable according your requirement.
You can extend the base Application class and add member variables to it:
public class MyApp extends Application {
private String appLevelString;
public String getAppLevelString() {
return this.appLevelString;
}
public void setAppLevelString(String val) {
this.appLevelString= val;
}
}
You will have to update the manifest file as follows:
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:name="MyApp">
You can get and set data like this:
//For setting
((MyApp) this.getApplication()).setAppLevelString("Test string");
//For getting
String str = ((MyApp) this.getApplication()).getAppLevelString();

Creating a SharedPreferencesUtil

This is my first time using SharedPreferences in my Android app. Since I will be using the SharedPreferences over and over again, I have created a utility class called SharedPreferencesUtil which contains a lot of static methods which allow me to access and modify the values. For example:
/**
* This method is used to add an event that the user
* is looking forward to. We use the objectId of a ParseObject
* because every object has a unique ID which helps to identify the
* event.
* #param objectId The id of the ParseObject that represents the event
*/
public static void addEventId(String objectId){
assert context != null;
prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0);
// Get a reference to the already existing set of objectIds (events)
Set<String> myEvents = prefs.getStringSet(Fields.MY_EVENTS, new HashSet<String>());
myEvents.add(objectId);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(Fields.MY_EVENTS, myEvents);
editor.commit();
}
I have a few of questions:
1. Is it a good decision to have a utility class SharedPreferencesUtil ?
2. Is the use of assert proper?
3. Is that how I will add a String to the set?
In general I think utility classes like this are fine. A few recommendations I'd have are:
Initialize your Context in a subclass of Application (in Application.onCreate()) and store a reference to that in your utility class. You don't have to worry about a memory leak if you ensure you only use the application context instead of an Activity context, and since SharedPreferences doesn't use any theme attributes, there's no need to use an Activity context anyway.
Check and throw an exception warning that the class hasn't been initialized yet if you try to use it without initialization. This way you don't need to worry about checking for a null context. I'll show an example below.
public final class Preferences {
private static Context sContext;
private Preferences() {
throw new AssertionError("Utility class; do not instantiate.");
}
/**
* Used to initialize a context for this utility class. Recommended
* use is to initialize this in a subclass of Application in onCreate()
*
* #param context a context for resolving SharedPreferences; this
* will be weakened to use the Application context
*/
public static void initialize(Context context) {
sContext = context.getApplicationContext();
}
private static void ensureContext() {
if (sContext == null) {
throw new IllegalStateException("Must call initialize(Context) before using methods in this class.");
}
}
private static SharedPreferences getPreferences() {
ensureContext();
return sContext.getSharedPreferences(SHARED_PREFS_FILE, 0);
}
private static SharedPreferences.Editor getEditor() {
return getPreferences().edit();
}
public static void addEventId(String eventId) {
final Set<String> events = getPreferences().getStringSet(MY_EVENTS, new HashSet<String>());
if (events.add(eventId)) {
// Only update the set if it was modified
getEditor().putStringSet(MY_EVENTS, events).apply();
}
}
public static Set<String> getEventIds() {
return getPreferences().getStringSet(MY_EVENTS, new HashSet<String>());
}
}
Basically, this avoids you having to always have a Context on hand to use SharedPreferences. Instead, it always retains a reference to the application context (provided you initialize it in Application.onCreate()).
You can check out how to use SharedPreferences properly here and check another example on the Android docs.
EDIT: As to your design question, it really shouldn't matter to have a static class or not.
Your SharedPreferences are shared throughout the app, and although you can create multiple SharedPreferences objects, they will essentially store and save to the same part of your app as if you just used one object.

Categories

Resources