共享首选项始终返回null并引发运行时异常

时间:2017-03-22 17:05:58

标签: android string sharedpreferences android-volley jsonexception

我是Android应用程序开发的新手。我的app项目中出现了一个奇怪的错误。当我第一次在模拟器(Genymotion)中运行代码时,应用程序运行得非常好。为了工作,应用程序在许多地方使用共享首选项。 然后,如果我在使用一段时间后卸载应用程序,然后在模拟器中重新安装应用程序,应用程序的登录过程就可以了。但是,当我使用其他片段时,我收到运行时错误,应用程序崩溃了。此代码在第一次安装时完美无缺。出于某种原因,如果我在模拟器中卸载应用程序,它将无法正常工作。我正在使用凌空抽射。网络很好,REST API提供了它应该给出的完美响应。我想知道我会错过在代码中处理的内容。这是发生错误的AttendanceFragment.java的代码。

package com.learn.app;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.app.AlertDialog;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.learn.app.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import dmax.dialog.SpotsDialog;

public class AttendanceFragment extends Fragment {
TableLayout attendancetable;
private AlertDialog progressDialog;
TextView attendance_name,attendance_rollno,attendance_dept,attendance_semester,attendance_dateupto;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_attendance, container, false);
}
public void getAttendance() {
    progressDialog.show();
    StringRequest stringRequest=new StringRequest(Request.Method.POST,
            Constants.URL_ATTEND,
            new Response.Listener<String>(){
                @Override
                public void onResponse(String response){
                    progressDialog.dismiss();
                    try {
                        JSONObject jsonObject=new JSONObject(response);
                        //start a new activity
                        System.out.println("hello world");
                        JSONArray AttendanceDetails=jsonObject.optJSONArray("response");
                        SharedPreferences prefAttendanceDetails = getActivity().getApplicationContext().getSharedPreferences("AttendanceDetails", 0); // 0 - for private mode
                        SharedPreferences.Editor editorAttendanceDetails = prefAttendanceDetails.edit();
                        editorAttendanceDetails.clear();
                        editorAttendanceDetails.commit();
                        editorAttendanceDetails.putString("Attendance",AttendanceDetails.toString());
                        editorAttendanceDetails.commit();


                    }
                    catch (JSONException e) {
                        LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View Layout=inflater.inflate(R.layout.custom_toast,null);
                        Toast toast=new Toast(getActivity().getApplicationContext());
                        toast.setGravity(Gravity.BOTTOM,0,0);
                        toast.setDuration(Toast.LENGTH_LONG);
                        toast.setView(Layout);
                        TextView toasterror=(TextView)Layout.findViewById(R.id.error);
                        toasterror.setText("Exception thrown");
                        toast.show();
                    }
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    progressDialog.hide();

                    LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View Layout=inflater.inflate(R.layout.custom_toast,null);
                    Toast toast=new Toast(getActivity().getApplicationContext());
                    toast.setGravity(Gravity.BOTTOM,0,0);
                    toast.setDuration(Toast.LENGTH_LONG);
                    toast.setView(Layout);
                    TextView toasterror=(TextView)Layout.findViewById(R.id.error);
                    toasterror.setText("Internet Connection Failed");
                    toast.show();
                    FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                    ft.setCustomAnimations(R.anim.trans_right_in,R.anim.trans_right_out);
                    ft.replace(R.id.content_frame, new HomeFragment());
                    ft.commit();

                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("Username", "13LM06");

            return params;

        }
    };

    RequestHandler.getInstance(getActivity().getApplicationContext()).addToRequestQueue(stringRequest);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("AppStatus", 0); // 0 - for private mode
    SharedPreferences.Editor editor = pref.edit();
    editor.putBoolean("Home", false);
    editor.commit();
    progressDialog = new SpotsDialog(getActivity(), R.style.CustomLoading);
    progressDialog.setCancelable(false);
    getAttendance();


    getActivity().setTitle("Attendance");

    SharedPreferences prefProfileDetails = getActivity().getApplicationContext().getSharedPreferences("ProfileDetails", 0);
    attendance_name=(TextView)getActivity().findViewById(R.id.attendance_name);
    attendance_rollno=(TextView)getActivity().findViewById(R.id.attendance_rollno);
    attendance_semester=(TextView)getActivity().findViewById(R.id.attendance_semester);
    attendance_dept=(TextView)getActivity().findViewById(R.id.attendance_dept);
    attendance_dateupto=(TextView)getActivity().findViewById(R.id.attendance_dateupto);


    attendancetable=(TableLayout)getActivity().findViewById(R.id.attendancetable);
    SharedPreferences prefAttendanceDetails = getActivity().getApplicationContext().getSharedPreferences("AttendanceDetails", 0);
    try {
        // Toast.makeText(getActivity().getApplicationContext(),prefAttendanceDetails.getString("Attendance", null),Toast.LENGTH_LONG);
        JSONArray Attendance = new JSONArray(prefAttendanceDetails.getString("Attendance", null));
        for(int i=0;i<Attendance.length();i++){
            JSONObject SubjectDetails = Attendance.getJSONObject(i);
            TableRow row = new TableRow(getActivity().getApplicationContext());
            TableLayout.LayoutParams params=new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT);
            params.setMargins(0,0,0,5);
            row.setLayoutParams(params);
            row.setWeightSum(7.0f);
            if(i==0) {
                attendance_name.setText(SubjectDetails.getString("NAME"));
                attendance_rollno.setText(SubjectDetails.getString("ROLLNO"));
                attendance_dept.setText(SubjectDetails.getString("PROG_NAME"));
                attendance_semester.setText("SEM : "+SubjectDetails.getString("SEM_NO"));
                attendance_dateupto.setText("Last update :"+SubjectDetails.getString("RUN_DATE"));
            }
            TextView Course=new TextView(getActivity().getApplicationContext());
            Course.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT,1f));
            Course.setGravity(Gravity.CENTER);
            Course.setTextColor(Color.parseColor("#393b41"));
            Course.setText(SubjectDetails.getString("COURSE_CODE"));

            TextView TotalHours=new TextView(getActivity().getApplicationContext());
            TotalHours.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT,1f));
            TotalHours.setGravity(Gravity.CENTER);
            TotalHours.setTextColor(Color.parseColor("#393b41"));
            TotalHours.setText(SubjectDetails.getString("COURSE_HOURS"));

            TextView TotalPresent=new TextView(getActivity().getApplicationContext());
            TotalPresent.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT,1f));
            TotalPresent.setGravity(Gravity.CENTER);
            TotalPresent.setTextColor(Color.parseColor("#393b41"));
            TotalPresent.setText(SubjectDetails.getString("COURSE_TOT_PRESENT"));

            TextView TotalAbsent=new TextView(getActivity().getApplicationContext());
            TotalAbsent.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT,1f));
            TotalAbsent.setGravity(Gravity.CENTER);
            TotalAbsent.setTextColor(Color.parseColor("#393b41"));
            TotalAbsent.setText(SubjectDetails.getString("COURSE_TOT_ABSENT"));

            TextView Exception=new TextView(getActivity().getApplicationContext());
            Exception.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT,1f));
            Exception.setGravity(Gravity.CENTER);
            Exception.setTextColor(Color.parseColor("#393b41"));
            Exception.setText(SubjectDetails.getString("COURSE_EXEMPTION"));


            TextView Percentage=new TextView(getActivity().getApplicationContext());
            Percentage.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT,1f));
            Percentage.setGravity(Gravity.CENTER);
            Percentage.setTextColor(Color.parseColor("#393b41"));
            Percentage.setText(SubjectDetails.getString("COURSE_PERC"));

            TextView PercentageWithException=new TextView(getActivity().getApplicationContext());
            PercentageWithException.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT,1f));
            PercentageWithException.setGravity(Gravity.CENTER);
            PercentageWithException.setTextColor(Color.parseColor("#393b41"));
            PercentageWithException.setText(SubjectDetails.getString("COURSE_PERC_EXEMP"));

            row.addView(Course);
            row.addView(TotalHours);
            row.addView(TotalPresent);
            row.addView(TotalAbsent);
            row.addView(Exception);
            row.addView(Percentage);
            row.addView(PercentageWithException);
            attendancetable.addView(row,2*i+1);

            TableRow row1 = new TableRow(getActivity().getApplicationContext());
            TableLayout.LayoutParams params1 = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT);
            params.setMargins(0, 18, 0, 18);
            row1.setLayoutParams(params1);

            View v = new View(getActivity().getApplicationContext());
            TableRow.LayoutParams params2 = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 1, 1f);
            v.setBackgroundColor(Color.parseColor("#FF909090"));
            v.setPadding(2, 2, 2, 2);
            v.setLayoutParams(params2);
            row1.addView(v);
            attendancetable.addView(row1, 2 * i + 2);

        }
    }catch(JSONException e){
        e.printStackTrace();
    }
}
}

