1

我是 android 开发的初学者,我正在构建一个与地图创建路线相关的应用程序。经纬度数据取自 php API。问题是当我调试程序时它工作得很好但是当我运行应用程序时它显示空点异常。请建议我我能做什么..

public class Driver extends AppCompatActivity{

    GoogleMap map;
    GPSTracker gps;
    String longitude;
    String latitude;
    String url;
    Context mContext;
    ArrayList<LatLng> markerPoints = new ArrayList<LatLng>();
    SupportMapFragment fm;
    LinearLayout layout;
    ArrayList<String> truck = new ArrayList<String>();
    ArrayList<LatLng> truck_latlong = new ArrayList<LatLng>();

    ArrayList<String> disposail = new ArrayList<String>();
    ArrayList<LatLng> disposail_latlong = new ArrayList<LatLng>();
    int mMode = 0;
    final int MODE_DRIVING = 0;
    final int MODE_BICYCLING = 1;
    final int MODE_WALKING = 2;
    public static final String EMAIL_SHARED_PREF = "phone";
    public static final String LOGGEDIN_SHARED_PREF = "success";
    public static final String SHARED_PREF_NAME = "myappLogin";
    private String Data_Url="http://XXXXXXXXXXXX/Android/driver_work.php";
    private String Truck_url = "http://XXXXXXXXXXXX/Android/trucks.php";
    public String Disposal_url = "http://XXXXXXXXXXXX/Android/disposal_bins.php";
    private String COMPLETE_STATUS = "http://XXXXXXXXXXXX/Android/driver_work_complete.php";

    Config config = new Config();
    FloatingActionButton fab;
    SwipeRefreshLayout swipeRefreshLayout;
    ArrayList<Marker> arraymarker= new ArrayList<Marker>();
    LatLng origin;
    LatLng dest;
    private Marker maps;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    //        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.tvlayout);
    //        swipeRefreshLayout.setOnRefreshListener(this);

        // Getting Map for the SupportMapFragment
        map = fm.getMap();
        fab = (FloatingActionButton) findViewById(R.id.fab);
    //        fab.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View view) {
    //                complete_status();
    //
    //
    //            }
    //        });


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        map.setMyLocationEnabled(true);


        truck_info();
        disposal_info();

