【问题标题】:Android plotting markers null pointer on postExecuteAndroid在postExecute上绘制标记空指针
【发布时间】:2017-08-04 03:09:01
【问题描述】:

如何在我的 for 循环中修复 java.lang.NullPointerException。我猜我在list_location.size() 上没有获得价值,此外,sharePreferences onBackground 上的 NPE。我要做的是在 postExecute 上绘制所有标记,并将其数据存储在 sharedpreferences 上,同时它在 onBackground 上运行。

问题,如何获取此处添加的 list_location 的值 list_location.add(new LocationHolder(lat, lng, location, remarks)); 我的 onBackground 并在 onPostExecute 获取它?

public class SnailTrailFragment extends Fragment implements OnMapReadyCallback {

private ProgressDialog pDialog;

ArrayList<LocationHolder> list_location;

public static GoogleMap mMapSnailTrail;

public static String baseUrl = "http://mark.journeytech.com.ph/mobile_api/";
public static NetworkAPI networkAPI;

Context context;
static Activity activity;

public SnailTrailFragment(Context c, Activity a) {
    context = c;
    activity = a;
}

public interface NetworkAPI {
    @POST("snailtrail.php")
    @Headers({"Content-Type:application/json; charset=UTF-8"})
    Call<JsonElement> loginRequest(@Body SnailTrailPojo body);
}

public static class SnailTrailPojo {
    String platenum;
    String datetimefrom;
    String datetimeto;
    String client_table;

    public SnailTrailPojo(String platenum, String datetimefrom, String datetimeto, String client_table) {
        this.platenum = platenum;
        this.datetimefrom = datetimefrom;
        this.datetimeto = datetimeto;
        this.client_table = client_table;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_contact_us, container, false);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
    mapFragment.getMapAsync(this);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMapSnailTrail = googleMap;
    new GetSnailTrail().execute();
    mMapSnailTrail.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(12.405888, 123.273419), 6));
}

class GetSnailTrail extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        httpClient.addInterceptor(logging);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();

        networkAPI = retrofit.create(NetworkAPI.class);

        SnailTrailPojo loginRequest = new SnailTrailPojo(vm.getPlate_num(), /*"08/03/2017 00:00:00"*/ BottomSheetModalFragment.dateFrom, "08/04/2017 23:59:59", client_table);

        System.out.println(vm.getPlate_num() + client_table + BottomSheetModalFragment.dateFrom + " asdas");

        Call<JsonElement> call = networkAPI.loginRequest(loginRequest);

        call.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                // success response
                if (response.body().isJsonArray()) {
                    JsonArray objectWhichYouNeed = response.body().getAsJsonArray();
   //                    System.out.println(response.body() + " "+ "Response");

                    list_location = new ArrayList<>();
                    for (int i = 0; i < response.body().getAsJsonArray().size(); i++) {

                        JsonElement location_array = response.body().getAsJsonArray().get(i);
                        JsonObject location_obj = location_array.getAsJsonObject();
                        String location = location_obj.get("location").toString();

                        JsonElement lat_array = response.body().getAsJsonArray().get(i);
                        JsonObject lat_obj = lat_array.getAsJsonObject();
                        String lati = lat_obj.get("lat").toString();
                        String latiString = lati;
                        latiString = latiString.replace("\"", "");
                        String lat = String.valueOf(latiString);

                        JsonElement lng_array = response.body().getAsJsonArray().get(i);
                        JsonObject lng_obj = lng_array.getAsJsonObject();
                        String longi = lng_obj.get("lng").toString();
                        String longiString = longi;
                        longiString = longiString.replace("\"", "");
                        String lng = String.valueOf(longiString);

                        JsonElement remarks_array = response.body().getAsJsonArray().get(i);
                        JsonObject remarks_obj = remarks_array.getAsJsonObject();
                        String remarks = remarks_obj.get("remarks").toString();
                        if (lat != null && !lat.equals("null") && (lng != null && !lng.equals("null"))) {
                            list_location.add(new LocationHolder(lat, lng, location, remarks));
                        }



                        SharedPreferences preferences = context.getSharedPreferences("AppPrefs", MODE_PRIVATE);
                        SharedPreferences.Editor prefsEditor = preferences.edit();

                        Gson gson = new Gson();

                        String jsonText = gson.toJson(list_location);
                        prefsEditor.putString("key", jsonText);
                        prefsEditor.commit();
                    }

                } else {
                    System.out.println("Not a JSONArray.");
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {
                // failure response
                System.out.println("Fail " + call.toString());
            }

        });

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

