SharedPreference doesn't contain anything inside Broadcast Receiver - java

So I'm new to android and I have developed a simple alarm clock app. Problem is that my alarms resets when I reboot my phone, so I created a receiver which starts at boot. This receiver is supposed to get my list of quickAlarms from my shared preference, loop through it and then send them to my AlarmService. The problem is that I am unable to get hold of the sharedPreference.
I have tried these methods:
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
This is the broadcastReceiver called upon boot:
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BootReceiver", "BootReceiver called");
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
//sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
if(sharedPref.contains("alarm")){
Log.d("BootReceiver", "SharedPreference do contain alarms, trying to set them...");
alarmService= new AlarmService(context);
activate(context);
}else{
Log.d("BootReceiver", "SharedPreference does not contain any alarms.");
//I always get this message, so sharedPref never contains anything here!
}
}
/**
* Loops through the stored list of QuickAlarms, checks if the are set to on and then reshedules them.
* #param context
*/
public void activate(Context context) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {}.getType();
List<QuickAlarm> alarmList = gson.fromJson(sharedPref.getString("alarm", ""), type);
Iterator<QuickAlarm> alarmIterator = alarmList.iterator();
while(alarmIterator.hasNext()){
if(alarmIterator.next().isActive()){
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", alarmIterator.next().getTime()).setAction("CREATE").putExtra("repeat", alarmIterator.next().getRepeat()).putExtra("id" , alarmIterator.next().getID()).putExtra("desc", alarmIterator.next().getDesc()));
}
}
Log.d("BootReceiver", "All alarms are set again!");
}}
Here is the code in MainActivity were I declare the sharedpreference and use it in the Controller class:
private SharedPreferences sharedPref;
//...
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
controller = new Controller(sharedPref, this.getApplicationContext());
Then it's really the Controller which use it:
public Controller(SharedPreferences sharedPref, Context context) {
this.context = context;
this.sharedPref = sharedPref;
editor = sharedPref.edit();
}
//...
public void addQuickAlarm(QuickAlarm qa, int id) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {
}.getType();
List<QuickAlarm> alarms;
if (gson.fromJson(sharedPref.getString("alarm", ""), type) == null) {
alarms = new ArrayList<>();
} else {
alarms = gson.fromJson(sharedPref.getString("alarm", ""), type);
}
if (id == -10) {
alarms.add(qa);
Log.d("Controller", "QuickAlarm added to pref");
} else {
alarms.remove(id);
alarms.add(id, qa);
Log.d("Controller", "QuickAlarm edited to pref");
}
String jsonAlarm = gson.toJson(alarms); //converting list to json and saving back
editor.putString("alarm", jsonAlarm);
editor.commit();
}
public void activateAlarm(boolean on, int id) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {
}.getType();
List<QuickAlarm> alarmList = gson.fromJson(sharedPref.getString("alarm", ""), type);
QuickAlarm qa = alarmList.get(id);
qa.setActive(on);
int[] repeat = qa.getRepeat();
addQuickAlarm(qa, id);
if (on) {
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qa.getTime()).setAction("CREATE").putExtra("repeat", repeat).putExtra("id" , id).putExtra("desc", qa.getDesc()));
} else {
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qa.getTime()).setAction("CANCEL").putExtra("id" , id));
}
}

you need to add the "alarm" key and its value to your sharedpreference when you are setting the alarm alert something like this
sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
or
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor=sharedPref.edit();
editor.putString("alarm", "value u want to keep");
editor.commit();

Unable to start receiver com.example.user.alarmclock.Local.StartMyServiceAtBootReceiver: java.util.NoSuchElementException because after alarmIterator.next().isActive() this you are calling another next() like this alarmIterator.next().getTime() which mean you are asking for List<QuickAlarm > next item object(QuickAlarm ) which is not there so only you are getting the error. change your code to this because even you mean if in this object(QuickAlarm ) isActive() is true then pull other info from this object(QuickAlarm ) like getTime(),getRepeat() etc.
while(alarmIterator.hasNext()){
QuickAlarm qm=alarmIterator.next()
if(qm.isActive()){
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qm.getTime()).setAction("CREATE").putExtra("repeat", qm.getRepeat()).putExtra("id" , qm.getID()).putExtra("desc", qm.getDesc()));
}
}

Related

Send data from BroadcastReceiver to Activity in background(without starting)

