Android中的Sharedpreferences从另一个活动调用时返回null
问题描述:
我做了两个活动,一个用于小部件,另一个用于设置活动。Android中的Sharedpreferences从另一个活动调用时返回null
在设置活动中初始化了两个变量“strSavedMem1”&“strSavedMem1”,并通过sharedPreference方法创建。
但是,当我尝试在窗口小部件活动中使用变量时,变量返回一个“null”值。
小部件活动:
package com.eightbitcloud.example.widget;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.shashank.pingwidget.R;
public class ExampleAppWidgetProvider extends AppWidgetProvider {
private static final String LOG_TAG = "Ping_Widget";
private static Handler handler;
static String currentTime = null ;
public String strSavedMem1;
public String strSavedMem2;
public static final String PREFS_NAME="LocalePrefs";
/**
* Custom Intent name that is used by the AlarmManager to tell us to update the clock once per second.
*/
public static String PING_WIDGET_UPDATE = "com.eightbitcloud.example.widget.8BITCLOCK_WIDGET_UPDATE";
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (PING_WIDGET_UPDATE.equals(intent.getAction())) {
Log.d(LOG_TAG, "Clock update");
// Get the widget manager and ids for this widget provider, then call the shared
// clock update method.
ComponentName thisAppWidget = new ComponentName(context.getPackageName(), getClass().getName());
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
for (int appWidgetID: ids) {
updateAppWidget(context, appWidgetManager, appWidgetID);
}
}
}
private PendingIntent createClockTickIntent(Context context) {
Intent intent = new Intent(PING_WIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
Log.d(LOG_TAG, "Widget Provider disabled. Turning off timer");
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(createClockTickIntent(context));
}
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME,0);
strSavedMem1 = sharedPreferences.getString("MEM1", null);
if (strSavedMem1 == null) {
strSavedMem1="google.com";
Log.d(getClass().getSimpleName(),"MEM1 name is: "+ strSavedMem1);
}
strSavedMem2 = sharedPreferences.getString("MEM1", null);
if (strSavedMem2 == null) {
strSavedMem2 = "1";
Log.d(getClass().getSimpleName(),"MEM2 name is: "+ strSavedMem2);
}
Log.d(LOG_TAG, "Widget Provider enabled. Starting timer to update widget every second");
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 30);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 50000, createClockTickIntent(context));
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
Log.d(LOG_TAG, "Updating Example Widgets.");
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, WidgetExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current app
// widget
appWidgetManager.updateAppWidget(appWidgetId, views);
// Update The clock label using a shared method
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
public void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId) {
//String currentTime = df.format(new Date());
handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
String pingCmd = "ping -c 3 " + "google.com";
String pingResult = "";
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
currentTime = inputLine + "\n";
pingResult += inputLine+ "\n";
currentTime = pingResult ;
}
in.close();
}//try
catch (IOException e) {
System.out.println(e);
}
handler.post(new Runnable() {
@Override
public void run() {
//progress.setProgress(value);
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget1);
updateViews.setTextViewText(R.id.widget1label, currentTime+"\n"+ strSavedMem1+"\n"+strSavedMem2);
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
});
}
};
new Thread(runnable).start();
}
}
的设置活动是:
package com.eightbitcloud.example.widget;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.shashank.pingwidget.R;
public class WidgetExampleActivity extends Activity {
public static final String PREFS_NAME="LocalePrefs";
public Context ctx = null;
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
editText1 = (EditText)findViewById(R.id.edittext1);
editText2 = (EditText)findViewById(R.id.edittext2);
buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
LoadPreferences();
}
};
Button.OnClickListener buttonSaveMem2OnClickListener = new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM2", editText2.getText().toString());
LoadPreferences();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME,MODE_WORLD_READABLE);
/*SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();*/
//SharedPreferences sharedPreferences =PreferenceManager.getDefaultSharedPreferences(WidgetExampleActivity.this);
//SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public void LoadPreferences(){
// SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "google.com");
String strSavedMem2 = sharedPreferences.getString("MEM2", "1");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
strSavedMem1 = sharedPreferences.getString("MEM1", null);
if (strSavedMem1 == null) {
strSavedMem1="google.com";
Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ strSavedMem1);
}
strSavedMem2 = sharedPreferences.getString("MEM1", null);
if (strSavedMem2 == null) {
strSavedMem2 = "1";
Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ strSavedMem2);
}
}
}
答
你应该
- 检查,如果提交的工作,回到真实。
- 打开使用MODE_PRIVATE以同样的方式既SharedPreferences(为常数,而不是它的价值)
参考此链接... HTTP://asmncl.blogspot.in/2012/04/android-sharedpreference-保存-and.html – 2012-04-25 16:30:07