应用程序偶尔会在asynchtask中崩溃

时间:2016-10-05 16:52:19

标签: android android-asynctask

我的应用程序调用4个不同的asynchtask。很多时候应用程序按预期工作,但有时它会与asynchtask中的错误一起崩溃。

这是我的logcat

10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err: java.io.IOException: Attempted read on closed stream.
10-05 10:57:30.282 27705-27785/com.malav.holistree E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at org.apache.http.conn.EofSensorInputStream.isReadAllowed(EofSensorInputStream.java:132)
10-05 10:57:30.282 27705-27785/com.malav.holistree W/System.err:    at org.json.JSONException: End of input at character 0 of 
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err: org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:162)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at java.io.InputStreamReader.read(InputStreamReader.java:233)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at java.io.BufferedReader.readLine(BufferedReader.java:397)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at com.malav.holistree.util.JSONfunctions.makeHttpRequest(JSONfunctions.java:126)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at com.malav.holistree.dashboard.DashboardFragment$fetchQuote.doInBackground(DashboardFragment.java:492)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at     at com.malav.holistree.dashboard.DashboardFragment$fetchQuote.doInBackground(DashboardFragment.java:476)
10-05 10:57:30.282 27705-27785/com.malav.holistree W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
10-05 10:57:30.282 27705-27785/com.malav.holistree W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
10-05 10:57:30.282 27705-27781/com.malav.holistree W/System.err:     at    java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-05 10:57:30.282 27705-27785/com.malav.holistree W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
10-05 10:57:30.283 27705-27785/com.malav.holistree W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
10-05 10:57:30.283 27705-27785/com.malav.holistree W/System.err:     at com.malav.holistree.util.JSONfunctions.makeHttpRequest(JSONfunctions.java:141)
10-05 10:57:30.283 27705-27785/com.malav.holistree W/System.err:     at com.malav.holistree.notification.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:79)
10-05 10:57:30.283 27705-27785/com.malav.holistree W/System.err:     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
10-05 10:57:30.283 27705-27785/com.malav.holistree W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
10-05 10:57:30.283 27705-27785/com.malav.holistree W/System.err:     at android.os.Looper.loop(Looper.java:148)
10-05 10:57:30.283 27705-27785/com.malav.holistree W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:61)
10-05 10:57:30.283 27705-27781/com.malav.holistree W/System.err: android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-05 10:57:30.283 27705-27781/com.malav.holistree W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at java.lang.Thread.run(Thread.java:818)
10-05 10:57:30.284 27705-27781/com.malav.holistree E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err: org.json.JSONException: End of input at character 0 of 
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at com.malav.holistree.util.JSONfunctions.makeHttpRequest(JSONfunctions.java:141)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at com.malav.holistree.dashboard.DashboardFragment$fetchQuote.doInBackground(DashboardFragment.java:492)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at com.malav.holistree.dashboard.DashboardFragment$fetchQuote.doInBackground(DashboardFragment.java:476)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-05 10:57:30.284 27705-27781/com.malav.holistree W/System.err:     at java.lang.Thread.run(Thread.java:818)
10-05 10:57:30.287 27705-27781/com.malav.holistree E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                 Process: com.malav.holistree, PID: 27705
                                                                 java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                     at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                     at java.lang.Thread.run(Thread.java:818)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
                                                                     at com.malav.holistree.dashboard.DashboardFragment$fetchQuote.doInBackground(DashboardFragment.java:495)
                                                                     at com.malav.holistree.dashboard.DashboardFragment$fetchQuote.doInBackground(DashboardFragment.java:476)
                                                                     at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                                                                     at java.lang.Thread.run(Thread.java:818) 
