没有互联网访问数据时Android共享首选项错误

时间:2016-09-21 07:19:34

标签: android json android-sharedpreferences

我正在尝试制作数据保存在服务器上的应用程序,当我在线访问时,我在列表视图中获取该数据,然后我可以访问数据,但是当我添加 在我的代码中共享首选项然后尝试访问数据然后我无法访问以下数据是我的代码。 MainActivity

public class MainActivity extends AppCompatActivity {
ListView listView;
Button button;
String Url="my server name is here";
ArrayList<User> arrayList;
//MyFile myFile
public static String SP_FILE_NAME="sp_Listview";
//SharedPreferences spfile;
MySharedPrefLib mySharedPrefLib;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    arrayList = new ArrayList<User>();
    //myFile = new MyFile(this);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listView);
    button = (Button) findViewById(R.id.button);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (isNetworkAvailable() == true) {

                StringRequest stringRequest = new StringRequest(Request.Method.POST,Url, new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d("mytag", "Response" + response);

                        mySharedPrefLib.sharedpreferences.edit().putString("response", response).commit();

                        fillResult(response);


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Mytag", "Error" + error);

                    }

                });
                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                requestQueue.add(stringRequest);
            } else if (mySharedPrefLib.checkSharedPrefs("response")) {

                fillResult(mySharedPrefLib.getPref("response"));

            }
        }

    });
}

private void fillResult(String response) {
    try {
        JSONArray JSONArray = new JSONArray(response);

        //   myFile.sharePref("response"+response).commit;

       // arrayList = new ArrayList<User>();
        for (int i = 0; i < JSONArray.length(); i++) {
            JSONObject jsonObject = JSONArray.getJSONObject(i);
            User user = new User();

            user.setID(jsonObject.getString("ID"));
            user.setName(jsonObject.getString("Name"));
            user.setEmail(jsonObject.getString("Email"));
            user.setPassword(jsonObject.getString("Password"));

            arrayList.add(user);

        }

        UserAdapter<User> userAdapter = new UserAdapter(getApplicationContext(), arrayList);
        listView.setAdapter(userAdapter);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    return isConnected;
}

}

MySharedPrefLib.java

public class MySharedPrefLib {

Context context;
SharedPreferences sharedpreferences;

public MySharedPrefLib(Context context){
    this.context=context;
    sharedpreferences = context.getSharedPreferences(MainActivity.SP_FILE_NAME, Context.MODE_PRIVATE);
}

public void saveSharedPrefs(String user_id, String user_name, String user_email){

    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString("ID", user_id);
    editor.putString("Name", user_name);
    editor.putString("Email", user_email);
    editor.putString("Password", user_email);


    editor.commit();
}

public  String getPref(String key) {
    SharedPreferences preferences = context.getSharedPreferences(MainActivity.SP_FILE_NAME, Context.MODE_PRIVATE);
    return preferences.getString(key, null);
}

public void clearSharedPrefs(){
    SharedPreferences sharedpreferences = context.getSharedPreferences(MainActivity.SP_FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.clear();
    editor.commit();
}

public boolean checkSharedPrefs(String key){
    SharedPreferences sharedPrefs = context.getSharedPreferences(MainActivity.SP_FILE_NAME, Context.MODE_PRIVATE);
    if(sharedPrefs.contains(key)) {
        return true;
    }
    return false;
}

}

而不是这个,我又添加了两个类,即user.java和useradpter 以下是我的错误日志

错误记录

09-21 12:21:40.039 19716-19716/com.example.mahadev.listview2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.mahadev.listview2, PID: 19716
                                                                           java.lang.NullPointerException: Attempt to read from field 'android.content.SharedPreferences com.example.mahadev.listview2.MySharedPrefLib.sharedpreferences' on a null object reference
                                                                               at com.example.mahadev.listview2.MainActivity$1$1.onResponse(MainActivity.java:58)
                                                                               at com.example.mahadev.listview2.MainActivity$1$1.onResponse(MainActivity.java:52)
                                                                               at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                                                                               at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                                                                               at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:135)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

错误来自

  mySharedPrefLib.sharedpreferences.edit().putString("response", response).commit();

在这里

StringRequest stringRequest = new StringRequest(Request.Method.POST,Url, new Response.Listener<String>() {

欢迎任何建议。

3 个答案:

答案 0 :(得分:0)

添加行

  

mySharedPrefLib = new MySharedPrefLib(context);

将初始化这是唯一的问题。

答案 1 :(得分:0)

你忘了初始化mySharedPrefLib

添加 mySharedPrefLib = new MySharedPrefLib(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    arrayList = new ArrayList<User>();
    .
    .
    .
    mySharedPrefLib = new MySharedPrefLib(this);

答案 2 :(得分:0)

添加以下行

mySharedPrefLib = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

其中"com.example.app"将是您的包裹名称。

mySharedPrefLib.sharedpreferences.edit().putString("response", response).commit();

由于您的mySharedPrefLib未初始化,因此无法投掷NullPointerException