shared preference is not created by the program - android

in the following program, what i am trying to do is:
i want to store a list of names in shared preference
when the app starts for the first time, it should create a shared preference by name "profile_names"
and subsequently , when the app starts for next times, it should check if the sharedprefernces is there or not
if it is present is should fetch the list from the preference and give it to the listview.
But it is not working ..... where have i gone wrong?
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.profilespage);
File f= new File("/data/data/neeraj.cardXchange.Basic/shared_prefs/profile_names");
if(f.exists()){
Toast.makeText(this, "prefernce already created", Toast.LENGTH_LONG).show();
profile_names= getSharedPreferences("profile_names", MODE_WORLD_READABLE);
try {
myarraylist = getArrayList(mycontext, key);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(this, "prefernce created now", Toast.LENGTH_LONG).show();
profile_names= getSharedPreferences("profile_names", MODE_WORLD_READABLE);
}
String [] name_list = myarraylist.toArray(new String[myarraylist.size()]);
ArrayAdapter adapter = new ArrayAdapter <String>(this, R.layout.textview, name_list);
setListAdapter(adapter);
}
here , i have used toast messages to keep a check on how things proceed
every time the toast message from my "else" gets executed and the shared preference is not created
i have checked it using DDMS.

You have to commit the created shared preference, first you have store values in shared preferences and then commit it so that I can retain values that can be used in other activities. here is small example to create and access shared preferences
To create:
SharedPreferences prefs = getSharedPreferences("UMSPreferences",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserId", login);
editor.putString("password", password);
editor.commit();
to access
String userid = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("UserId", login);
String paswrd = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("password", password);

Related

SharedPreferences returning null

I've created a class to save some username and password using the Android SharedPreferences, its seems that the methods for set both username and password are ok.
But everytime i try to get these, from within another activity or by just trying to print out the value i receiver nothing (if trying to print the value) or null (if trying to get on i activity).
Here is my code:
public class AuthPreferences {
private static final String KEY_USER = "userid";
private static final String KEY_PASSWORD = "mypassword";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context.getSharedPreferences("authoris", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
Log.v("MailApp", "User is " + user);
editor.apply();
if(editor.commit() == true) {
System.out.println("The user was set!");
}else{
System.out.println("The user was not set!");
}
}
public void setPassword(String pass) {
Editor editor = preferences.edit();
editor.putString(KEY_PASSWORD, pass);
Log.v("MailApp", "Password is " + pass);
editor.apply();
if(editor.commit() == true) {
System.out.println("The password was set!");
String mainUser = preferences.getString(KEY_PASSWORD, "456");
System.out.println(mainUser);
}else{
System.out.println("The password was not set!");
}
}
public String getUser() {
return preferences.getString(KEY_USER, "456");
}
public String getPassword() {
return preferences.getString(KEY_PASSWORD, "456");
}
Here is how i'm trying to get it:
preferences = new AuthPreferences(getActivity());
try {
String mainUser = preferences.getUser();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("App", "Could not get the user");
}
It is all because you use Activity as a context (you use result of getActivity() method as context). Since you got different activities you got different contexts so in result you are accessing different shared preferences files (XMLs). In other words you are writing to file A in activity A, and then read in activity B using file B as your source. This obviously is not going to work. To have this all work as you expect you shall always use the same context for data that you want to be accessed across many activities, in this case I recommend to use Application context. Technically, instead of calling getActivity() to get context in your fragment, you call getActivity().getApplicationContext() to get your application context, so you will be accessing the same shared preferences storage file, not matter what activity or fragment is doing that write or read.
Aside from this there's no need to call apply() and commit() as these two is kinda equivalent and do the same. Please check docs for more information.
Try replacing:
Editor editor = preferences.edit();
with
SharedPreferences.Editor editor = preferences.edit();
Then replace editor.apply(); with editor.commit();.
Instead of doing:
editor.apply();
do this:
editor.commit();
Also you need to commit your edits by using the methods somewhere:
AuthPreferences preferences = new AuthPreferences(getActivity());
preferences.setUser("USER_NAME");
preferences.setPassword("PASSWORD_VALUE");

How to do one time registration in android?

In my android application, I want to show the registration page only at the time of registration after that it will directly go to the main activity, doesn't go for registration page again if I open.
I did like this,It works but.
if I open my app and close it suddenly before registration process, the registration page didn't appear for the next time, without registration.
how can I avoid that.
How to write a condition to disappear the activity after the registration process.
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
Intent intent = new Intent(this, Track.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
Guys please help!
SharedPreferences _RegPref;
boolean _UserType = "";
You have to check shref pref before setcontentview method Like:
_RegPref = getApplicationContext().getSharedPreferences("LoginPref", 0);
_UserType = _RegPref.getString("REGISTERD", _UserType);
if (_UserType==true) {
try {
startActivity(new Intent(_ctx, YourActivity.class));
finish();
overridePendingTransition(R.anim.enter_new_screen, R.anim.exit_old_screen);
} catch (Exception e) {
e.printStackTrace();
}
}else {
set contentview("your register activity view");
}
after the registration is succesful, save the values in shred pref like:
Editor prefsEditor = _RegPref.edit();
_UserType = false;
prefsEditor.putString("REGISTERD", _UserType);
prefsEditor.commit();
you are in currect way, save sharedpreferences for this.
When user successfull register in your app, at that time save sharepreferences.
In onCreate method, if no sharepreferences found then forward to registration page.
Hi you can save sharedpreferences using bellow code.
This is the standard method for write shared preferences.
/**
* write SharedPreferences
* #param context
* #param name, name of preferences
* #param value, value of preferences
*/
public static void writePreferences(Context context,String name,String value)
{
SharedPreferences setting= context.getSharedPreferences("Give_your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=setting.edit();
editor.putString(name, value);
editor.commit();
}
Save your preferences.
Follow this link click here

How to display saved textview onto image button

Functionality Description:
Image Button(calls on a secondary application) that allow users to enter and input text, handwritten as well as keyboard input. User will then have the option to save the text. When, user exit the secondary application, the image button is supposed to displayed the saved text.
Genuine Issue:
Have intended to use shared preferences method but the saved text is still not displayed. Can anyone please help. Following is the code used.
Code:
//EDITED VERSION TO CALL OUT THE SECONDARY APPLICATION FOR USER TO INPUT TEXTandr
private void addListenerOnButtonMyScript() {
// TODO Auto-generated method stub
imageButton = (ImageButton) findViewById(R.id.imageButton_myscript);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("SingleViewActivity:onCreate:addListenerOnButtonMyScript" + ":onKey" , "Initiate myScript:");
final Intent intent = new Intent();
intent.setClassName("com.visionobjects.textwidget.sample", "com.visionobjects.textwidget.sample.SampleActivity");
startActivity(intent);
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
Log.i("Calling on Shared Preferences" , "Shared Preferences to pref_text:" + getString(R.string.pref_text) );
SharedPreferences.Editor editor = pref.edit();
editor.putString(getString(R.string.pref_text),"");
editor.commit();
}
});
}
//EDITED VERSION TO CALL ON SHARED PREFERENCES FUNCTION TO DISPLAY EDITED TEXT FROM MY_SCRIPT-20/10/2014
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();
editor.commit();
}
Strings.xml
<resources>
<string name="app_name">SalesBase</string>
<string name ="pref_text">StandardPreferences</string>
<string name="contacts_default">Contacts Details\n名字:HARRY\n公司:BARTENDER\n路名:123, Road Name\nZip:Zip\nState:State\nMobile:012-345-6789\nOffice:12-345-678\n</string>
</resources>
You are using wrong code to load the data. If loadSavedPreferences() is your final code to get data then you will not get any data. Try this
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
String data = prefs.getString(getString(R.string.pref_text), "");
}
However, I would suggest you to use different keys for preference name and the data you are trying to save.
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Use a different key where you are saving the data in this line and obviously value is the data you want to save. Use something like this.
editor.putString(key,value);
editor.commit();
And when you want to show the data then use the same key to get the data.
String data = prefs.getString(key, "");
Have a look at this as well.
Android Shared preferences example

