Android 3.0中Oncreate中的NullPointernullException

时间:2014-05-23 00:59:36

标签: android nullpointerexception version

我收到NullPointerException,这是我的日志:

05-23 00:42:49.384: E/AndroidRuntime(408): FATAL EXCEPTION: main
05-23 00:42:49.384: E/AndroidRuntime(408): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apparkingit/com.example.apparkingit.MainActivity}: java.lang.NullPointerException
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.app.ActivityThread.access$1500(ActivityThread.java:123)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.os.Looper.loop(Looper.java:126)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.app.ActivityThread.main(ActivityThread.java:3997)
05-23 00:42:49.384: E/AndroidRuntime(408):  at java.lang.reflect.Method.invokeNative(Native Method)
05-23 00:42:49.384: E/AndroidRuntime(408):  at java.lang.reflect.Method.invoke(Method.java:491)
05-23 00:42:49.384: E/AndroidRuntime(408):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
05-23 00:42:49.384: E/AndroidRuntime(408):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
05-23 00:42:49.384: E/AndroidRuntime(408):  at dalvik.system.NativeStart.main(Native Method)
05-23 00:42:49.384: E/AndroidRuntime(408): Caused by: java.lang.NullPointerException
05-23 00:42:49.384: E/AndroidRuntime(408):  at com.example.apparkingit.MainActivity.onCreate(MainActivity.java:83)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
05-23 00:42:49.384: E/AndroidRuntime(408):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)
05-23 00:42:49.384: E/AndroidRuntime(408):  ... 11 more

这是我的MainActivity代码:

public class MainActivity extends FragmentActivity  {

GoogleMap googleMap;

MarkerOptions markerOptions;
LatLng latLng;
private ProgressDialog pDialog;
//private ListView navList;

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

    // Getting reference to SupportMapFragment
    SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
   // Getting reference to btn_find of the layout activity_main

    Button btn_find = (Button) findViewById(R.id.btn_find);
    OnClickListener findClickListener = new OnClickListener() {         
        @Override
        public void onClick(View v) {
            // Getting reference to EditText to get the user input location
            EditText etLocation = (EditText) findViewById(R.id.et_location);

            // Getting user input location
            String location = etLocation.getText().toString();

            if(location!=null && !location.equals("")){
                new GeocoderTask().execute(location);
            }
        }
    };
    btn_find.setOnClickListener(findClickListener); 

    // Creating GoogleMap from SupportMapFragment
    googleMap = fragment.getMap();

    // Enabling MyLocation button for the Google Map
    googleMap.setMyLocationEnabled(true);

    double lat= -33.4520839;
     double lng = -70.6585019;
     LatLng ll = new LatLng(lat, lng);
     googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 10));

    googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        Integer sw=1;
        public void onMyLocationChange(Location pos) {
            // TODO Auto-generated method stub

             if (sw==1){
            // Extraigo la Lat y Lon del Listener


            final double latO2 = pos.getLatitude();

             final double lonO2 = pos.getLongitude();

            sw=0;

             }    

        }
    });

    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker marker) {
            // TODO Auto-generated method stub

            // Obtenemos la posicion del marcador en tipo LatLng 
            String snip = marker.getSnippet();
            Location Origen = googleMap.getMyLocation();
            double Origenlat = Origen.getLatitude();
            double Origenlng = Origen.getLongitude();
            LatLng LatLng = marker.getPosition();
            double latt = LatLng.latitude;
            double lngg = LatLng.longitude;

            String user;
            String lat = Double.toString(latt);
            String lng = Double.toString(lngg);
            String latO = Double.toString(Origenlat);
            String lngO = Double.toString(Origenlng);
            Bundle bundle = getIntent().getExtras();
             user  = bundle.getString("user");//usuario


            String title = marker.getTitle();

            if (snip.equalsIgnoreCase("Estacionamiento")==true){
            Intent i = new Intent(MainActivity.this,infowindow.class);
            i.putExtra("latO", latO);
            i.putExtra("lngO", lngO);
            i.putExtra("title", title);
            i.putExtra("lat", lat);
            i.putExtra("lng", lng);
            i.putExtra("user", user);

            Log.e("Variable a pasar",lat);
            Log.e("Variable a pasar",lng);
            Log.e("Variable a pasar",title);
            Log.e("Variable a pasar",latO);
            Log.e("Variable a pasar",lngO);
            startActivity(i);
            }
            if (snip.equalsIgnoreCase("Bencinera")==true){
                Intent i = new Intent(MainActivity.this,infowindowben.class);
                i.putExtra("latO", latO);
                i.putExtra("lngO", lngO);
                i.putExtra("title", title);
                i.putExtra("lat", lat);
                i.putExtra("lng", lng);

                Log.e("Variable a pasar",lat);
                Log.e("Variable a pasar",lng);
                Log.e("Variable a pasar",title);
                Log.e("Variable a pasar",latO);
                Log.e("Variable a pasar",lngO);
                startActivity(i);
                }


        //  startActivity(new Intent(MainActivity.this,infowindow.class)); 
        }
    });

    // Setting OnClickEvent listener for the GoogleMap
    //mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
        //@Override
        //public void onMapClick(LatLng latlng) {
        //  addMarker(latlng);
        //  sendToServer(latlng);
        //}