I have this receiver class, it' registered in my MainActivity, it's supposed to count unlocks.
My goal
I want to make it work even when the app itself is not running(the receiver is never unregistered). It should get the amount of unlocks to the main activity without starting/restarting the activity.
My problem
I have no idea how to do that. As you can see I have tried to do it with SharedPreferences, but it didn't work, the receiver works fine and gets broadcasts, I just don't want it to start everytime.
public class UnlockReceiver extends BroadcastReceiver {
private int count = 0;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static final String TAG = "UnlockReceiver";
#Override
public void onReceive(Context context, Intent intent) {
preferences = context.getSharedPreferences("label", 0);
count = preferences.getInt("tag", 0);
KeyguardManager keyguardManager = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
if (!keyguardManager.inKeyguardRestrictedInputMode()) {
count++;
editor = preferences.edit();
editor.putInt("tag", count).commit();
Log.d(TAG, "unlock registered");
Intent i = new Intent(context, MainActivity.class);
i.putExtra("tag", count);
context.sendBroadcast(i);
}
} else {
if (!keyguardManager.isDeviceLocked()) {
count++;
editor = preferences.edit();
editor.putInt("tag", count).commit();
Log.d(TAG, "unlock registered");
Intent i = new Intent(context, MainActivity.class);
i.putExtra("tag", count);
context.sendBroadcast(i);
}
}
}
}

SharedPreferences in non activity class NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to use SharedPreferences in a non activity class from onResume() in an activity but I'm getting a NullPointerException on the context.
For some reason I cannot get the context in onResume(). Not sure if I'm missing something, but any help would be appreciated.
onResume() Method in my activity
#Override
protected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed").
// Check User's Access Token exists and hasn't expired.
AccountFunctions accountFunctions = new AccountFunctions();
if (!accountFunctions.validateUserToken(this)) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
validateUserToken(Context context) method in AccountFunctions Class
public Boolean validateUserToken(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
String accessToken = sharedPref.getString(getString(R.string.user_access_token), null);
DateTime expiryDate = new DateTime(sharedPref.getLong(getString(R.string.user_expires), 0));
if (accessToken == null || expiryDate.isBeforeNow()) {
return false;
} else {
return true;
}
}
The Error
java.lang.RuntimeException: Unable to resume activity
{uk.co.itsstonbury.www.intouch/uk.co.itsstonbury.www.intouch.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.Context
android.content.Context.getApplicationContext()' on a null object
reference
replace getString(R.str with context.getString because AccountFunctions class has not been created by the OS so it doesn't have it's own context ready.
Basically activity gets it's context form application when oncreate function get called by OS callbacks since it's not gonna happen in this case so AccountFunctions object will not have it's own context
This code simply assume that AccountFunctions will be created normally through intent but in this case it is like a simple class object which has no connection with activity life-cycle calls.
so your code will look like
public Boolean validateUserToken(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
String accessToken = sharedPref.getString(context.getString(R.string.user_access_token), null);
DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));
if (accessToken == null || expiryDate.isBeforeNow()) {
return false;
} else {
return true;
}
}
or you can use string values directly
SharedPreferences sharedPref = context.getSharedPreferences("yourkey", Context.MODE_PRIVATE); // This is where the error is thrown
or
The better option is create a separate Util class for helper function rather like
class Util{
public static boolean validateUserToken(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
String accessToken = sharedPref.getString(context.getString(context.R.string.user_access_token), null);
DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));
if (accessToken == null || expiryDate.isBeforeNow()) {
return false;
} else {
return true;
}
}
}
from your activity call it like
Util.validateUserToken(this);
Replace SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.user_file_key), Context.MODE_PRIVATE);
with
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE);

How to use shared preferences to save data that get from database? [duplicate]

