应用关闭后无法访问共享偏好

时间:2015-07-01 11:45:22

标签: android nullpointerexception sharedpreferences static-methods

我有一个webrequest活动,它向网络服务器发出请求并存储数据。

从登录中使用该应用程序时,一切都很好。但是一旦应用程序关闭并重新打开,任何对服务器的请求都会遇到以下错误:

for l in listoflist:
    d_temp = []
    for s in l:
        d_temp.append(s.encode('ascii'))
    d.append(d_temp)

这是用于发出网络请求的类:

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

请求在另一个Activity的onCreate部分中调用。

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);
    }
}

}

2 个答案:

答案 0 :(得分:1)

您看到的错误是因为您在没有先致电WebRequest.Request()的情况下致电new WebRequest()。静态方法Request()取决于静态字段context,它仅在WebRequest()的构造函数中设置。您的static方法必须是独立的,不需要构造对象来使用它们。

答案 1 :(得分:0)

将编辑器对象编写为

SharedPreferences.Editor editor = prefs.edit();