final PolylineOptions polylineOptions = new PolylineOptions();
                            for (int j = 0; j < list_location.size(); j++) {

                                // Setting the color of the polyline
                                polylineOptions.color(Color.RED);

                                // Setting the width of the polyline
                                polylineOptions.width(3);

                                Double d1 = Double.parseDouble(list_location.get(j).getLatitude());
                                Double d2 = Double.parseDouble(list_location.get(j).getLongitude());

                                Toast.makeText(getContext(), d1 + d2.toString(),Toast.LENGTH_LONG).show();
                                // Setting points of polyline
                                polylineOptions.add(new LatLng(d1, d2));

                                createMarker(j, d1, d2, list_location.get(j).getRemarks());

                            }
                            // Adding the polyline to the map
                            mMapSnailTrail.addPolyline(polylineOptions);

/*            Gson gson = new Gson();
        SharedPreferences myPrefs;
        myPrefs = context.getSharedPreferences("AppPrefs", MODE_PRIVATE);
        String jsonText = myPrefs.getString("key", null);

        Type collectionType = new TypeToken<List<LocationHolder>>(){}.getType();
        List<LocationHolder> addArray= (List<LocationHolder>) new Gson()
                .fromJson( jsonText , collectionType);*/

    }
}

public void createMarker(int index, Double latitude, Double longitude, String snippet) {
    // Adding the taped point to the ArrayList
    BitmapDescriptor image = BitmapDescriptorFactory.fromResource(R.drawable.bus);

    mMapSnailTrail.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .anchor(0.5f, 0.5f)
            .title(snippet)
            .snippet(snippet)
            .icon(image));

    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15.0f));

    mMapSnailTrail.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    });
}

public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    public MarkerInfoWindowAdapter() {
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {
        View v = getActivity().getLayoutInflater().inflate(R.layout.marker_popup, null);
        Button b = (Button) v.findViewById(R.id.button2);
        b.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                marker.hideInfoWindow();
            }
        });
        TextView markerLabel = (TextView) v.findViewById(R.id.textView2);
        markerLabel.setText("");

        return v;
    }
}
}

日志

java.lang.NullPointerException
                                                   at com.journeytech.mark.mark.fragment.SnailTrailFragment$GetSnailTrail.onPostExecute(SnailTrailFragment.java:227)
                                                   at com.journeytech.mark.mark.fragment.SnailTrailFragment$GetSnailTrail.onPostExecute(SnailTrailFragment.java:122)
                                                   at android.os.AsyncTask.finish(AsyncTask.java:632)
                                                   at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:136)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5021)
                                                   at java.lang.reflect.Method.invokeNative(Native Method)
                                                   at java.lang.reflect.Method.invoke(Method.java:515)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)

这是第二个日志

java.lang.NullPointerException 在 com.journeytech.mark.mark.fragment.SnailTrailFragment$GetSnailTrail$1.onResponse(SnailTrailFragment.java:212) 在 retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68) 在 android.os.Handler.handleCallback(Handler.java:733) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:136) 在 android.app.ActivityThread.main(ActivityThread.java:5021) 在 java.lang.reflect.Method.invokeNative(Native Method) 在 java.lang.reflect.Method.invoke(Method.java:515) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)

【问题讨论】:

  • 添加您的错误日志
  • 嗨,Ayush,已添加日志
  • 您可以添加完整的thisFragmentcode 吗?
  • 您是否正确收到onResponse 的回复?
  • 将上面的代码更新为我当前的。我想要的是在 ProgressDialog 运行时在 PostExecute 上绘制所有值,这样就没有延迟。但是,我在 list_location.size()? 有一个 NPE? ^是的

标签: java android android-asynctask android-arrayadapter android-sharedpreferences


【解决方案1】:

问题:

您正在使用改造以使用异步发送请求的enqueue 获得响应。

不,你正在做的是异步调用enqueue,没有必要这样做。您的AsyncTask 在您收到onResponse 的回复之前完成,并且当您在postExecute 中创建一个for 循环时,您会得到空指针,因为列表尚未更新并且您尝试访问它。

   @Override
