【问题标题】:Converting Asnyctask to volley [duplicate]将 Asnyctask 转换为 volley [重复]
【发布时间】:2017-07-21 09:30:19
【问题描述】:

我是 android 新手,我正在尝试将以下 asnyctask 代码转换为 volley,但收到了很多关于如何完全成功的错误建议

private class AsyncJsonObject extends AsyncTask<String, Void, String> {

        private ProgressDialog progressDialog;

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

            HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httpPost = new HttpPost("http://192.168.0.2/testquiz/index.php");
            String jsonResult = "";

            try {
                HttpResponse response = httpClient.execute(httpPost);
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
                System.out.println("Returned Json object " + jsonResult.toString());

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return jsonResult;
        }
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog = ProgressDialog.show(QuizActivity.this, "Downloading Quiz","Wait....", true);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            System.out.println("Resulted Value: " + result);
            parsedObject = returnParsedJsonObject(result);
            if(parsedObject == null){
                return;
            }
            quizCount = parsedObject.size();
            firstQuestion = parsedObject.get(0);

            quizQuestion.setText(firstQuestion.getQuestion());
            String[] possibleAnswers = firstQuestion.getAnswers().split(",");
            optionOne.setText(possibleAnswers[0]);
            optionTwo.setText(possibleAnswers[1]);
            optionThree.setText(possibleAnswers[2]);
            optionFour.setText(possibleAnswers[3]);
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = br.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return answer;
        }
    }
    */
    private List<QuizWrapper> returnParsedJsonObject(String result) {

        List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
        JSONObject resultObject = null;
        JSONArray jsonArray = null;
        QuizWrapper newItemObject = null;
        try {
            resultObject = new JSONObject(result);
            System.out.println("Testing the water " + resultObject.toString());
            jsonArray = resultObject.optJSONArray("quiz_questions");
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        if (jsonArray != null) {     // check jsonArray is null?
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonChildNode = null;
                try {
                    jsonChildNode = jsonArray.getJSONObject(i);
                    int id = jsonChildNode.getInt("id");

                    String question = jsonChildNode.getString("question");
                    String answerOptions = jsonChildNode.getString("possible_answers");
                    int correctAnswer = jsonChildNode.getInt("correct_answer");
                    newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer);
                    jsonObject.add(newItemObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
            return jsonObject;
        }

这是我迄今为止所取得的成就,任何帮助将不胜感激

public Object getQuestion() {
        JsonObjectRequest  jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray questions = response.getJSONArray("questions");
                    for(int i=0; i<questions.length(); i++){
                        JSONObject quiz_questions = questions.getJSONObject(i);

                        String firstQuestion = quiz_questions.getString("firstQuestion");
                        String optionOne = quiz_questions.getString("optionOne");
                        String optionTwo = quiz_questions.getString("optionTwo");
                        String optionThree = quiz_questions.getString("optionThree");
                        String optionFour = quiz_questions.getString("optionFour");

                        quizQuestion.append(firstQuestion+ "" +optionOne+"" +optionTwo+""+optionThree+""+optionFour+ "");




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

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestQueue.add(jsonObjectRequest);
        return question;
    }

发生的错误

FATAL EXCEPTION: main

Process: test.com.okcupid, PID: 31544
                                                                      java.lang.RuntimeException: Unable to start activity ComponentInfo{test.com.okcupid/test.com.okcupid.QuizActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)    
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at test.com.okcupid.QuizActivity.getQuestion(QuizActivity.java:175)
at test.com.okcupid.QuizActivity.onCreate(QuizActivity.java:118)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

【问题讨论】:

标签: android android-asynctask android-volley


【解决方案1】:

问题出在这一行:

requestQueue.add(jsonObjectRequest);

由于某种原因,它到达requestQueue 行时为空。您需要确保在使用变量之前对其进行初始化。如果你不能确定,那么总是用

包裹它
if (requestQueue != null)

您还需要学习有关多线程如何工作的快速教程。因为在 getQuestion 中,您启动了一个异步请求 (JsonObjectRequest),它之后的行(requestQueue.add(jsonObjectRequest) 和 return 语句)将在 before onResponse

之前执行

【讨论】:

  • 我该怎么做?
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 2013-02-10
  • 2015-04-11
  • 1970-01-01
  • 2015-08-06
  • 2017-03-03
  • 2020-05-16
  • 2011-07-27
相关资源
最近更新 更多