10-05 10:57:30.312 27705-27720/com.malav.holistree V/FA: Activity paused, time: 171909023
10-05 10:57:30.629 27705-27720/com.malav.holistree D/FA: Application backgrounded. Logging engagement
10-05 10:57:30.632 27705-27720/com.malav.holistree I/FA: Tag Manager is not found and thus will not be used
10-05 10:57:30.635 27705-27720/com.malav.holistree D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=3710}]
10-05 10:57:30.693 27705-27705/com.malav.holistree D/FirebaseApp: Notifying background state change listeners.
10-05 10:57:31.312 27705-27720/com.malav.holistree D/FA: Application backgrounded. Logging engagement
10-05 10:57:31.312 27705-27720/com.malav.holistree W/FA: Not logging non-positive engagement time: 0

这是我的Java代码

    public class DashboardFragment extends Fragment {

        List<SpinnerWithTag> studentList;
        private Activity activity;
        public Context context;
        public static String filename = "MySharedString";
        private SharedPreferences someData;
        private ListView reminderList, upcomingMeetingList;
        private EditText question;
        private String s_question,l_Id;
        private Button post;
        private TextView hasNoMeetings,textViewTodayQuote;
        ImageButton editQuote;
        String todayQuote;
        Spinner studentSpinner;
        String selectedStudent, selectedStudentL_Id;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
            activity = getActivity();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.dashboard_fragment, container, false);

            someData = activity.getSharedPreferences(filename, 0);

            reminderList = (ListView) view.findViewById(R.id.listReminder);
            upcomingMeetingList = (ListView) view.findViewById(R.id.listMeetings);
            post = (Button) view.findViewById(R.id.post);
            question = (EditText) view.findViewById(R.id.question);
            hasNoMeetings = (TextView) view.findViewById(R.id.textNoMeetings);
            editQuote = (ImageButton) view.findViewById(R.id.editQuote);
            textViewTodayQuote = (TextView) view.findViewById(R.id.todayQuote);
            studentSpinner = (Spinner) view.findViewById(R.id.studentsSpinner);

            l_Id = someData.getString("commonL_Id", "");

            if(Utility.isOnline(activity)){
                new fetchQuote().execute();
            }

            post.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                if(CommonUtils.isNotNull(question.getText().toString())){
                    s_question = question.getText().toString();
                    if(Utility.isOnline(activity)){
                        new PostQuestion().execute();
                    }
                }else{
                    Toast.makeText(activity, "Cannot post blank question", Toast.LENGTH_LONG).show();
                }
                }
            });

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

                    new MaterialDialog.Builder(activity)
                        .title("Update Quote")
                        .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE)
                        .positiveText("Update")
                        .input("Type here", "", false, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                //showToast("Hello, " + input.toString() + "!");
                                todayQuote = input.toString();

                                new AddQuote().execute();
                            }
                    }).show();
                }
            });

            studentSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    SpinnerWithTag s = (SpinnerWithTag) parent.getItemAtPosition(position);
                    selectedStudent = s.getString();
                    selectedStudentL_Id = s.getTag();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            return view;
        }

        class GrabAllStudents extends AsyncTask<String, String, String> {

            JSONArray jsonarray;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {

                List<NameValuePair> para = new ArrayList<NameValuePair>();
                para.add(new BasicNameValuePair("role", "Students"));
                Log.d("request!", "starting");

                JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_ALL_STUDENTS, "POST", para);

                try{
                    studentList = new ArrayList<SpinnerWithTag>();
                    studentList.clear();
                    studentList.add(new SpinnerWithTag("Select Student", "0"));
                    studentList.add(new SpinnerWithTag("Select Global", "-1"));

                    jsonarray = jsonobject.getJSONArray("All_Students");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        jsonobject = jsonarray.getJSONObject(i);

                        String studentName = jsonobject.getString("name");
                        String selectedStudentL_Id = jsonobject.getString("l_Id");
                        studentList.add(new SpinnerWithTag(studentName,selectedStudentL_Id));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return "Success";
            }

            @Override
            protected void onPostExecute(String sResponse) {

                new GrabAllAdminUpcomingMeetings().execute();
                ArrayAdapter<SpinnerWithTag> adapter = new ArrayAdapter<SpinnerWithTag> (activity, R.layout.spinner_item_result, studentList);

                studentSpinner.setAdapter(adapter);
            }

        }

        class GrabAllUpcomingMeetings extends AsyncTask<String, String, String> {
            int flag = 0;
            JSONArray jsonarray;
            ArrayList<HashMap<String,String>> myAppointmentList;
            MyAppointmentDashboardAdapter myAppointmentAdapter;

            protected void onPreExecute()
            {
                super.onPreExecute();
            }

            protected String doInBackground(String... params)
            {

                List<NameValuePair> para = new ArrayList<NameValuePair>();
                para.add(new BasicNameValuePair("booked_l_Id", l_Id));
                Log.d("request!", "starting");

                JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_MY_APPOINTMENT, "POST", para);

                try{
                    myAppointmentList = new ArrayList<HashMap<String,String>>();
                    jsonarray = jsonobject.getJSONArray("My_Appointments");
                    for (int i = 0; i < jsonarray.length(); i++)
                    {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);

                        map.put("startTime", jsonobject.getString("startTime"));
                        map.put("endTime", jsonobject.getString("endTime"));
                        map.put("appt_Id", jsonobject.getString("appt_Id"));
                        map.put("l_Id", jsonobject.getString("l_Id"));
                        map.put("m_Id", jsonobject.getString("m_Id"));
                        map.put("date", jsonobject.getString("date"));
                        map.put("booked", jsonobject.getString("booked"));
                        map.put("approved", jsonobject.getString("approved"));
                        map.put("booked_l_Id", jsonobject.getString("booked_l_Id"));
                        map.put("booked_date", jsonobject.getString("booked_date"));
                        map.put("color", Integer.toString(Utility.getRandomColor(activity)));
                        myAppointmentList.add(map);
                    }
                }catch(JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
            protected void onPostExecute(String file_url) {
                myAppointmentAdapter = new MyAppointmentDashboardAdapter(activity, myAppointmentList);
                upcomingMeetingList.setAdapter(myAppointmentAdapter);
            }
        }

        class GrabAllAdminUpcomingMeetings extends AsyncTask<String, String, String> {
            int flag = 0;
            JSONArray jsonarray;
            ArrayList<HashMap<String,String>> adminAllAppointmentList;
            AdminBookedAppointmentDashboardAdapter AdminAppointmentAdapter;

            protected void onPreExecute()
            {
                super.onPreExecute();
            }

            protected String doInBackground(String... params)
            {

                List<NameValuePair> para = new ArrayList<NameValuePair>();
                Log.d("request!", "starting");

                JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_BOOKED_APPOINTMENT_LIST_ADMIN_FRAGMENT, "POST", para);

                try{
                    adminAllAppointmentList = new ArrayList<HashMap<String,String>>();
                    jsonarray = jsonobject.getJSONArray("Admin_Appointment_List");
                    for (int i = 0; i < jsonarray.length(); i++)
                    {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);

                        map.put("startTime", jsonobject.getString("startTime"));
                        map.put("endTime", jsonobject.getString("endTime"));
                        map.put("appt_Id", jsonobject.getString("appt_Id"));
                        map.put("l_Id", jsonobject.getString("l_Id"));
                        map.put("m_Id", jsonobject.getString("m_Id"));
                        map.put("date", jsonobject.getString("date"));
                        map.put("booked", jsonobject.getString("booked"));
                        map.put("approved", jsonobject.getString("approved"));
                        map.put("booked_l_Id", jsonobject.getString("booked_l_Id"));
                        map.put("booked_date", jsonobject.getString("booked_date"));
                        map.put("name", jsonobject.getString("name"));
                        map.put("phone", jsonobject.getString("phone"));
                        map.put("emailId", jsonobject.getString("emailId"));
                    }
                }catch(JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            protected void onPostExecute(String file_url)
            {
                if(adminAllAppointmentList!=null && adminAllAppointmentList.size()>0){
                    hasNoMeetings.setVisibility(View.GONE);
                }
                AdminAppointmentAdapter = new AdminBookedAppointmentDashboardAdapter(activity, adminAllAppointmentList);
                upcomingMeetingList.setAdapter(AdminAppointmentAdapter);
            }
        }

        class GrabAllReminders extends AsyncTask<String, String, String> {
            int flag = 0;
            JSONArray jsonarray;
            ArrayList<HashMap<String,String>> myRemindersList;
            ReminderAdapter reminderAdapter;

            protected void onPreExecute()
            {
                super.onPreExecute();
            }

            protected String doInBackground(String... params)
            {

                List<NameValuePair> para = new ArrayList<NameValuePair>();
                para.add(new BasicNameValuePair("login_Id", l_Id));
                Log.d("request!", "starting");

                JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_GRAB_ALL_REMINDERS, "POST", para);

                try{
                    myRemindersList = new ArrayList<HashMap<String,String>>();
                    jsonarray = jsonobject.getJSONArray("All_Reminders");
                    for (int i = 0; i < jsonarray.length(); i++)
                    {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);

                        map.put("r_date", jsonobject.getString("r_date"));
                        map.put("reminder", jsonobject.getString("reminder"));
                        map.put("r_Id", jsonobject.getString("r_Id"));
                        map.put("login_Id", jsonobject.getString("login_Id"));
                        myRemindersList.add(map);
                    }
                }catch(JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
            protected void onPostExecute(String file_url) {
                reminderAdapter = new ReminderAdapter(activity, myRemindersList);
                reminderList.setAdapter(reminderAdapter);
            }
        }

        class PostQuestion extends AsyncTask<String, String, String> {
            int flag = 0;
            String success="0", message="";

            protected void onPreExecute()
            {
                super.onPreExecute();
            }

            protected String doInBackground(String... params)
            {

                List<NameValuePair> para = new ArrayList<NameValuePair>();
                para.add(new BasicNameValuePair("l_Id", l_Id));
                para.add(new BasicNameValuePair("question", s_question));

                Log.d("request!", "starting");

                JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_POST_QUESTION, "POST", para);

                try{
                    success = jsonobject.getString("success");
                    message = jsonobject.getString("message");

                }catch(JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
            protected void onPostExecute(String file_url) {
                if(!success.equalsIgnoreCase("0") && !success.equalsIgnoreCase("")){
                    question.setText("");
                    Toast.makeText(activity, "Question posted successfully", Toast.LENGTH_LONG).show();
                }else{
                }
            }
        }

        class AddQuote extends AsyncTask<String, String, String> {
            int flag = 0;
            String success="0", message="";

            protected void onPreExecute()
            {
                super.onPreExecute();
            }

            protected String doInBackground(String... params)
            {

                List<NameValuePair> para = new ArrayList<NameValuePair>();
                para.add(new BasicNameValuePair("todayQuote", todayQuote));
                JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_ADD_QUOTE, "POST", para);

                try{
                    success = jsonobject.getString("success");
                    message = jsonobject.getString("message");

                }catch(JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
            protected void onPostExecute(String file_url) {
                if(!success.equalsIgnoreCase("0") && !success.equalsIgnoreCase("")){
                    textViewTodayQuote.setText(todayQuote);
                    Toast.makeText(activity, "Quote Updates", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(activity, "Quote failed to post", Toast.LENGTH_LONG).show();
                }
            }
        }

        class fetchQuote extends AsyncTask<String, String, String> {
            int flag = 0;
            JSONArray jsonarray;
            String success="0", message="";
            String quote;

            protected void onPreExecute()
            {
                super.onPreExecute();
            }

            protected String doInBackground(String... params)
            {
                List<NameValuePair> para = new ArrayList<NameValuePair>();
                para.add(new BasicNameValuePair("todayQuote", todayQuote));
                Log.d("request!", "starting");
                JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_FETCH_QUOTE, "POST", para);

                try{
                    jsonarray = jsonobject.getJSONArray("TodaysQuote");
                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);

                        quote = jsonobject.getString("quoteText");
                    }
                }catch(JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
            protected void onPostExecute(String file_url) {
                textViewTodayQuote.setText(quote);

                if(someData.contains("role")) {
                    if (Utility.isOnline(activity)) {
                        new GrabAllReminders().execute();
                        if (someData.getString("role", "").equalsIgnoreCase("Admin")) {
                            editQuote.setVisibility(View.VISIBLE);
                            studentSpinner.setVisibility(View.VISIBLE);
                            new GrabAllStudents().execute();

                        }else{
                            new GrabAllUpcomingMeetings().execute();
                        }
                    }else{
                        Toast.makeText(getActivity(), "Connectivity Issues, You are offline", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

    }

我的PHP文件正在以预期的方式正确返回数据。

我很困惑,应用程序不是每次都崩溃。它偶尔会崩溃。

3 个答案:

答案 0 :(得分:2)

将此行放在try/catch

JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_MY_APPOINTMENT, "POST", para);

答案 1 :(得分:2)

logcat日志显示问题所在:

at com.malav.holistree.util.JSONfunctions.makeHttpRequest(JSONfunctions.java:126)

所以它在JSONfunctions.java和第126行。

java.io.IOException: Attempted read on closed stream.因此您可能偶尔遇到网络或服务器问题,当您尝试从数据构建org.json.JSONException时,还会JSONObject那不是。

如果您希望有人查看它,您可以发布JSONfunctions.java,并建议改进错误处理。

您可以打包方法调用

JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_ALL_STUDENTS, "POST", para);

在try catch中,应该抓住 java.io.IOExceptionorg.json.JSONException

但是当然你要么在try-catch之外需要JSONObject jsonobject;,要么你也可以在同一个try-catch中包含访问jsonobject的所有代码:

try {
    JSONObject jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_ALL_STUDENTS, "POST", para);

    studentList = new ArrayList<SpinnerWithTag>();
    studentList.clear();
    studentList.add(new SpinnerWithTag("Select Student", "0"));
    studentList.add(new SpinnerWithTag("Select Global", "-1"));

    jsonarray = jsonobject.getJSONArray("All_Students");

    for (int i = 0; i < jsonarray.length(); i++) {
        jsonobject = jsonarray.getJSONObject(i);

        String studentName = jsonobject.getString("name");
        String selectedStudentL_Id = jsonobject.getString("l_Id");
        studentList.add(new SpinnerWithTag(studentName,selectedStudentL_Id));
    }            
} catch (JSONException|java.io.IOException e) {
    e.printStackTrace();
}

或者你可以只包括麻烦的方法调用,并在catch块中返回除了&#34;成功&#34;:

之外的其他内容
JSONObject jsonobject; 
try {
    jsonobject = JSONfunctions.makeHttpRequest(QueryMapper.URL_ALL_STUDENTS, "POST", para);
} catch (JSONException|java.io.IOException e) {
    e.printStackTrace();
    return "";
}

现在studentList会有一些旧数据(可能......我不详细了解您的应用程序)如果onPostExecute()您应忽略doInBackground()中的代码返回&#34;成功&#34;:

以外的其他内容
@Override
protected void onPostExecute(String sResponse) {

    if (sResponse.equals("Success") {
        new GrabAllAdminUpcomingMeetings().execute();
        ArrayAdapter<SpinnerWithTag> adapter = new ArrayAdapter<SpinnerWithTag> (activity, R.layout.spinner_item_result, studentList);

        studentSpinner.setAdapter(adapter);
    }
}

如您更了解代码,您应该考虑在这种情况下studentSpinner.setAdapter(adapter);方法调用是否存在任何问题。

简单地用try-catch包装JSONfunctions.makeHttpRequest()方法调用无论如何都会留下一些问题。

答案 2 :(得分:0)

您的数据请求不正确。输入流正在关闭,因为:

require 'FastRoute/RouteCollector.php';
require 'FastRoute/Dispatcher.php';
...

这意味着您的服务器偶尔会返回一个对象的空值。检查您的PHP并验证返回的数据。具体来说,您可能希望逐行解析而不是依赖库来调试这个。