//  });

    // Starting locations retrieve task
    new RetrieveTask().execute();

    googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        Integer sw=1;
        public void onMyLocationChange(Location pos) {
            // TODO Auto-generated method stub

             if (sw==1){
            // Extraigo la Lat y Lon del Listener
            double lat = pos.getLatitude();
            double lon = pos.getLongitude();

            LatLng Punto = new LatLng(lat,lon);
            MarkerOptions mp = new MarkerOptions();

            mp.position(new LatLng(lat, lon));

            mp.title("my position");
            mp.icon(BitmapDescriptorFactory.fromResource(R.drawable.markergeolocx));

            googleMap.addMarker(mp);
            // Muevo la cámara a mi posición
            CameraUpdate cam = CameraUpdateFactory.newLatLngZoom(Punto, 10);

            sw=0;

             } 
        }
    });

    final AlertDialog alert = null;
      final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

      if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
          AlertNoGps();}
      }

      private void AlertNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("El sistema GPS debe estar activado para que funcione la App correctamente, ¿Desea activarlo?")
               .setCancelable(false)
               .setPositiveButton("Si", new DialogInterface.OnClickListener() {
                   public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                       startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();

}

// FIN DEL ONCREATE

// Adding marker on the GoogleMaps
private void addMarker(LatLng latlng, String title , String categoria) {
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latlng);

    markerOptions.title(title);
    markerOptions.snippet(categoria);
    if (categoria.equalsIgnoreCase("Estacionamiento")==true){
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markerestx));
    }
    if (categoria.equalsIgnoreCase("Bencinera")==true){
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markerbenx));
    }
    if (categoria.equalsIgnoreCase("Bicicleta")==true){
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markerbicix));
    }
    if (categoria.equalsIgnoreCase("Servipag")==true){
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markersenx));
    }
    googleMap.addMarker(markerOptions);
}

// Invoking background thread to store the touched location in Remove MySQL server
////    new SaveTask().execute(latlng);
//}

// Background task to retrieve locations from remote mysql server
private class RetrieveTask extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {
        String strUrl = "http://biosis1.comlu.com/retrieve4.php";               
        URL url = null;
        StringBuffer sb = new StringBuffer();
        try {
            url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream iStream = connection.getInputStream();              
            BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));         
            String line = "";               
            while( (line = reader.readLine()) != null){
                sb.append(line);
            }

            reader.close();
            iStream.close();                            

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }       
        return sb.toString();
    }

    @Override
    protected void onPostExecute(String result) {           
        super.onPostExecute(result);
        new ParserTask().execute(result);
    }

}

// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
    protected void onPreExecute() {
        //para el progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Cargando Mapa...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected List<HashMap<String,String>> doInBackground(String... params) {
        MarkerJSONParser markerParser = new MarkerJSONParser();
        JSONObject json = null;
        try {
            json = new JSONObject(params[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        List<HashMap<String, String>> markersList = markerParser.parse(json);
        return markersList;
    }

    @Override
    protected void onPostExecute(List<HashMap<String, String>> result) {

        try{
        for(int i=0; i<result.size();i++){
            HashMap<String, String> marker = result.get(i);
            String categoria = marker.get("categoria");
            LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
            String title = marker.get("title");
            Log.e("Valor",categoria);


            addMarker(latlng,title,categoria);

        }
        pDialog.dismiss();
        Toast.makeText(getBaseContext(), "Mapa cargado correctamente!", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show()  ;
        }
    }
}

//@Override
//public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
//().inflate(R.menu.main, menu);
//  return true;
//}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{

    @Override
    protected List<Address> doInBackground(String... locationName) {
        // Creating an instance of Geocoder class
        Geocoder geocoder = new Geocoder(getBaseContext());
        List<Address> addresses = null;

        try {
            // Getting a maximum of 3 Address that matches the input text
            addresses = geocoder.getFromLocationName(locationName[0], 3);
        } catch (IOException e) {
            e.printStackTrace();
        }           
        return addresses;
    }


    @Override
    protected void onPostExecute(List<Address> addresses) {         

        if(addresses==null || addresses.size()==0){
            Toast.makeText(getBaseContext(), "No se ha encontrado direccion", Toast.LENGTH_SHORT).show();
        }

        // Clears all the existing markers on the map
        //googleMap.clear();

        // Adding Markers on Google Map for each matching address
        for(int i=0;i<addresses.size();i++){                

            Address address = (Address) addresses.get(i);

            // Creating an instance of GeoPoint, to display in Google Map
            latLng = new LatLng(address.getLatitude(), address.getLongitude());

            String addressText = String.format("%s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                    address.getCountryName());

            markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

            markerOptions.title(addressText);

          //  googleMap.addMarker(markerOptions);



            // Locate the first location
            if(i==0)                        
                googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15)); 

        }           
    }   

}

  }

这是我的XML

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity" >
   <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >      

    <Button 
        android:id="@+id/btn_find"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="@string/str_btn_find" 
        android:layout_alignParentRight="true" />

    <EditText
        android:id="@+id/et_location"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:inputType="text" 
        android:hint="@string/hnt_et_location"
        android:layout_toLeftOf="@id/btn_find" />

</LinearLayout>

<fragment 

    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    class="com.google.android.gms.maps.SupportMapFragment" />

</LinearLayout>

问题是该应用程序刚刚与Android版本&gt; 4.0崩溃,我真的不知道我该怎么做:(

这是我的第一个问题,所以我很抱歉代码的错误结构。

谢谢!

0 个答案:

没有答案