致命异常:主要NullPointerException doIngBackground

时间:2013-11-14 22:06:01

标签: java android json google-maps google-maps-markers

使用json输出从数据库获取位置标记的应用程序。我可以在LogCat中看到json输出。 当我尝试使用AsyncTask来添加这些标记时,它自己依赖于数据库中有多少项,我得到了一个FC。

MapsActivity:

public class MapsActivity extends Activity {

     private MainMapFragement mapFragment;
     private HashMap<Marker, EventInfo> eventMarkerMap;
     private LatLng mPosition;
     Geocoder geocoder;
     String bestProvider;
     List<Address> user = null;
     double lat, lng;
     LatLng latLng;
     private ProgressDialog pDialog;
     JSONParser jParser = new JSONParser();
     ArrayList<HashMap<String, String>> productsList;
     private static String url_all_products = "http://000100023.host56.com/db_all.php";

     // JSON Node names
     private static final String TAG_SUCCESS = "success";
     private static final String TAG_PRODUCTS = "locations";
     private static final String TAG_PID = "id";
     private static final String TAG_NAME = "name";

     // products JSONArray
     JSONArray products = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        ActionBar abs = getActionBar();
        abs.setTitle(R.string.activity_title_map);
        abs.setDisplayHomeAsUpEnabled(true);

        mapFragment = new MainMapFragement();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.map, mapFragment);
        ft.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

     @Override
     protected void onStart() {
         super.onStart();
         new LoadAllLocations().execute();
         //setUpEventSpots();
         setCurrentLocationSpot();
     }

     private void setCurrentLocationSpot() {
         LocationManager lm = (LocationManager) MapsActivity.this.getSystemService(Context.LOCATION_SERVICE);

         Criteria criteria = new Criteria();
         bestProvider = lm.getBestProvider(criteria, false);
         Location location = lm.getLastKnownLocation(bestProvider);

         if (location == null){
             Toast.makeText(MapsActivity.this,"Location Not found",Toast.LENGTH_LONG).show();
          }else{
              geocoder = new Geocoder(MapsActivity.this);
              try {
                  user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                  lat=(double)user.get(0).getLatitude();
                  lng=(double)user.get(0).getLongitude();

                  mPosition = new LatLng(lat, lng);

                  GoogleMap mGap = ((MapFragment) getFragmentManager()
                          .findFragmentById(R.id.map)).getMap();

                  mGap.setMyLocationEnabled(true);
                  mGap.animateCamera(CameraUpdateFactory.newLatLngZoom(mPosition, 13));

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

     private void setUpEventSpots() {
          EventInfo firstEventInfo = new EventInfo(new LatLng(60.39341189999999, 5.322973699999999), "Right now - event", new Date(), null);
          //EventInfo secondEventInfo = new EventInfo(new LatLng(51.25, 4.15), "Future Event", new Date(1032, 5, 25), null);

          Marker firstMarker = mapFragment.placeMarker(firstEventInfo);
          //Marker secondMarker = mapFragment.placeMarker(secondEventInfo);

          eventMarkerMap = new HashMap<Marker, EventInfo>();

          eventMarkerMap.put(firstMarker, firstEventInfo);
          //eventMarkerMap.put(secondMarker, secondEventInfo);

          /*mapFragment.getMap().setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
          @Override
          public void onInfoWindowClick(Marker marker) {
              EventInfo eventInfo = eventMarkerMap.get(marker);
              Toast.makeText(getBaseContext(),
              "The date of " + eventInfo.getName() + " is " + eventInfo.getSomeDate().toLocaleString(),
              Toast.LENGTH_LONG).show();
          }*
          });*/
     }

     class LoadAllLocations extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                //pDialog = new ProgressDialog(MapsActivity.this);
                //pDialog.setMessage("Loading locations. Please wait...");
                //pDialog.setIndeterminate(false);
                //pDialog.setCancelable(false);
                //pDialog.show();

            }



            /**
             * getting All products from url
             * */
            protected String doInBackground(String... args) {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

                // Check your log cat for JSON reponse
                Log.d("All Products: ", json.toString());

                try {
                    // Checking for SUCCESS TAG
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // products found
                        // Getting Array of Products
                        products = json.getJSONArray(TAG_PRODUCTS);

                        // looping through All Products
                        for (int i = 0; i < products.length(); i++) {
                            JSONObject c = products.getJSONObject(i);

                            // Storing each json item in variable
                            String id = c.getString(TAG_PID);
                            String name = c.getString(TAG_NAME);

                            // creating new HashMap
                            //HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            //map.put(TAG_PID, id);
                            //map.put(TAG_NAME, name);

                            // adding HashList to ArrayList
                            //productsList.add(map);
                        }
                    } else {
                        // no products found
                        // Launch Add New product Activity
                        //Intent i = new Intent(getApplicationContext(),
                          //      NewProductActivity.class);
                        // Closing all previous activities
                        //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //startActivity(i);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }

            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all products
                //pDialog.dismiss();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        /**
                         * Updating parsed JSON data into ListView
                         * */

                        for (int i = 0; i < products.length(); i++) {

                            try {
                                JSONObject c = products.getJSONObject(i);
                                String id = c.getString(TAG_PID);
                                String name = c.getString(TAG_NAME);
                                String lat = c.getString("lat");
                                String lng = c.getString("lng");
                                Double l1 = latLng.latitude;
                                Double l2 = latLng.longitude;
                                l1 = Double.parseDouble(lat);
                                l2 = Double.parseDouble(lng);
                                //Log.d("LOGTAG", id);
                                EventInfo eventInfo = new EventInfo(new LatLng(l1, l2), name, new Date(), null);
                                Marker mMarker = mapFragment.placeMarker(eventInfo);
                                eventMarkerMap = new HashMap<Marker, EventInfo>();
                                eventMarkerMap.put(mMarker, eventInfo);
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }


                    }
                });


            }
     }
}

