无法从doInBackground获取数据

时间:2018-07-31 20:05:59

标签: android json asynchronous

由于UI线程做了很多工作,我的代码无法正常工作。我必须执行一个异步任务来获取JSON数据。

我的问题是我无法从包含所有getter和setter的类中获取数据。我是Android开发的新手。

public class LoadPoliceData extends AsyncTask<URL,Void,Void>{

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                ProgressDialog pDialog = new ProgressDialog(MapsActivity.this);
                pDialog.setMessage("Loading Map");
                pDialog.setCancelable(true);
                pDialog.show();
            }

            @Override
            protected Void doInBackground(URL... urls) {

                //TODO: don't fetch twice could cause bug
                Bundle extras = getIntent().getExtras();
                double latitude = extras.getDouble("latitude");
                double longitude = extras.getDouble("longitude");

                String lat = String.valueOf(latitude);
                String lng = String.valueOf(longitude);

                String URL = API_URL;
                Uri.Builder builder = Uri.parse(URL).buildUpon();
                builder.appendQueryParameter("lat", lat);
                builder.appendQueryParameter("lng",lng);
                URL =builder.build().toString();

                Log.d(TAG, "buildURL: " + URL);

                if (URLUtil.isValidUrl(URL)){

                    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            try{
                                for (int i = 0; i<response.length();i++){



                                    JSONObject data = response.getJSONObject(i);
                                    policeUkApi newModel = new policeUkApi();
                                    newModel.setCategory(data.getString("category"));
                                    JSONObject latlng= data.getJSONObject("location");

                                    newModel.setLatitude(latlng.getDouble("latitude"));
                                    newModel.setLongitude(latlng.getDouble("longitude"));


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

                        }

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

                        }
                    });
                    mQueue.add(jsonArrayRequest);

                }else {
                    Log.d(TAG, "ERROR GET API DATA URL NOT VALID");
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);

                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                markerOptions.title(newModel.getCategory());
                markerOptions.snippet(newModel.getDate());
                markerOptions.position(new LatLng(newModel.getLatitude(),newModel.getLongitude()));

                Marker marker = mMap.addMarker(markerOptions);
            }
        }

我得到的错误是

enter image description here

如果您有关于理论的任何链接

,我会丢失一些教训或忘记一些我所学到的教训

1 个答案:

答案 0 :(得分:1)

根据您的需要使用此修改的类,

public class LoadPoliceData extends AsyncTask<URL,Void,policeUkApi> {
    private policeUkApi newModel=new policeUkApi();

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ProgressDialog pDialog = new ProgressDialog(MapsActivity.this);
        pDialog.setMessage("Loading Map");
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected policeUkApi doInBackground(URL... urls) {
        //TODO: don't fetch twice could cause bug
        Bundle extras = getIntent().getExtras();
        double latitude = extras.getDouble("latitude");
        double longitude = extras.getDouble("longitude");

        String lat = String.valueOf(latitude);
        String lng = String.valueOf(longitude);

        String URL = API_URL;
        Uri.Builder builder = Uri.parse(URL).buildUpon();
        builder.appendQueryParameter("lat", lat);
        builder.appendQueryParameter("lng",lng);
        URL =builder.build().toString();

        Log.d(TAG, "buildURL: " + URL);

        if (URLUtil.isValidUrl(URL)){

            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    try{
                        for (int i = 0; i<response.length();i++){



                            JSONObject data = response.getJSONObject(i);
                            newModel.setCategory(data.getString("category"));
                            JSONObject latlng= data.getJSONObject("location");

                            newModel.setLatitude(latlng.getDouble("latitude"));
                            newModel.setLongitude(latlng.getDouble("longitude"));


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

                    }

                }

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

                }
            });
            mQueue.add(jsonArrayRequest);

        }else {
            Log.d(TAG, "ERROR GET API DATA URL NOT VALID");
        }

        return newModel;
    }

    @Override
    protected void onPostExecute(policeUkApi newModel) {
        super.onPostExecute(newModel);
        if(newModel!=null){

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            markerOptions.title(newModel.getCategory());
            markerOptions.snippet(newModel.getDate());
            markerOptions.position(new LatLng(newModel.getLatitude(),newModel.getLongitude()));

            Marker marker = mMap.addMarker(markerOptions);
        }

    }
}

让我们简要介绍一下AsyncTask的工作原理

AsyncTask<InputParamType, ProgressUpdateParamType, OutputParamType>

在此示例中,URL = InputParamType,它是背景方法 doInBackGround(URL ... urls)

的输入

无效=进度参数类型,因为我们没有更新进度。

policeUkApi =您已经定义的输出自定义类类型,这是在后台线程中运行的doInBackground(...)的返回类型。

在返回结果(在本例中为您的自定义类PoliceUkApi)时,它是方法 onPostExecute(..)的输入,该方法也在UI线程中运行,您可以从在那里。

onPreExecute()也在UI线程上运行。