public void onMapReady(GoogleMap googleMap) {
    mMapSnailTrail = googleMap;
    // Remove asynctask since you are already using retrofit enqueue
    // new GetSnailTrail().execute();
    //Create a new method to call api using retrofit
    getDataFromServer();
    mMapSnailTrail.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(12.405888, 123.273419), 6));
}

private void getDataFromServer() {

    /**
    *Show Progress dialog here      
    */

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    httpClient.addInterceptor(logging);
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();

    networkAPI = retrofit.create(NetworkAPI.class);

    SnailTrailPojo loginRequest = new SnailTrailPojo(vm.getPlate_num(), /*"08/03/2017 00:00:00"*/ BottomSheetModalFragment.dateFrom, "08/04/2017 23:59:59", client_table);

    System.out.println(vm.getPlate_num() + client_table + BottomSheetModalFragment.dateFrom + " asdas");

    Call<JsonElement> call = networkAPI.loginRequest(loginRequest);

    call.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
            // success response

           /**
           * Hide the progress dialog here
           */

            if (response.body().isJsonArray()) {
                JsonArray objectWhichYouNeed = response.body().getAsJsonArray();
                //                    System.out.println(response.body() + " "+ "Response");

                list_location = new ArrayList<>();
                for (int i = 0; i < response.body().getAsJsonArray().size(); i++) {

                    JsonElement location_array = response.body().getAsJsonArray().get(i);
                    JsonObject location_obj = location_array.getAsJsonObject();
                    String location = location_obj.get("location").toString();

                    JsonElement lat_array = response.body().getAsJsonArray().get(i);
                    JsonObject lat_obj = lat_array.getAsJsonObject();
                    String lati = lat_obj.get("lat").toString();
                    String latiString = lati;
                    latiString = latiString.replace("\"", "");
                    String lat = String.valueOf(latiString);

                    JsonElement lng_array = response.body().getAsJsonArray().get(i);
                    JsonObject lng_obj = lng_array.getAsJsonObject();
                    String longi = lng_obj.get("lng").toString();
                    String longiString = longi;
                    longiString = longiString.replace("\"", "");
                    String lng = String.valueOf(longiString);

                    JsonElement remarks_array = response.body().getAsJsonArray().get(i);
                    JsonObject remarks_obj = remarks_array.getAsJsonObject();
                    String remarks = remarks_obj.get("remarks").toString();
                    if (lat != null && !lat.equals("null") && (lng != null && !lng.equals("null"))) {
                        list_location.add(new LocationHolder(lat, lng, location, remarks));
                    }



                    SharedPreferences preferences = context.getSharedPreferences("AppPrefs", MODE_PRIVATE);
                    SharedPreferences.Editor prefsEditor = preferences.edit();

                    Gson gson = new Gson();

                    String jsonText = gson.toJson(list_location);
                    prefsEditor.putString("key", jsonText);
                    prefsEditor.commit();


                    //Move the on postExecute code here

                    final PolylineOptions polylineOptions = new PolylineOptions();
                    for (int j = 0; j < list_location.size(); j++) {

                        // Setting the color of the polyline
                        polylineOptions.color(Color.RED);

                        // Setting the width of the polyline
                        polylineOptions.width(3);

                        Double d1 = Double.parseDouble(list_location.get(j).getLatitude());
                        Double d2 = Double.parseDouble(list_location.get(j).getLongitude());

                        Toast.makeText(getContext(), d1 + d2.toString(),Toast.LENGTH_LONG).show();
                        // Setting points of polyline
                        polylineOptions.add(new LatLng(d1, d2));

                        createMarker(j, d1, d2, list_location.get(j).getRemarks());

                    }
                    // Adding the polyline to the map
                    mMapSnailTrail.addPolyline(polylineOptions);

                }

            } else {
                System.out.println("Not a JSONArray.");
            }
        }

        @Override
        public void onFailure(Call<JsonElement> call, Throwable t) {
            // failure response
            System.out.println("Fail " + call.toString());
        }

    });
}

【讨论】:

  • 该代码运行良好。但是我想要进度对话框,而它延迟绘制所有标记
  • 好的,我在代码中添加了 cmets,您可以在其中显示和隐藏对话框
  • 嗨,Ayush,在我的第二个日志上。我在 SharePreferences 上有一个 NPE。有什么线索吗?
  • 也许你的上下文是空的?
  • 嗨,Ayush,我已经设置好了class(Context c) {this.context = c;}你有什么解决办法吗?
猜你喜欢
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多