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.
Related
I have been searching for the correct answer everywhere, but couldn't find it anywhere. That is why I am posting this question, this may look very similar to other questions but I didn't find the answer to this yet. I have to retrieve the user data that was saved during the login on Android device and I want to use the same data in a fragment, I tried using several answers found on StackOverflow, none of them worked for me. Look at the code below, how can I get the user values into strings?
SharedPreferences preferences = getActivity().getSharedPreferences("mysharedpref",Context.MODE_PRIVATE);
String user_name = preferences.getString("user_id",null);
String password = preferences.getString("role", null);
I have to pass these string values to a URL, but it doesn't work. I also checked passing values manually, it's working. For example, if I take assign values to the above strings like
String user_name="admin";
String password="administrator";
Best way to use your SharedPrefernce is by using your appContext that is accessible to the whole App(Common SharedPrefernce and accessible Everywhere).
Define your SharedPrefernce instance in your Application class with get and set methods as below : (If you have not created the Application class then create one as below, This class is called at the start of your app)
public class Application extends android.app.Application {
private static Application _instance;
private static SharedPreferences _preferences;
#Override
public void onCreate() {
super.onCreate();
_instance = this;
}
public static Application get() {
return _instance;
}
/**
* Gets shared preferences.
*
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences() {
if (_preferences == null)
_preferences = PreferenceManager.getDefaultSharedPreferences(_instance);
return _preferences;
}
//set methods
public static void setPreferences(String key, String value) {
getSharedPreferences().edit().putString(key, value).commit();
}
public static void setPreferences(String key, long value) {
getSharedPreferences().edit().putLong(key, value).commit();
}
public static void setPreferences(String key, int value) {
getSharedPreferences().edit().putInt(key, value).commit();
}
public static void setPreferencesBoolean(String key, boolean value) {
getSharedPreferences().edit().putBoolean(key, value).commit();
}
//get methods
public static String getPrefranceData(String key) {
return getSharedPreferences().getString(key, "");
}
public static int getPrefranceDataInt(String key) {
return getSharedPreferences().getInt(key, 0);
}
public static boolean getPrefranceDataBoolean(String key) {
return getSharedPreferences().getBoolean(key, false);
}
public static long getPrefranceDataLong(String interval) {
return getSharedPreferences().getLong(interval, 0);
}
}
Declare the Application class in AndroidManifest.xml file with line android:name=".Application" as shown in below snippet:
<application
android:name=".Application"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
Now, How to store key-value:
Application.setPreferences("Key","String_Value");
How to fetch key-value:
String value_string=Application.getPrefranceData("Key");
You can now set-SharedPrefernce key-value and get-SharedPrefernce value from anywhere in the app using public Application class and the static get and set methods
Firstly create a SharedPreference.java Class.
public class SharedPreference {
Context context;
SharedPreferences sharedPreferences;
String user_name;
String password;
public SharedPreference(Context co) {
context = co;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getPassword() {
password = getStringInput("password");
return password;
}
public void setPassword(String password) {
this.password = password;
stringInput("password", password);
}
public String getUser_name() {
user_name = getStringInput("Username");
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
stringInput("Username", user_name);
}
public void stringInput(String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public String getStringInput(String key) {
return sharedPreferences.getString(key, "0");
}
}
Now go into activity or Fragment
example: I'm gone use it in MainActivity.java
public class MainActivity extends AppCompatActivity {
Prefrences prefrences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Dashboard");
prefrences = new Prefrences(MainActivity.this);
prefrences.setUser_name("Rishabh Jain");
prefrences.setUser_name("8369554235");
Log.e("Details",prefrences.getUser_name()+" "+prefrences.getPassword())
}
}
The output will be Rishabh Jain 8369554235.
Similarly, you can use this in any Activity or any Fragment
I guess you are trying to get values with different key. Get values with same key you put them with.
String user_name = preferences.getString(preferences.KEY_USERNAME,null);
String password = preferences.getString(preferences.KEY_PASSWORD, null);
----BUT----
And don't use singleton pattern for SharedPreferences it is very bad to use Context in singleton. It will crash your app. You can figure it out why.
Instead use static methods.
public class PreferenceUtil {
public static final String PASSWORD = "PASSWORD";
public static void setInt(Context context, int in, String key) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
editor.putInt(key, in);
editor.apply();
}
public static int getInt(Context context, String key) {
SharedPreferences settings;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(key)) {
return settings.getInt(key, 0);
} else
return 0;
}
}
And access it like this
int password = PreferenceUtil.getInt(getActivity(), PreferenceUtil.PASSWORD);
I'm trying to take string from user and use it later when the app is closed..now it works just when the app is in background but i lose the string when i close the app..is there a way to do it like this or i have to use SharedPreference and if i have to use it please explain how because i tried and failed..thanks alot.
this is my code in my MainActivity to the string from the EditText
public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPreferences;
private static String reminder;
private EditText et;
private Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize variables
sharedPreferences = getSharedPreferences("MyPREFERENCES",Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
et = (EditText) findViewById(R.id.Name);
reminder = et.getText().toString();
if(reminder == null){
reminder = "TWEAK!";
}
editor.putString("TAG",reminder);
editor.commit();
// do stuff
}
// get the user's string
public String getRem() {
reminder = sharedPreferences.getString("TAG", "");
return reminder;
}
the app crashes and gives
"Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference"
at this line
reminder = sharedPreferences.getString("TAG", "");
this is the class where i call the method
public class Notifications extends BroadcastReceiver {
private String rem;
// set notification
#Override
public void onReceive(Context context, Intent intent) {
// object to access MainActivity methods
MainActivity main = new MainActivity();
rem = main.getRem();
}
Wherever you called the method of getRem(), you can't do that outside the Activity as the SharedPreferences are null.
Like, I assume you made a new MainActivity(), then called getRem() on that, perhaps?
You need to obtain the SharedPreferences again from an available Context, and then you can use getString("TAG", "")
EDIT Borrowed from Shared preferences inside broadcastreceiver
public class Notifications extends BroadcastReceiver {
private String rem;
// set notification
#Override
public void onReceive(Context context, Intent intent) {
setRem(context);
}
private void setRem(Context context) {
SharedPreferences prefs = context.getSharedPreferences("MyPREFERENCES",Context.MODE_PRIVATE);
rem = prefs.getString("TAG", "");
}
}
You can use sharedpreferences
SharedPreferences sharedpreferences = getSharedPreferences("MyPREFERENCES",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("TAG",reminder);
editor.commit();
to retrive it:
sharedpreferences.getString("TAG","");
[update]
public class Notifications extends BroadcastReceiver {
private String rem;
// set notification
#Override
public void onReceive(Context context, Intent intent) {
// object to access MainActivity methods
SharedPreferences sharedPreferences = context.getSharedPreferences("MyPREFERENCES",Context.MODE_PRIVATE);
rem = sharedPreferences.getString("TAG", "");
}
more about SharedPreferences
I have a problem where my shared preferences are not working in a class file.I am confused and not able to solve it.Below is my file globalfile which saves data as follows.
public class globalfile extends Activity {
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Pwd = "pwdKey";
public static final String Email = "emailKey";
private static String global_username = "null/", global_pwd = "null/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
}
public String getusername() {
global_username = sharedpreferences.getString(Email, "");
return global_username;
}
public String getuserpwd() {
global_pwd = sharedpreferences.getString(Pwd, "");
return global_pwd;
}
public void setusername(String someVariable) {
global_username = someVariable;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Email,global_username);
editor.commit();
}
public void setuserpwd(String someVariable) {
global_pwd = someVariable;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Pwd,global_pwd);
editor.commit();
}
}
I first called setuserpwd() & setusername() then getuserpwd() & getusername() from another activity using object of class globalfile.But always returns null.although if I use this code without shared pref.it is working fine
create an instance of Activity with Activity class object
Technically, you can create an instance of an Activity class. but, activity instance would be useless because its underlying Context would not have been set up.
The rule is that you should never ever create instances of Android components (Activity, Service, BroadcastReceiver, Provider) yourself (using the new keyword or other means). These classes should only ever be created by the Android framework, because Android sets up the underlying Context for these objects and also manages the lifecycle.
I think your newly created activity object can't get actual context. so try to avoid your current flow. I suggest you to create a separate class that may use as factory class and I think your problem will solved.
Or another solution would be like this :
Context context = /*get application context*/
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
/*get value from this sharedPref*/
So you don't need to create activity class object and here you should avoid your previous getter method to get value.
change you globalfile to be a utility class and not an activity so it can be used really easily by other parts of your app (that aren't an activity but have access to an android context).
public class Global {
private final SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Pwd = "pwdKey";
public static final String Email = "emailKey";
private static String global_username = "null/",
global_pwd = "null/";
public Global(Context context) {
this.sharedpreferences = context.getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
}
public String getusername() {
global_username = sharedpreferences.getString(Email, "null/");
return global_username;
}
public String getuserpwd() {
global_pwd = sharedpreferences.getString(Pwd, "null/");
return global_pwd;
}
public void setusername(String someVariable) {
global_username = someVariable;
sharedpreferences.edit().putString(Email,global_username).commit();
}
public void setuserpwd(String someVariable) {
global_pwd = someVariable;
sharedpreferences.edit().putString(Pwd,global_pwd).commit();
}
}
And here's how to use your new util class
Global global = new Global(context);
global.setusername("foo");
Log.d("TAG", "username from prefs = " + global.getusername());
global.setuserpwd("bar");
Log.d("TAG", "password from prefs = " + global.getusername());
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 !
Hi stackoverflow again,
I want to store the session, but I have a problem, I jump an error
I have class "Session" and another class called "MainActivity"
In my Session I have :
public void saveSession(Context ctx,String username, String password){
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
Editor editor = sharedpreferences.edit();
String u = username;
String p = password;
editor.putString(name, u);
editor.putString(pass, p);
editor.commit();
}
And in my Main have :
session.saveSession(getApplicationContext(), username.getText().toString(),password.getText().toString());
I get this error :
03-12 01:47:01.648: E/AndroidRuntime(3395): FATAL EXCEPTION: main
03-12 01:47:01.648: E/AndroidRuntime(3395): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xx/com.example.xx.UserList}: java.lang.NullPointerException
03-12 01:47:01.648: E/AndroidRuntime(3395): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
Update: onCreate() method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
//loadSesion(); session.loadSession(getApplicationContext());
usernameSession = session.getUsernameSession();
passwordSession = session.getPasswordSession();
inicializeBdSqlite();
inicialize();
user_list.setOnItemClickListener(this);
}
First, about the SharedPreferences and the way you are using it. I have some notes:
1) Make sure that the strings name and pass are final string and already initialized in the class that this method is inside because if any of your sharedPreference keys are null the whole file may be broke as following:
final string name = "name";
final string pass = "password";
2)No need to put the new values into new strings, pass it directly
public void saveSession(Context ctx,String username, String password){
SharedPreference sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
Editor editor = sharedpreferences.edit();
editor.putString(name, username);
editor.putString(pass, password);
editor.commit();
}
3)Make your getter methods as following:
public String getUserName(Context ctx){
SharedPreference sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
return sharedpreferences.getString(name, "");//"" is the default value
}
4)About the user_list line user_list.setOnItemClickListener(this); .Make sure that your Main activity implements the class OnClickListener as following:
public class MainActivity extends Activity implements OnClickListener {
and in your MainActivity override it as following:
#Override
public void onClick(View v) {
//You action
}
I hope it helps