LogCat:

11-14 23:01:11.448: E/AndroidRuntime(6593): FATAL EXCEPTION: main
11-14 23:01:11.448: E/AndroidRuntime(6593): Process: com.spxc.nightclubratings, PID: 6593
11-14 23:01:11.448: E/AndroidRuntime(6593): java.lang.NullPointerException
11-14 23:01:11.448: E/AndroidRuntime(6593):     at com.spxc.nightclubratings.MapsActivity$LoadAllLocations$1.run(MapsActivity.java:239)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at android.app.Activity.runOnUiThread(Activity.java:4712)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at com.spxc.nightclubratings.MapsActivity$LoadAllLocations.onPostExecute(MapsActivity.java:225)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at com.spxc.nightclubratings.MapsActivity$LoadAllLocations.onPostExecute(MapsActivity.java:1)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at android.os.AsyncTask.finish(AsyncTask.java:632)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at android.os.Handler.dispatchMessage(Handler.java:102)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at android.os.Looper.loop(Looper.java:137)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at android.app.ActivityThread.main(ActivityThread.java:4998)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at java.lang.reflect.Method.invokeNative(Native Method)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at java.lang.reflect.Method.invoke(Method.java:515)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-14 23:01:11.448: E/AndroidRuntime(6593):     at dalvik.system.NativeStart.main(Native Method)

为什么我不能让这个工作?问题出现在onPostExecute方法中,如上所示。

非常感谢任何帮助!感谢

1 个答案:

答案 0 :(得分:0)

我通过做一些调整来实现它:

String lat = c.getString("lat");
                                String lng = c.getString("lng");
                                Double l1 = latLng.latitude;
                                    Double l2 = latLng.longitude;
                                l1 = Double.parseDouble(lat);
                                l2 = Double.parseDouble(lng);
                                //Log.d("LOGTAG", id);
                                EventInfo eventInfo = new EventInfo(new LatLng(l1, l2), name, new Date(), null);
                                Marker mMarker = mapFragment.placeMarker(eventInfo);
                                eventMarkerMap = new HashMap<Marker, EventInfo>();
                                eventMarkerMap.put(mMarker, eventInfo);

TO:

String lat = c.getString("lat");
                                String lng = c.getString("lng");
                                Double l1;
                                Double l2;
                                l1 = Double.parseDouble(lat);
                                l2 = Double.parseDouble(lng);
                                //Log.d("LOGTAG", id);
                                EventInfo eventInfo = new EventInfo(new LatLng(l1, l2), name, new Date(), null);
                                Marker mMarker = mapFragment.placeMarker(eventInfo);
                                eventMarkerMap = new HashMap<Marker, EventInfo>();
                                eventMarkerMap.put(mMarker, eventInfo);

这只是Double的l1和l2,这就是造成这个问题的原因!