0

I am a newbie in android app development. I am getting a weird error in my app project. When I run the code for the first time in an emulator(Genymotion) the app runs perfectly well. For working the app uses shared preferences in many places. Then if I uninstall the app after using for a while and then reinstall the app in the emulator, the login process of the app works just fine. But when I use other fragments I am getting a runtime error and the app crashes. This code works perfectly fine in the first install. For some reason it's not working if I uninstall the app in the emulator. I am using volley. The network is fine and REST API gives the perfect response it was supposed to give. I am wondering what I would've missed to handle in the code. This is the code of AttendanceFragment.java where the error occurs.

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

This is the response in 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

So , the network connection is working. No error in volley. The error occurs as if String Request part is not working. So the Shardpreference getString() is always returning null. Thus eventually leading to app crash. Please help me. What am I missing?

Hewitt V S
  • 11
  • 3

1 Answers1

1

Try changing this part:

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

To:

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

Also, is there any reason why are you trying to convert directly from JsonArray to String?

  • It is not possible to store JsonArray as such in shared preferences. So I change it to string to access it at different places. – Hewitt V S Mar 22 '17 at 17:30
  • For some reason, the code where I try to read shared preferences is executed before writing a value into it. – Hewitt V S Mar 22 '17 at 17:34