This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 6 years ago.
I have this button code and it was connect to database
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
String email = jsonResponse.getString("email");
String alamat = jsonResponse.getString("alamat");
int notelp = jsonResponse.getInt("notelp");
String username = jsonResponse.getString("username");
String password = jsonResponse.getString("password");
Intent intent = new Intent(MainActivity.this, adminarea.class);
intent.putExtra("name", name);
intent.putExtra("email", email);
intent.putExtra("alamat", alamat);
intent.putExtra("notelp", notelp);
intent.putExtra("username", username);
intent.putExtra("password", password);
MainActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Login Gagal")
.setNegativeButton("Ulangi", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
i have a table called admin thats contain field name, email and etc.. how can i take the data from databse then save my data like name, email, alamat and the other to shared prefences. then can you help me to call it to another activity?
First of all you have to create SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_PREF_NAME", MODE_PRIVATE);
Editor edt = pref.edit();
To add value in preference:
edt.putString("name", name);
edt.putString("email", email);
edt.putString("alamat", alamat);
edt.putString("notelp", notelp);
edt.putString("username",username);
// Save your changes
edt.commit();
Now for getting data from preference:
String name=pref.getString("name", null);
String email=pref.getString("email", null);
String alamat=pref.getString("alamat", null);
String notelp=pref.getString("notelp", null);
String username=pref.getString("username", null);
If you want to clear the preference data:
edt.clear();
edt.commit();
Save like below.
SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);
Intent intent = new Intent(MainActivity.this, adminarea.class);
intent.putExtra("name", name);
getPref.edit().putString("name",name).apply();
intent.putExtra("email", email);
getPref.edit().putString("email",name).apply();
intent.putExtra("alamat", alamat);
getPref.edit().putString("alamat",name).apply();
intent.putExtra("notelp", notelp);
intent.putExtra("username", username);
intent.putExtra("password", password);
MainActivity.this.startActivity(intent);
Retrieve like this.
SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);
String name = getPref.getString("name","");
String email = getPref.getString("email","");
String alamat = getPref.getString("alamat","");
Create a class SharePrefUtil
private Context context;
private SharedPreferences prefs;
public SharePrefUtil(Context mContext) {
this.context = mContext;
prefs = this.context.getSharedPreferences("your package name", Context.MODE_PRIVATE);
}
public void setValueInSharePref(String keyName, String value) {
prefs.edit().putString(keyName, value).apply();
}
public String getValueFromSharePref(String keyName) {
return prefs.getString(keyName, "");
}
}
When ever you want to store the value
Just Make a object of class in you activity to get or set a value
for example
SharePreUtil shef = new SharePreUtil(this);
When ever you what to set a value in the activity
shef.setValueInSharePref("key", "yourvalue");
when you want to get value
shef.getValueFromSharePref("key");
All the best...
onCreate() method
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
to get all data server after
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(name, name);
editor.putString(email, email);
.....
editor.commit();
quoting the training guide at https://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
and to read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
In your other activity....first receive data from intent...like this
String name = getIntent().getExtras().getInt("name");
now,save this data into shared prefrences....to do that...you need sharedPreferences.Editor to write data.....like this...
SharedPreferences sp = Your_Activity.this.getSharedPreferences("SharedPreferences_Name", Context.MODE_PRIVATE);
SharedPreferences.Editor spwriter = sp.edit();
spwriter.putString("name",name);
spwriter.commit();
if (success) {
// once you retrieve all the required data
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Writing data to SharedPreferences
Editor editor = prefs.edit();
editor.putString("name", name);
editor.putString("email", email);
editor.putInt("notelp", notelp);
editor.commit();
// start your AdminArea activity here
}
Retrieve data inn AdminArea class:
// Reading from SharedPreferences
String value = prefs.getString("name", "DEFAULT_STRIGN"); // if the given key not found, it'll take the default string as value
int intValue = prefs.getInt("notelp", -1); // instead of -1, you can give any default value
hope this helps :)
You can save data in SharedPreferences in your activity class as below:
SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name);
editor.putString("email", alamat);
editor.putString("alamat", alamat);
editor.commit();
And in your activity where you want to fetch them, do as below:
SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name", "abc");
String email=sharedPreferences.getString("email", "abc#gmail.com");
To put int,
editor.putInt("number",0);
And to retrive it,
sharedPreferences.getInt("number",0);

SharedPreferences not being cleared android