        driver_response();





    }
    public void complete_status()
    {

    }
    //    @Override
    //    public void onRefresh() {
    //
    //        new Handler().postDelayed(new Runnable() {
    //            @Override
    //            public void run() {
    //                swipeRefreshLayout.setRefreshing(false);
    //
    //                driver_response();
    ////
    //            }
    //        }, 4000);
    //    }


    private void logout(){
        //Creating an alert dialog to confirm logout
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure you want to logout?");
        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                        //Getting out sharedpreferences
                        SharedPreferences preferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
                        //Getting editor
                        SharedPreferences.Editor editor = preferences.edit();
                        //Puting the value false for loggedin
                        editor.putBoolean(LOGGEDIN_SHARED_PREF, false);

                        //Putting blank value to email
                        editor.putString(EMAIL_SHARED_PREF,"");

                        //Saving the sharedpreferences
                        editor.commit();

                        //Starting login activity
                        Intent intent = new Intent(Driver.this, MainActivity.class);
                        startActivity(intent);
                    }
                });

        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });

        //Showing the alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

    public void truck_info()
    {
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Truck_url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        truck_Json(response);

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


                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }
    public void truck_Json(JSONArray array)
    {
        for (int i = 0; i < array.length(); i++) {
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);


                String truck_no = json.getString("truck_id");
                truck.add(truck_no);
                String capacity = json.getString("capacity");
                String truck_lat = json.getString("latitude");
                String truck_long = json.getString("longitude");

                LatLng mlstlong = new LatLng(Double.parseDouble(truck_lat), Double.parseDouble(truck_long));
                truck_latlong.add(mlstlong);

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

    }

    public void disposal_info()
    {
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Disposal_url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        disposal_Json(response);

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


                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }
    public void disposal_Json(JSONArray array)
    {
        for (int i = 0; i < array.length(); i++) {
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);


                String disposial_id = json.getString("disposal_bin_id");
    //                truck.add(truck_no);
                disposail.add(disposial_id);

                String disposial_lat = json.getString("latitude");
                String disposial_long = json.getString("longitude");

                LatLng mlstlong = new LatLng(Double.parseDouble(disposial_lat), Double.parseDouble(disposial_long));
                disposail_latlong.add(mlstlong);

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

    }


    public void driver_response()
       {

           Intent i = getIntent();
           final String str = i.getStringExtra("phone");
           TextView tv = (TextView)findViewById(R.id.textView);
           tv.setText(str);


           StringRequest stringRequest = new StringRequest(Request.Method.POST,Data_Url,
                   new Response.Listener<String>() {
                       @Override
                       public void onResponse(String s) {

                         if(s.equalsIgnoreCase("Work is not been alloted yet"))
                         {
                             layout = (LinearLayout)findViewById(R.id.maplayout);
                             layout.setVisibility(View.INVISIBLE);
                             fab.setVisibility(View.INVISIBLE);
                             TextView tv = (TextView)findViewById(R.id.textView2);
                             tv.setText(s);

                         }
                           else{

                             driver_request(s);
    //                             truck_info();
                             routeCreate();


                             fab.setOnClickListener(new View.OnClickListener() {
                                 @Override
                                 public void onClick(View view) {
                                     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Driver.this);
                                     alertDialogBuilder.setMessage("If you have completed your work then press Yes");
                                     alertDialogBuilder.setPositiveButton("Yes",
                                             new DialogInterface.OnClickListener() {
                                                 @Override
                                                 public void onClick(DialogInterface arg0, int arg1) {

    //                                                     complete_status();

                                                 }
                                             });

                                     alertDialogBuilder.setNegativeButton("No",
                                             new DialogInterface.OnClickListener() {
                                                 @Override
                                                 public void onClick(DialogInterface arg0, int arg1) {

                                                 }
                                             });

                                     //Showing the alert dialog
                                     AlertDialog alertDialog = alertDialogBuilder.create();
                                     alertDialog.show();



                                 }
                             });


                         }


    //
                       }
                   },
                   new Response.ErrorListener() {
                       @Override
                       public void onErrorResponse(VolleyError volleyError) {
                           //Dismissing the progress dialog
    //                        loading.dismiss();

                           //Showing toast
                           Toast.makeText(Driver.this, "error to connect", Toast.LENGTH_LONG).show();
                       }
                   }){
               @Override
               protected Map<String, String> getParams() throws AuthFailureError {





                   Map<String,String> params = new Hashtable<>();

                   params.put(Config.KEY_PHONE, str);



                   //returning parameters
                   return params;
               }
           };

           //Creating a Request Queue
           RequestQueue requestQueue = Volley.newRequestQueue(this);

           //Adding request to the queue
           requestQueue.add(stringRequest);

       }
      public void driver_request(String s) {


          JSONArray array = null;
          try {
              array = new JSONArray(s);

          for (int i = 0; i < array.length(); i++) {
              JSONObject json = null;
              try {
                  json = array.getJSONObject(i);



                  String area = json.getString("area");
                  String latitude = json.getString("latitude");
                  String longitude = json.getString("longitude");

                  final String truck_id = json.getString("truck_id");
                  for(int j=0;j<truck.size();j++)
                  {
                      String truck_value = truck.get(j);
                      if(truck_id.equals(truck_value))
                      {
                          map.addMarker(new MarkerOptions().position(truck_latlong.get(j)).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_truck)));
                          config.setLatLng(truck_latlong.get(j));
                      }
                  }

                  String disposial_id = json.getString("disposal_bin_id");
                  for (int k=0;k<disposail.size();k++)
                  {
                      String disposal_value = disposail.get(k);
                      if(disposial_id.equals(disposal_value))
                      {
                          map.addMarker(new MarkerOptions().position(disposail_latlong.get(k)).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_green_bin)));
                          config.setDisposail_latlng(disposail_latlong.get(k));
                      }
                  }


                  LatLng dest = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
                 maps =  map.addMarker(new MarkerOptions().position(dest).title("latlong").snippet(dest.toString()).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_red_bin1)));
                  arraymarker.add(maps);
                  map.moveCamera(CameraUpdateFactory.newLatLngZoom(dest, 14));
                  map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

                      @Override
                      public boolean onMarkerClick(Marker markers) {
                          for(int j=0;j<arraymarker.size();j++) {
                              if (markers.equals(arraymarker.get(j))) {
                                  Intent i = getIntent();

                                  final String str = i.getStringExtra("phone");
                                  final LatLng latLng = markers.getPosition();
                                  Double lat = latLng.latitude;
                                  Double lon = latLng.longitude;
                                  final String lats = lat.toString();
                                  final String lons = lon.toString();
                                  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Driver.this);
                                  alertDialogBuilder.setMessage("Confirm??");
                                  alertDialogBuilder.setPositiveButton("Yes",
                                          new DialogInterface.OnClickListener() {
                                              @Override
                                              public void onClick(DialogInterface arg0, int arg1) {


                                                  StringRequest stringRequest = new StringRequest(Request.Method.POST, COMPLETE_STATUS,
                                                          new Response.Listener<String>() {

                                                              @Override
                                                              public void onResponse(String response) {
                                                                  Toast.makeText(Driver.this, response, Toast.LENGTH_LONG).show();

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

                                                                  Toast.makeText(Driver.this, "error to connect", Toast.LENGTH_LONG).show();

                                                              }
                                                          }) {
                                                      @Override
                                                      protected Map<String, String> getParams() throws AuthFailureError {


                                                          Map<String, String> params = new Hashtable<>();

                                                          params.put(Config.KEY_PHONE, str);
                                                          params.put("lat", lats);
                                                          params.put("lon", lons);
                                                          params.put("truck",truck_id);



                                                          //returning parameters
                                                          return params;
                                                      }
                                                  };

                                                  //Creating a Request Queue
                                                  RequestQueue requestQueue = Volley.newRequestQueue(Driver.this);

                                                  //Adding request to the queue
                                                  requestQueue.add(stringRequest);


                                              }
                                          });

                                  alertDialogBuilder.setNegativeButton("No",
                                          new DialogInterface.OnClickListener() {
                                              @Override
                                              public void onClick(DialogInterface arg0, int arg1) {

                                              }
                                          });

                                  //Showing the alert dialog
                                  AlertDialog alertDialog = alertDialogBuilder.create();
                                  alertDialog.show();

                              }
                          }



                          return false;
                      }
                  });



                  marker(dest);


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


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

      }

    private void marker(LatLng point)
    {

        markerPoints.add(config.getLatLng());
        markerPoints.add(config.getDisposail_latlng());
        markerPoints.add(point);

        }
     public void routeCreate()
     {
         if (markerPoints.size() >=2) {
             origin = markerPoints.get(0);
             dest = markerPoints.get(1);

             String url = getDirectionsUrl(origin, dest);
             DownloadTask downloadTask = new DownloadTask();
             downloadTask.execute(url);

         }

     }

    public String getDirectionsUrl(LatLng origin, LatLng dest) {


        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
        String str_dest ="destination=" + dest.latitude + "," + dest.longitude;






        // Sensor enabled
        String sensor = "sensor=false";
        String waypoints = "";


        for(int  i=2;i<markerPoints.size();i++)
        {

            LatLng point = (LatLng)markerPoints.get(i);
            if(i==2)
                waypoints = "waypoints=optimize:true|";
            waypoints += point.latitude +"," +point.longitude + "|";
        }
            // Building the parameters to the web service
    //        String parameters = "waypoints=optimize:true|"+"&"+str_origin+"&"+str_dest+"&"+"alternatives=true"+"&"+sensor+"&"+"mode=driving"+"&"+"key=AIzaSyBM9huE4dOMUE_tBHNaibKd_8nOexVCnag";
        String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints+"&"+"mode=Driving"+"&"+"key=AIzaSyAAhlkzSggXQrO0ojRw4v_JXh0hNAhgAWE";
            // Output format
        String output = "json";

        // Building the url to the web service
      url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;


        return url;
    }

    /**
     * A method to download json data from url
     */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exception while", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, String> {

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            String data = "";

            try {
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask();

            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    /**
     * A class to parse the Google Places in JSON format
     */
    private class ParserTask extends AsyncTask<String, Integer,  List<List<HashMap<String, String>>>> {

        // Parsing the data in non-ui thread
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                PathJSONParser parser = new PathJSONParser();

                // Starts parsing data
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result)         {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            // Traversing through all the routes
            for (int i = 0; i < result.size(); i++) {
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> point = path.get(j);

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(3);
                //lineOptions.color(Color.RED);

                // Changing the color polyline according to the mode
                if (mMode == MODE_DRIVING)
                    lineOptions.color(Color.RED);
    //                else if (mMode == MODE_BICYCLING)
    //                    lineOptions.color(Color.GREEN);
                else if (mMode == MODE_WALKING)
                    lineOptions.color(Color.BLUE);
            }

            if (result.size() < 1) {
                Toast.makeText(getBaseContext(), "No Points",    Toast.LENGTH_SHORT).show();
                return;
            }

            // Drawing polyline in the Google Map for the i-th route
            map.addPolyline(lineOptions);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_driver, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {

           logout();
            return false;
        }

        return super.onOptionsItemSelected(item);
    }

    }
4

0 回答 0