java - 异步任务中的空指针异常

标签 java android asynchronous

when i tried to put direction from source to destination on map this null pointer exception heppen when i tried to put direction from source to destination on map this null pointer exception heppen

            l

ocat:

                07-05 02:19:21.569 23133-23133/com.example.saad.testapp E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.example.saad.testapp, PID: 23133
                    java.lang.NullPointerException
                        at com.example.saad.testapp.map$TaskParser.onPostExecute(map.java:248)
                        at com.example.saad.testapp.map$TaskParser.onPostExecute(map.java:205)
                        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:146)
                        at android.app.ActivityThread.main(ActivityThread.java:5511)

                        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:1283)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                        at dalvik.system.NativeStart.main(Native Method)

map.class is as follows :

            public class map extends FragmentActivity implements OnMapReadyCallback {

                private GoogleMap mMap;
                loc ambLoc;
                loc patLoc;
                String tempE;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_map);
                    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
                    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.map);
                    mapFragment.getMapAsync(this);
                    ambLoc=new loc();
                    patLoc=new loc();
                    tempE=new String();
                }



                @Override
                public void onMapReady(GoogleMap googleMap) {
                    getPoints();
                }
                void getPoints()
                {


            //some code here


                    String url=getRequestUrl(ambLoc,patLoc);
                    TaskRequestDirections taskRequestDirections = new TaskRequestDirections();
                    taskRequestDirections.execute(url);


                }
                private String getRequestUrl(loc origin, loc dest) {
                    //Value of origin
                    String str_org = "origin=" + origin.getLatitude() +","+origin.getLongitude();
                    //Value of destination
                    String str_dest = "destination=" + dest.getLatitude()+","+dest.getLongitude();
                    //Set value enable the sensor
                    String sensor = "sensor=false";
                    //Mode for find direction
                    String mode = "mode=driving";
                    //Build the full param
                    String param = str_org +"&" + str_dest + "&" +sensor+"&" +mode;
                    //Output format
                    String output = "json";
                    //Create url to request
                    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + param;
                    return url;
                }
                private String requestDirection(String reqUrl) throws IOException {
                    String responseString = "";
                    InputStream inputStream = null;
                    HttpURLConnection httpURLConnection = null;
                    try{
                        URL url = new URL(reqUrl);
                        httpURLConnection = (HttpURLConnection) url.openConnection();
                        httpURLConnection.connect();

                        //Get the response result
                        inputStream = httpURLConnection.getInputStream();
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                        StringBuffer stringBuffer = new StringBuffer();
                        String line = "";
                        while ((line = bufferedReader.readLine()) != null) {
                            stringBuffer.append(line);
                        }

                        responseString = stringBuffer.toString();
                        bufferedReader.close();
                        inputStreamReader.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        httpURLConnection.disconnect();
                    }
                    return responseString;
                }


                public class TaskRequestDirections extends AsyncTask<String, Void, String> {

                    @Override
                    protected String doInBackground(String... strings) {
                        String responseString = "";
                        try {
                            responseString = requestDirection(strings[0]);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return  responseString;
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        //Parse json here
                        TaskParser taskParser = new TaskParser();
                        taskParser.execute(s);
                    }
                }

having exception on the below line

                public class TaskParser extends AsyncTask<String, Void, List<List<HashMap<String, String>>> > {

                    @Override
                    protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
                        JSONObject jsonObject = null;
                        List<List<HashMap<String, String>>> routes = null;
                        try {
                            jsonObject = new JSONObject(strings[0]);
                            DirectionParser directionsParser = new DirectionParser();
                            routes = directionsParser.parse(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return routes;
                    }

                    @Override
                    protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
                        //Get list route and display it into the map

                        ArrayList points = null;

                        PolylineOptions polylineOptions = null;

                        for (List<HashMap<String, String>> path : lists) {
                            points = new ArrayList();
                            polylineOptions = new PolylineOptions();

                            for (HashMap<String, String> point : path) {
                                double lat = Double.parseDouble(point.get("lat"));
                                double lon = Double.parseDouble(point.get("lon"));

                                points.add(new LatLng(lat,lon));
                            }

                            polylineOptions.addAll(points);
                            polylineOptions.width(15);
                            polylineOptions.color(Color.BLUE);
                            polylineOptions.geodesic(true);
                        }

                        if (polylineOptions!=null) {
                            Toast.makeText(getApplicationContext(), "adding polyline!", Toast.LENGTH_SHORT).show();

having exception on the

                            mMap.addPolyline(polylineOptions);
                        } else {
                            Toast.makeText(getApplicationContext(), "Direction not found!", Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            }

suggest any solution if you have thank you thank you thank you thank you

最佳答案

你从来没有设置过mMap变量尝试这样

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    getPoints();
}

关于java - 异步任务中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181072/

相关文章:

使用 while 循环的 Java 数组

android - 如何删除出现在 XML Android 列表项之间的透明线

java - 如何在 Android studio 中的 Runnable() 中断中设置断点?

Android,onPrepareDialog 更新参数化字符串不更新。

java - 使用@EnableAsync时Spring Boot不响应任何请求

javascript - React 的 setState 是异步的还是什么?

java - 即使使用了 Set,数组中仍存在重复项

java - Java中如何继承多个基类?

java - 提取字符串的设备名称

c++ - QObject : Cannot create children for a parent that is in a different thread