I have an app where a user logs in and his details are saved so that the next time he starts the app he doesn't need to log in again.I have used SharedPreferences for this purpose. Now when I implement a logout function, I clear the preferences and I get a Map with 0 elements. Also I delete the Preference file. But when another user logs in he can still see the previous users details instead of his. How can I solve this?
Here is my code:-
SessionManagement.java
public class SessionManagement extends Application
{
static SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// ContextS
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyUserDetails";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_EMAILID = "email";
// Email address (make variable public to access from outside)
public static final String KEY_USERSNAME = "usersname";
public static final String KEY_DEVICEREGISTERED = "deviceregistered";
// Constructor
public SessionManagement(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String emailId, String usersname)
{
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
editor.putBoolean(KEY_DEVICEREGISTERED, true);
editor.putString(KEY_EMAILID, emailId);
editor.putString(KEY_USERSNAME, usersname);
editor.commit();
// commit changes
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails()
{
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
user.put(KEY_USERSNAME, pref.getString(KEY_USERSNAME, null));
// return user
return user;
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin()
{
// Check login status
if(!this.isLoggedIn())
{
// user is not logged in redirect him to Login Activity
Intent i =new Intent(this, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
// This function clears all session data and redirect the user to LoginActivity
/**
* Clear session details
* */
public void logoutUser()
{
// Clearing all data from Shared Preferences
editor.remove(KEY_EMAILID);
editor.remove(KEY_USERSNAME);
editor.remove(IS_LOGIN);
editor.clear();
editor.commit();
}
public boolean isLoggedIn()
{
return pref.getBoolean(IS_LOGIN, false);
}
}
Login.java
sessionManager = new SessionManagement(getApplicationContext());
if(sessionManager.isLoggedIn())
{
//Go directly to main activity
HashMap<String, String> userDetails = sessionManager.getUserDetails();
startMyActivity();
finish();
}
else
{
sessionManager.createLoginSession(email, username);
}
public void startMyActivity()
{
// TODO Auto-generated method stub
Intent in = new Intent(getApplicationContext(), Details1.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
}
Logout.java
SessionManagement session = new SessionManagement(getApplicationContext());
session.logoutUser();
ClearData cl = new ClearData();
cl.clearApplicationData(getApplicationContext());
Intent i = new Intent(Home.this, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(i);
ClearData.java
public class ClearData
{
public static void clearApplicationData(Context context)
{
File cache = context.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
File f = new File(appDir, s);
if(deleteDir(f))
Log.i("TAG", String.format("**************** DELETED -> (%s) *******************",
f.getAbsolutePath()));
}
}
}
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Instead of removing value from sharedpreference you can just edit value of sharedpreference with null value.
public void logoutUser()
{
editor.putBoolean(IS_LOGIN, false);
editor.putBoolean(KEY_DEVICEREGISTERED, false);
editor.putString(KEY_EMAILID, null);
editor.putString(KEY_USERSNAME, null);
editor.commit();
}
i think this will work..
You can change the values of Shared preferences.
public void logoutUser()
{
editor.putBoolean(IS_LOGIN, false);
editor.putBoolean(KEY_DEVICEREGISTERED, false);
editor.putString(KEY_EMAILID, "");
editor.putString(KEY_USERSNAME, "");
editor.clear();
editor.commit();
}
or You try this code. Clear your Shared preferences values.
pref.edit().clear().commit();
if your are using Marshmallow then
Add file in xml folder
mybackupscheme.xml
<full-backup-content>
<exclude domain="sharedpref" path="yourshared pref name.xml"/>
</full-backup-content>
then add in AndroidManifest.xml
<application
...
android:fullBackupOnly="false"
android:fullBackupContent="#xml/mybackupscheme"
/>
Hope this using this your issue will be resolved.
Try to get editor every time before calling commit().
If this not works, check contexts, that are returning preferences, they must be in one application and process.
I think problem is in your way of working with editor.
I think there is problem in your view of your editor and preference globalization you have to create preference and editor locally....
Because you are getting preferences
public SessionManagement(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
And now you are not getting any updated Preferences....
Each and every time when you have to work with your preferences...
Initialize preference and editor every time.
Either logging In or log out.

Add several appWidgets with different configuration?

I've created a widget which displays a simple textview, which is editable as an Edittext in a configuration activity. I save the inputted text with shared preferences, so the user can tap the widget to edit the text, and the already inputted text appears in the edittextfield.
My problem is this. I would like the user to be able to add multiple widgets, but when a seccond widget is added, the same text as in the other widget is loaded from shared preferences. And, when on widget is edited so is the other one. Hope i'm being clear. I kinda have an idea it has something to do with appWidgetIds but i cannot figure it out.
Here's my code, a bit simplified.
public class WidgetConfig extends Activity implements OnClickListener, OnItemSelectedListener {
AppWidgetManager awm;
int awID;
Context c;
EditText info;
Button b;
String note;
int styleStart = -1, cursorLoc = 0;
SharedPreferences sp;
Spinner spinner;
String[] paths = { "10", "20", "30" };
File path = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
c = WidgetConfig.this;
info = (EditText)findViewById(R.id.etwidgetconfig);
...
b = (Button)findViewById(R.id.bwidgetconfig);
loadPrefs();
b.setOnClickListener(this);
//Getting Info about the widget that launched this activity
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null){
awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID );
}
awm = AppWidgetManager.getInstance(c);
}
...
private void loadPrefs(){
sp = PreferenceManager.getDefaultSharedPreferences(this);
note = sp.getString("NOTE", "DEFAULT");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value); // value to store
editor.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("NOTE", info.getText().toString());
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.tvConfigInput, info.getText());
ComponentName thisWidget = new ComponentName(this, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
Intent in = new Intent(c, WidgetConfig.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.B_EditAgain, pi);
awm.updateAppWidget(awID, views);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK, result);
finish();
}
}
UPDATE:
So i tried this, but nothings different, still doesn't work.
private void loadPrefs(){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
note = sp.getString("Note", "");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.clear();
editor.putString("Note", info.getText().toString());
editor.putString(key, value); // value to store
editor.commit();
}
You probably don't want to use getDefaultSharedPreferences here. All widgets share the same default shared preferences, so they will be constantly overwriting each other.
I had the same situation in my own app, so I used a custom preference file for each widget. You can name the preference file with the widgetID, and then each widget will always get it's own unique set of preferences.
In the configuration PreferenceActivity:
this.getPreferenceManager().setSharedPreferencesName(
"widget" + String.valueOf(mAppWidgetId)
);
This will store all of the PreferenceActivity settings into a preference file named after the widget id.
Then in the widget itself, just retrieve the file corresponding to its id:
preferences = context.getSharedPreferences(
"widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
And retrieve preferences like normal.

Categories

Resources