I am succesfully making, saving, and retrieving my shared preferences from my mainActivity, but I cant get it from my service...
For some reason, my shared preferences is null when I try to retrieve it from a background service...
I initialize my preferences in onCreate:
contactsPrefs = getSharedPreferences("contactsPrefs", MODE_PRIVATE); //Making a shared preferences
Save values in onCreate:
myEditor = contactsPrefs.edit();
Set<String> set = new HashSet<String>();
set.addAll(contactArrayList);
myEditor.clear(); //Clearing current values in shared pref
myEditor.putStringSet("contactSetKey", set); //Adding contacts
myEditor.commit();
All this is going fine, but when I try to access my preferences from my service, I get null:
preferences = PreferenceManager.getDefaultSharedPreferences(c); //See edit at bottom for more info
if(preferences.getStringSet("contactSetKey", null) != null) {
contactArrayList.addAll(preferences.getStringSet("contactSetKey", null));
for (String number : contactArrayList) {
number.substring(number.indexOf("-") + 1); //Remove all characters before the hyphen from my string
Log.v(TAG, number);
}
}else{
Log.v(TAG, "Dagnabit it its null");
}
And to my disappointment, I get the log Dagnabit it its null. why is it null? I can assure you that it works from my main activity, because I am able to display all of my data from my shared preferences when I access it from my shared preference. So I know that it shouldn't be null...But it is for some reason
Thanks,
Ruchir
EDIT:
I actually register a volume listener using content observer, and I am accesing the preferences from there. Here is in the service:
mSettingsContentObserver = new volumeCheck(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);
Here is the Content Observer:
public class volumeCheck extends ContentObserver {
public volumeCheck(Context c, Handler handler) {
super(handler); //Creates a new handler
context = c; //variable context, defined earlier, is set equal to c, context of service.
preferences = PreferenceManager.getDefaultSharedPreferences(c);
}
Try to get shared pref reference using application context as shown below:
contactsPrefs =
getApplicationContext().getSharedPreferences("contactsPrefs",
MODE_PRIVATE); //Making a shared preferences
Note:
If you still getting null, then get the shared preference from onStart() method of the service instead of doing it inside onCreate().
EDIT:
I tested and its working
public class MainActivity extends AppCompatActivity {
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Status","Success");
editor.apply();
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,
new VolumeCheck(this, new Handler()));
}
}
import android.content.Context;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
public class VolumeCheck extends ContentObserver {
private final SharedPreferences preferences;
private Context context;
public VolumeCheck(Context c, Handler handler) {
super(handler); //Creates a new handler
context = c; //variable context, defined earlier, is set equal to c, context of service.
preferences = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext());
String status = preferences.getString("Status", "");
if(!status.equalsIgnoreCase(""))
{
// got the value read from shared preference
Log.i("Reading value", status);
}
}
}
Related
I'm trying to save textview from getIntent String. When I close the application, then open again, textview is null. I have used many methods like onSaveInstance, SharedPreference but all failed.
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
jamShubuh = findViewById(R.id.jamShubuhTextView);
jamDzuhur = findViewById(R.id.jamDzuhurTextView);
jamAshar = findViewById(R.id.jamAsharTextView);
getShubuh = getIntent().getStringExtra("getShubuh");
getDzuhur = getIntent().getStringExtra("getDzuhur");
getAshar = getIntent().getStringExtra("getAshar");
jamShubuh.setText(getShubuh);
jamDzuhur.setText(getDzuhur);
jamAshar.setText(getAshar);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("shubuh", getShubuh);
editor.putString("dzuhur", getDzuhur);
editor.putString("ashar", getAshar);
retriveData();
private void retriveData() {
SharedPreferences getData = getPreferences(Context.MODE_PRIVATE);
getData.getString("shubuh", null);
getData.getString("dzuhur", null);
getData.getString("ashar", null);
}
To use the shared preferences, I suggest you to make certain class to handle it. Maybe like this.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class MyPrefManager {
SharedPreferences sp;
SharedPreferences.Editor editor;
public void setPref(Context context, String key, String value){
sp = PreferenceManager.getDefaultSharedPreferences(context);
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public String getPref(Context context, String key){
sp = PreferenceManager.getDefaultSharedPreferences(context);
value = null;
String X = sp.getString(key, value);
return X;
}
}
Then use setPref method to set the value and getPref method to get the value. Assume now you are in MainActivity and you want to save values of getShubuh, getDzuhur, and getAshar to Preference Manager, you can do something like this :
MyPrefManager MPM = new MyPrefManager();
MPM.setPref(MainActivity.this,"keyShubuh",getShubuh);
MPM.setPref(MainActivity.this,"keyDzuhur",getDzuhur);
MPM.setPref(MainActivity.this,"keyAshar",getAshar);
And to get the value of keyShubuh, keyDzuhur, and keyAshar wherever you want, you can do something like this.
MyPrefManager MPM = new MyPrefManager();
MPM.getPref(AnyActivity.this,"keyShubuh");
MPM.getPref(AnyActivity.this,"keyDzuhur");
MPM.getPref(AnyActivity.this,"keyAshar");
Hope it can help.
To save text state
//Saving The Text Entered by User
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
editText = findViewById(R.id.editText);// getting the reference of editext from xml
CharSequence text = editText.getText();// getting text u entered in edittext
outState.putCharSequence("savedText", text);// saved that text in bundle object i.e. outState
}
and restore saved text
//Restoring the State
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
editText = findViewById(R.id.editText);// getting the reference of textview from xml
CharSequence savedText =
savedInstanceState.getCharSequence("savedText");// getting the text of editext
editText.setText(savedText);// set the text that is retrieved from bundle object
}
instead of EditText you can use TextView.
I'm writing an app that uses WebView, and every time the app is launched, it goes to the same loadUrl. Here is me establishing the WebView. Followed by everything else that I want the WebView to do.
myWebView = findViewById(R.id.myWebView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(theUrlHere);
Now lets say that a certain condition was met by the user, may it be some action that was taken, or by just launching the app a second time, would it be possible to use SharedPreferences to change what url will load the next time the app is launched?
Edit: Can I get an example of how this can be achieved? Thanks in advance!
Shared Preferences implementation:
private SharedPreferences pref;
then load it
pref = this.getSharedPreferences("myAppPref",MODE_PRIVATE);
now to put the new url if he met conditions you said about save the newUrl
pref.edit().putString("url","my new url to be loaded").commit();
and when the user reopen now(or opens for the first time) you have to load it from prefs:
String WebUrl= pref.getString("url","default url here");
myWebView.loadUrl(WebUrl); //this is ur webview
now if the value is NULL(not found) it will return default url(this case is for the first time he opens)
NOTE THAT: you should clear the cache on exit.
NOTE THAT: this value will be lost if the user clears the application data.
Yes, you can
First, create this class to handle SharedPreferencess
public class SharedPreferensessClass {
static SharedPreferensessClass Instance;
static SharedPreferences sharedPreferences;
static SharedPreferences.Editor editor;
Context context;
public SharedPreferensessClass(Context context) {
this.context = context;
}
public static SharedPreferensessClass getInstance(Context context) {
if (Instance == null) {
Instance = new SharedPreferensessClass(context);
}
init(context);
return Instance;
}
public static void init(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences("app_name", Context.MODE_PRIVATE);
}
if (editor == null) {
editor = sharedPreferences.edit();
}
}
public static void setFirstTimeFalse() {
editor.putBoolean("firstTime", false);
editor.commit();
}
public static boolean getFirstTime() {
return sharedPreferences.getBoolean("firstTime", true);
}
public static String getLink() {
return sharedPreferences.getString("mainUrl", "");
}
public void setLink(String name) {
editor.putString("mainUrl", name);
editor.commit();
}
}
then use this code to save the link first time
if (SharedPreferensessClass.getInstance(getBaseContext()).getFirstTime()) {
System.out.println("FIRSTTIMENOW");
SharedPreferensessClass.getInstance(getBaseContext()).setLink("http://your_link");
SharedPreferensessClass.getInstance(getBaseContext()).setFirstTimeFalse();
}
The last step, use this code to get the link from SharePreferencess and put it in webView
myWebView.loadUrl(SharedPreferensessClass.getInstance(context).getLink());
note: the value will not be lost even if the user clears the data, because it will be the first time again :D
Happy coding!
I have problem with sharedpreferences, something goes wrong and I always get a default value.
My sharedpref class is:
public class IntolleranceData {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
}
I save value in Activity by:
intolleranceData = getApplicationContext().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something").apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG).show();
and this is great (toast shows correct string -"fish: something") but if I try to use sharedpreferences in fragment (in the same Activity and SharedPreferences, Activity and Fragment are in the same package) by:
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
It shows "fish: 00000" so this is default value...
Is there any way to solve my problem?
Try checking to make sure that your GetActivity() isn't null before you reference it to return the SharedPreferences.
Also, you are using 'apply()' to add your changes to the SharedPreferences, which is a process which runs in the background. If you try and read from the data too early (e.g. simultaneously) then you can often get the default value. Alternatively, use .commit() to save your changes to the SharedPreferences.
Finally, if the problem is unrelated to either of these common issues, saving 'getActivity().getApplicationContext()' to a variable when the fragment is initialized, it should help with the problem of the context not linking correctly!
Best of Luck!
There is need to change your file like this, In the Place of
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
You Must change Your code Like this, way,.... and also you just simply change your getActivity() with className.this
intolleranceData = MainActivity.this.getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
introlleranceEditor.commit();
introllerenceEditor.apply();
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
You don't need editor to read data.
When you send data use
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();
I got your Problem i will give you a Perfect answer for your problem simply check this code......
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and in Shared Preferece or Inside button Click you can write this code
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();
If you Solve your problem give a simple response
I understand that you trying to use this code display a message in the Fragment kk, try this code.....
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = getActivity().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and In Shared Prefereces
intolleranceData = getApplicationContext().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();
You should commit after you add the string...
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();
I am just trying to store the users input from an editText in a Shared Preference, but it is not working:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
}
return true;
});
When I first edit the text, I will first get a log of "mDefault" which is normal, since nothing is stored in the shared preference.
Then, I store something in the shared preference, and to make sure it stored, I log and I get a log of what I typed. Which means the shared preference data WAS stored.
Heres the problem: After I have stored something in the shared preference, I go to a different activity, and I come back, and all the data stored in the shared preference is GONE!
The very first log still says mDefault after navigating through activities.
What could the problem be?
EDIT:
Here is my instantiation:
onCreate:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
Maybe you don't save on setOnEditorActionListener. Save when you go to a different activity. Because when it goes to different activity the setOnEditorActionListener editText.getText().toString() it returns null.
STORING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("username", "Rishabh");
edit.putString("password", "rishabh123");
// Commit the changes
edit.commit();
RETRIEVING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password= pref.getString("password", "");
Log.d(TAG, username);
Log.d(TAG, password);
Adding this as an example in case you missed a key components. This is currently working for me:
public class Main2Activity extends ActionBarActivity {
private SharedPreferences keyword;
private SharedPreferences.Editor keywordEditor;
private String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
final EditText editText = (EditText) findViewById(R.id.et_text);
findViewById(R.id.btn_launch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
startActivity(intent);
}
});
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, "Initial: " + keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, "Saving in prefs: " + keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
return true;
}
});
}
}
From a fresh install:
I typed in "test" and hit the send button on keyboard therefore invoked the onEditorAction
Then clicked on launch new activity -> hit back button and typed in "test2" and hit send button.
The following is the log out put:
02-29 23:26:42.068 18105-18105/com.example.naveed.myapplication V/TAG: Initial: mDefault
02-29 23:26:42.136 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test
02-29 23:26:53.281 18105-18105/com.example.naveed.myapplication V/TAG: Initial: test
02-29 23:26:53.338 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test2
As you can see initially it was "mDefault" then "test" was saved. I launched a new activity and came back. Next time the initial was "test" since it was saved last time and "test2" was the new value saved.
Create SharedPreferences class
public class SharedPreferenceClass
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "INTELLIJ_AMIYO";
public static final String KEY_SET_VALUE= "KEY_SET_VALUE";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setUserDATA(String data)
{
editor.remove(KEY_SET_VALUE);
editor.putString(KEY_SET_VALUE, data);
editor.commit();
}
public String getUserDATA()
{
String getData= pref.getString(KEY_SET_VALUE, null);
return getData;
}
}
Now call this in your Activity section globally
SharedPreferenceClass sharedPrefClassObj;
& call onCreate(Bundle savedInstanceState) section
sharedPrefClassObj = new SharedPreferenceClass(getApplicationContext());
Now add this
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
sharedPrefClassObj.setUserDATA(editText.getText().toString()); // Set data
// Get data sharedPrefClassObj.getUserDATA();
}
}
return true;
});
Very important: you need a Preference name (for example: "MY_PREFS_NAME") to set and retrieve the values:
SharedPreferences.Editor keywordEditor = context.getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
Use the same constant Preference name and it will give you the same preferences in any point of your app.
I've currently got a preferences screen, and I've created a custom class that extends DialogPreference and is called from within my Preferences. My preferences data seems store/retrieve from SharedPreferences without an issue, but I'm trying to add 2 more sets of settings from the DialogPreference.
Basically I have two issues that I have not been able to find. Every site I've seen gives me the same standard info to save/restore data and I'm still having problems. Firstly I'm trying to save a username and password to my SharedPreferences (visible in the last block of code) and if possibly I'd like to be able to do it in theonClick().
My preferences XML that calls my DialogPreference:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory>
<com.rone.optusmon.AccDialog
android:key="AccSettings"
android:title="Account Settings"
android:negativeButtonText="Cancel"
android:positiveButtonText="Save" />
</PreferenceCategory>
</PreferenceScreen>
My Custom DialogPreference Class file:
package com.rone.optusmon;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener {
private TextView mUsername, mPassword;
private EditText mUserbox, mPassbox;
CharSequence mPassboxdata, mUserboxdata;
private CheckBox mShowchar;
private Context mContext;
private int mWhichButtonClicked;
public AccDialog(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
#Override
protected View onCreateDialogView() {
// Access default SharedPreferences
#SuppressWarnings("unused")
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
#SuppressWarnings("unused")
LinearLayout.LayoutParams params;
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(10, 10, 10, 10);
layout.setBackgroundColor(0xFF000000);
mUsername = new TextView(mContext);
mUsername.setText("Username:");
mUsername.setTextColor(0xFFFFFFFF);
mUsername.setPadding(0, 8, 0, 3);
mUserbox = new EditText(mContext);
mUserbox.setSingleLine(true);
mUserbox.setSelectAllOnFocus(true);
mPassword = new TextView(mContext);
mPassword.setText("Password:");
mPassword.setTextColor(0xFFFFFFFF);
mPassbox = new EditText(mContext);
mPassbox.setSingleLine(true);
mPassbox.setSelectAllOnFocus(true);
mShowchar = new CheckBox(mContext);
mShowchar.setOnCheckedChangeListener(mShowchar_listener);
mShowchar.setText("Show Characters");
mShowchar.setTextColor(0xFFFFFFFF);
mShowchar.setChecked(false);
if(!mShowchar.isChecked()) {
mPassbox.setTransformationMethod(new PasswordTransformationMethod());
}
layout.addView(mUsername);
layout.addView(mUserbox);
layout.addView(mPassword);
layout.addView(mPassbox);
layout.addView(mShowchar);
return layout;
}
public void onClick(DialogInterface dialog, int which) {
mWhichButtonClicked = which;
// if statement to set save/cancel button roles
if (mWhichButtonClicked == -1) {
Toast.makeText(mContext, "Save was clicked\nUsername: " + mUserbox.getText().toString() +"\nPassword is: " + mPassbox.getText().toString(), Toast.LENGTH_SHORT).show();
// Save user preferences
SharedPreferences settings = getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putString("usernamekey", mUserbox.getText().toString());
editor.putString("passwordkey", mPassbox.getText().toString());
editor.commit();
}
else {
Toast.makeText(mContext, "Cancel was clicked", Toast.LENGTH_SHORT).show();
}
}
}
My main activity test code:
public void onResume() {
super.onResume();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\nThe monitor will refresh every "+ pref.getString("refreshfreq", "30 minutes"));
builder.append("\nThe skin chosen is "+ pref.getString("skinkey", "null"));
builder.append("\nThe style chosen is "+ pref.getString("stylekey", "% used"));
builder.append("\nThe font chosen is "+ pref.getString("fontkey", "Calibri"));
builder.append("\nThe font color is "+ pref.getString("fontcolkey", "White"));
builder.append("\nYour username is "+ pref.getString("usernamekey", "not set yet"));
builder.append("\nYour password is "+ pref.getString("passwordkey", "not set yet"));
Toast.makeText(Optusmon.this, builder.toString(), Toast.LENGTH_LONG).show();
}
In my SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); line, Eclipse says "The method getDefaultSharedPreferences(AccDialog) is undefined for the type AccDialog". I've attempted to change the context to my preferences class, use a blank context and I've also tried naming my SharedPrefs and using getSharedPreferences() as well. I'm just not sure exactly what I'm doing here.
As I'm quite new to Java/Android/coding in general, could you please be as detailed as possible with any help, eg. which of my files I need to write the code in and whereabouts in that file should I write it (i.e. onCreate(), onClick(), etc)
In the onCreate() you returned before execute this line, so Eclipse says it's unreachable.
In your onClick() try:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
should be OK
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);