这是Logcat中的响应

03-22 12:35:02.360 7872-7901/com.learn.miniproject W/EGL_emulation:eglSurfaceAttrib not implemented
03-22 12:35:02.360 7872-7901/com.learn.miniproject W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xec8e7040, error=EGL_SUCCESS
03-22 12:35:03.306 7872-7872/com.learn.miniproject I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.
03-22 12:35:03.426 7872-7901/com.learn.miniproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xf3d574e0

[ 03-22     12:35:03.708    99:   99 D/         ] Socket deconnection
03-22 12:35:05.373 7872-7872/com.learn.miniproject D/AndroidRuntime: Shutting down VM
03-22 12:35:05.375 7872-7872/com.learn.miniproject E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.learn.miniproject, PID: 7872
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                                     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                                     at org.json.JSONArray.<init>(JSONArray.java:92)
                                                                     at org.json.JSONArray.<init>(JSONArray.java:108)
                                                                     at com.learn.app.AttendanceFragment.onActivityCreated(AttendanceFragment.java:151)
                                                                     at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1797)
                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:979)
                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
                                                                     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
                                                                     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
                                                                     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-22 12:35:08.332 7872-7872/com.learn.miniproject I/Process: Sending signal. PID: 7872 SIG: 9

因此,网络连接正常。凌空没有错误。发生错误,就好像字符串请求部分不起作用。所以Shardpreference getString()总是返回null。因此最终导致应用程序崩溃。请帮我。我错过了什么?