how to store a text in one activity and retrieve it in another activity.?

I have created an app for alarm service..such that a person can set a alarm to a specific time and the alarm will pop up as a notification..Now i want to create that alarm service app to a task reminder app such a way that at the time of creating or setting the task , user input the message in the edit text and save it and then when the alarm pops up , and if the user taps the notification , a new activity comes up and the message that he typed earlier is printed in front of him..(i mean the message is show as a text view to him) So Please tell me how could i do that using shared preferences..
In simple way just tell how could a load the stored string from the activity where the string was created and save with the help of a button and to load that same string and pass it in a text view to some other activity..
You can use shared-preferences to store data in one activity. and these data will be available in any activity with in same application.
http://developer.android.com/reference/android/content/SharedPreferences.html
example is available at http://developer.android.com/guide/topics/data/data-storage.html
Good Luck.......
I would like to suggest you to do all your preference tasks in your Application Utils.clas
// Declaration
public static String KEY = "SESSION";
// Method declaration :
public static void saveUserName(String userid, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", userid);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
// You can save the values in preference by calling the below :
Utils.saveUserName("12345",YourActivity.this);
// Finally you can retrieve the stored value by calling this code snippet :
String myUserName = Utils.getUserName(YourActivity.this);
Hope it helps
You can use SharedPreferences.
Using setSetting, you can set the text at caller class. Similarly, you can get the text which was set in the caller class using getSetting in the called class.
Method to set the Preference-
public void setSetting(String key, String value) {
if(getActivity() != null)
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
// Commit the edits!
editor.commit();
}
}
Method to get the preference-
public String getSetting(String key, String def) {
try
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
return settings.getString(key, def);
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
Here,
public abstract SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.
More on Android developer reference.

Android SharedPreferences update does not work

I know, this issue has been dealt with in many threads, but I cannot figure out this one.
So I set a shared preference like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.apply();
I read the preferences like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = null;
spinnerValuesSet = prefs.getStringSet(spinnerName,null );
Everything works, except for my changes are visible while this activity runs i.e. - I display the values from the SharedPreferences, allow the user to delete or add and then update the ListView. This works, but after I restart the application, I get the initial values.
This for example is my method to delete one value from the list, update the values in SharedPreferences and update the ListView
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
for (String s : spinnerValuesSet)
{
if(s == currentSelectedItemString)
{
spinnerValuesSet.remove(s);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, spinnerValuesSet );
editor.apply();
break;
}
}
updateListValues();
}
});
And this is the method that updates the ListView:
private void updateListValues()
{
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
if(spinnerValuesSet.size() > 0)
{
names = new ArrayList<String>();
names.clear();
int k=0;
for (String s : spinnerValuesSet) {
names.add(k, s);
k++;
}
namesAA = new ArrayAdapter<String> ( this, android.R.layout.simple_list_item_activated_1, names );
myList.setAdapter(namesAA);
}
}
Any help is much appreciated.
The Objects returned by the various get methods of SharedPreferences should be treated as immutable. See SharedPreferences Class Overview for reference.
You must call remove(String) through the SharedPreferences.Editor returned by SharedPreferences.edit() rather than directly on the Set returned by SharedPreferences.getStringSet(String, Set<String>).
You will need to construct a new Set of Strings containing the updated content each time since you have to remove the Set entry from SharedPreferences when you want to update its content.
Problem happens because the Set returned by SharedPreference is immutable. https://code.google.com/p/android/issues/detail?id=27801
I solved this by created a new instance of Set and storing in all the values returned from SharedPreferences.
//Set<String> address_ids = ids from Shared Preferences...
//Create a new instance and store everything there.
Set<String> all_address_ids = new HashSet<String>();
all_address_ids.addAll(address_ids);
Now use the new instance to push the update back to SharedPreferences
I may be wrong but I think the way you are retrieving the Shared Preferences is the problem. Try using
SharedPreferences prefs = getSharedPreferences("appPreferenceKey", Context.Mode_Private);
Use editor.commit(); instead of editor.apply();
Example Code:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.commit();
I hope this helps.
Depending on the OS Build you may have to save values in a different way.
boolean apply = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
public static void saveValue(SharedPreferences.Editor editor)
{
if(apply) {
editor.apply();
} else {
editor.commit();
}
}

Categories

Resources