应用关闭后无法访问共享首选项
Unable to access sharedpreferences after app close
我有一个网络请求 activity,它向网络服务器发出请求并存储数据。
当应用程序从登录使用时一切正常。但是一旦应用程序关闭并重新打开,对服务器的任何请求都会遇到以下错误:
07-01 12:32:43.222: E/AndroidRuntime(29847): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.impact.main/com.impact.main.ActionsPopUpActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
这是 class 我用来发出网络请求的:
public class WebRequest{
private static final String TAG = "WebRequest";
AtomicInteger msgId = new AtomicInteger();
GoogleCloudMessaging gcm;
public static SharedPreferences prefs;
public static SQLiteHandler db;
public static SessionManager session;
protected static Context context;
private static RequestQueue mRequestQueue;
public WebRequest(Context context){
this.context = context.getApplicationContext();
}
public static void Request(final String url, final String vars, final Boolean show, final String title, final String msg, final String requestName, final Boolean isLogin){
session = new SessionManager(context);
final ProgressDialog theProgressDialog = new ProgressDialog(context);
db = new SQLiteHandler(context);
if(show == true){
theProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
theProgressDialog.setTitle(title);
theProgressDialog.setMessage(msg);
theProgressDialog.setIndeterminate(true);
theProgressDialog.setCancelable(true);
theProgressDialog.show();
}
StringRequest strreq = new StringRequest(Method.POST, url + vars,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "WEB Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
switch(requestName){
case "fetch_action_comments":
JSONArray comments = jObj.getJSONArray("comments");
// looping through All actions
for (int i = 0; i < comments.length(); i++) {
JSONObject comment = comments.getJSONObject(i);
if(comment.has("comments") && !comment.getString("comments").equals("empty")){
int commentCheck = db.getRowCount("*", dbTables.TABLE_ACTIONCOMMENTS, "WHERE actioncommentid='" + comment.getString("actioncommentid") + "'");
if(commentCheck == 0){
String[][] commentValues = {
{ dbTables.KEY_ACTIONCOMMENTID, comment.getString(dbTables.KEY_ACTIONCOMMENTID) },
{ dbTables.KEY_ACTIONID, comment.getString(dbTables.KEY_ACTIONID) },
{ dbTables.KEY_COMMENT, comment.getString(dbTables.KEY_COMMENT) },
{ dbTables.KEY_ADDEDBY, comment.getString(dbTables.KEY_ADDEDBY) },
{ dbTables.KEY_DATEADDED, comment.getString(dbTables.KEY_DATEADDED) },
{ dbTables.KEY_EDITEDBY, comment.getString(dbTables.KEY_EDITEDBY) },
{ dbTables.KEY_DATEEDITED, comment.getString(dbTables.KEY_DATEEDITED) },
{ dbTables.KEY_USERID, comment.getString(dbTables.KEY_USERID) }
};
db.insert(dbTables.TABLE_ACTIONCOMMENTS, commentValues);
}
}
}
break;
}
if(show == true){
theProgressDialog.dismiss();
}
}else{
String errorMsg = jObj.getString("error_msg");
if(errorMsg.length() > 0){
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
}
if(show == true){
theProgressDialog.dismiss();
}
}
}catch(JSONException e){
// JSON error
e.printStackTrace();
Toast.makeText(context, e+"", Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Web Error: " + error.getMessage());
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
});
// Adding request to request queue
addToRequestQueue(strreq, requestName);
}
public static RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
public static <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
请求在另一个 Activity 的 onCreate 部分调用。
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "Login";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in air plan mode it will be null
return (netInfo != null && netInfo.isConnected());
}
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
}
您看到的错误是因为您没有先调用 new WebRequest()
就调用了 WebRequest.Request()
。静态方法Request()
依赖于静态字段context
,它只在WebRequest()
的构造函数中设置。您的 static
方法需要是独立的,不需要构造对象来使用它们。
将编辑器对象写为
SharedPreferences.Editor editor = prefs.edit();
我有一个网络请求 activity,它向网络服务器发出请求并存储数据。
当应用程序从登录使用时一切正常。但是一旦应用程序关闭并重新打开,对服务器的任何请求都会遇到以下错误:
07-01 12:32:43.222: E/AndroidRuntime(29847): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.impact.main/com.impact.main.ActionsPopUpActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
这是 class 我用来发出网络请求的:
public class WebRequest{
private static final String TAG = "WebRequest";
AtomicInteger msgId = new AtomicInteger();
GoogleCloudMessaging gcm;
public static SharedPreferences prefs;
public static SQLiteHandler db;
public static SessionManager session;
protected static Context context;
private static RequestQueue mRequestQueue;
public WebRequest(Context context){
this.context = context.getApplicationContext();
}
public static void Request(final String url, final String vars, final Boolean show, final String title, final String msg, final String requestName, final Boolean isLogin){
session = new SessionManager(context);
final ProgressDialog theProgressDialog = new ProgressDialog(context);
db = new SQLiteHandler(context);
if(show == true){
theProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
theProgressDialog.setTitle(title);
theProgressDialog.setMessage(msg);
theProgressDialog.setIndeterminate(true);
theProgressDialog.setCancelable(true);
theProgressDialog.show();
}
StringRequest strreq = new StringRequest(Method.POST, url + vars,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "WEB Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
switch(requestName){
case "fetch_action_comments":
JSONArray comments = jObj.getJSONArray("comments");
// looping through All actions
for (int i = 0; i < comments.length(); i++) {
JSONObject comment = comments.getJSONObject(i);
if(comment.has("comments") && !comment.getString("comments").equals("empty")){
int commentCheck = db.getRowCount("*", dbTables.TABLE_ACTIONCOMMENTS, "WHERE actioncommentid='" + comment.getString("actioncommentid") + "'");
if(commentCheck == 0){
String[][] commentValues = {
{ dbTables.KEY_ACTIONCOMMENTID, comment.getString(dbTables.KEY_ACTIONCOMMENTID) },
{ dbTables.KEY_ACTIONID, comment.getString(dbTables.KEY_ACTIONID) },
{ dbTables.KEY_COMMENT, comment.getString(dbTables.KEY_COMMENT) },
{ dbTables.KEY_ADDEDBY, comment.getString(dbTables.KEY_ADDEDBY) },
{ dbTables.KEY_DATEADDED, comment.getString(dbTables.KEY_DATEADDED) },
{ dbTables.KEY_EDITEDBY, comment.getString(dbTables.KEY_EDITEDBY) },
{ dbTables.KEY_DATEEDITED, comment.getString(dbTables.KEY_DATEEDITED) },
{ dbTables.KEY_USERID, comment.getString(dbTables.KEY_USERID) }
};
db.insert(dbTables.TABLE_ACTIONCOMMENTS, commentValues);
}
}
}
break;
}
if(show == true){
theProgressDialog.dismiss();
}
}else{
String errorMsg = jObj.getString("error_msg");
if(errorMsg.length() > 0){
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
}
if(show == true){
theProgressDialog.dismiss();
}
}
}catch(JSONException e){
// JSON error
e.printStackTrace();
Toast.makeText(context, e+"", Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Web Error: " + error.getMessage());
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
});
// Adding request to request queue
addToRequestQueue(strreq, requestName);
}
public static RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
public static <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
请求在另一个 Activity 的 onCreate 部分调用。
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "Login";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in air plan mode it will be null
return (netInfo != null && netInfo.isConnected());
}
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
}
您看到的错误是因为您没有先调用 new WebRequest()
就调用了 WebRequest.Request()
。静态方法Request()
依赖于静态字段context
,它只在WebRequest()
的构造函数中设置。您的 static
方法需要是独立的,不需要构造对象来使用它们。
将编辑器对象写为
SharedPreferences.Editor editor = prefs.edit();