1 个答案:

答案 0 :(得分:1)

尝试更改此部分:

System.out.println("hello world");
                        JSONArray AttendanceDetails=jsonObject.optJSONArray("response");
                        SharedPreferences prefAttendanceDetails = getActivity().getApplicationContext().getSharedPreferences("AttendanceDetails", 0); // 0 - for private mode
                        SharedPreferences.Editor editorAttendanceDetails = prefAttendanceDetails.edit();
                        editorAttendanceDetails.clear();
                        editorAttendanceDetails.commit();
                        editorAttendanceDetails.putString("Attendance",AttendanceDetails.toString());
                        editorAttendanceDetails.commit();

要:

System.out.println("hello world");
                        JSONArray AttendanceDetails=jsonObject.optJSONArray("response");
if(AttendanceDetails != null){
                        SharedPreferences prefAttendanceDetails = getActivity().getApplicationContext().getSharedPreferences("AttendanceDetails", 0); // 0 - for private mode
                        SharedPreferences.Editor editorAttendanceDetails = prefAttendanceDetails.edit();
                        editorAttendanceDetails.clear();
                        editorAttendanceDetails.commit();
                        editorAttendanceDetails.putString("Attendance",AttendanceDetails.toString());
                        editorAttendanceDetails.commit();
}

另外,你有什么理由试图直接从JsonArray转换为String吗?