bonjour ,
Je suis débutante dans le développement android et je souhaite votre aide.Quand je lance l'application, le compilateur ne donne aucune erreur mais le logcat affiche"java.lang.NullPointerException".
voici le logcat:
03-15 13:25:11.309: D/dalvikvm(952): GC_CONCURRENT freed 161K, 11% free 2635K/2944K, paused 7ms+6ms, total 272ms 03-15 13:25:11.320: W/CursorWrapperInner(952): Cursor finalized without prior close() 03-15 13:25:11.330: W/CursorWrapperInner(952): Cursor finalized without prior close() 03-15 13:25:12.089: I/Maps.MyLocationOverlay(952): Request updates from gps 03-15 13:25:12.099: D/AndroidRuntime(952): Shutting down VM 03-15 13:25:12.099: W/dalvikvm(952): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 03-15 13:25:12.149: E/AndroidRuntime(952): FATAL EXCEPTION: main 03-15 13:25:12.149: E/AndroidRuntime(952): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.recherche_restaurant/com.example.recherche_restaurant.MainActivity}: java.lang.NullPointerException 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.ActivityThread.access$600(ActivityThread.java:141) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.os.Handler.dispatchMessage(Handler.java:99) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.os.Looper.loop(Looper.java:137) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.ActivityThread.main(ActivityThread.java:5041) 03-15 13:25:12.149: E/AndroidRuntime(952): at java.lang.reflect.Method.invokeNative(Native Method) 03-15 13:25:12.149: E/AndroidRuntime(952): at java.lang.reflect.Method.invoke(Method.java:511) 03-15 13:25:12.149: E/AndroidRuntime(952): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 03-15 13:25:12.149: E/AndroidRuntime(952): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 03-15 13:25:12.149: E/AndroidRuntime(952): at dalvik.system.NativeStart.main(Native Method) 03-15 13:25:12.149: E/AndroidRuntime(952): Caused by: java.lang.NullPointerException 03-15 13:25:12.149: E/AndroidRuntime(952): at com.example.recherche_restaurant.MainActivity.onCreate(MainActivity.java:98) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.Activity.performCreate(Activity.java:5104) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 03-15 13:25:12.149: E/AndroidRuntime(952): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 03-15 13:25:12.149: E/AndroidRuntime(952): ... 11 more 03-15 13:30:12.389: I/Process(952): Sending signal. PID: 952 SIG: 9
les classes java :
MainActivity.java :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package com.example.recherche_restaurant; import java.io.InputStream; import java.util.List; import org.apache.http.HttpEntity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.example.recherche_restaurant.JsonParser; import com.example.recherche_restaurant.ListItimizedOverlay; import com.example.recherche_restaurant.R; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; import android.content.Context; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.view.KeyEvent; import android.widget.Toast; public class MainActivity extends MapActivity implements LocationListener { static String lg =""; static String lt =""; private static String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+lg+","+lt+"&radius=500&types=food&name=harbour&sensor=true&key=AIzaSyDxms7wMJorpD9LZVRL9OiozgV1D9wJKxo"; private static final String TAG_results = "results"; private static final String TAG_geometry = "geometry"; private static final String TAG_location = "location"; private static final String TAG_lat = "lat"; private static final String TAG_lng = "lng"; JSONArray contacts = null; private MapView mapView = null; private LocationManager lm = null; private static double lat = 0; private static double lng = 0; private MapController mc = null; private MyLocationOverlay myLocation = null; HttpEntity httpEntity; static InputStream is = null; static JSONObject jObj = null; static String json = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mapView = (MapView) this.findViewById(R.id.mapView); mapView.setBuiltInZoomControls(true); lm = (LocationManager) this.getSystemService(LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, this); mc = mapView.getController(); mc.setZoom(19); myLocation = new MyLocationOverlay(getApplicationContext(), mapView); myLocation.runOnFirstFix(new Runnable() { public void run() { mc.animateTo(myLocation.getMyLocation()); mc.setZoom(17); } }); mapView.getOverlays().add(myLocation); myLocation.enableMyLocation(); lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); double longitude = l.getLongitude(); double latitude = l.getLatitude(); lg=Double.toString(longitude); lt=Double.toString(latitude); getData(); } private void getData() { Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher); final ListItimizedOverlay itemizedoverlay = new ListItimizedOverlay(drawable,this); new AsyncTask<Void, Void, JSONObject>(){ @Override protected JSONObject doInBackground(Void... params) { // instancier la classe JsonParser JsonParser jParser = new JsonParser (); // récupérer le JSONObject à partir de lurl du fichier employes.json JSONObject json = jParser.getJSONFromUrl(url); return json; }; protected void onPostExecute(JSONObject json) { try { // récupérer la liste de tous les employés JSONArray results = json.getJSONArray(TAG_results); // parcourir toute la liste des employés for(int i = 0; i < results.length(); i++){ // récupérer un employé de type JSONObject JSONObject emp = results.getJSONObject(i); // récupérer le JSONObject phone qui contient deux items JSONObject geometry = emp.getJSONObject(TAG_geometry); JSONObject location = geometry.getJSONObject(TAG_location); String latitude = location.getString(TAG_lat); String longitude= location.getString(TAG_lng); double b = Double.parseDouble(latitude); double c = Double.parseDouble(longitude); GeoPoint geoPoint = new GeoPoint((int) (c* 1E6) , (int)(b* 1E6)); OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello from", "Tahiti"); itemizedoverlay.addOverlayItem(overlayitem); List<Overlay> mapOverlays = mapView.getOverlays(); mapOverlays.add(itemizedoverlay); } } catch(JSONException e) { e.printStackTrace(); } }; }.execute(); } @Override protected void onResume() { super.onResume(); myLocation.enableMyLocation(); myLocation.enableCompass(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_S) { mapView.setSatellite(!mapView.isSatellite()); return true; } return super.onKeyDown(keyCode, event); } @Override public void onLocationChanged(Location location) { lat = location.getLatitude(); lng = location.getLongitude(); Toast.makeText( getBaseContext(), "Location change to : Latitude = " + lat + " Longitude = " + lng, Toast.LENGTH_SHORT).show(); GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); mc.animateTo(p); mc.setCenter(p); } @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } }
JsonParser.java :
ListItimizedOverlay.java :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2 package com.example.recherche_restaurant; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JsonParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // Constructeur de notre classe public JsonParser() { } public JSONObject getJSONFromUrl(String url) { // début de la requête http try { // faire appel à defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // convertir le résultat qui est sous format d'un String en un JSONObject try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // retourner un JSONObject return jObj; } }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2 package com.example.recherche_restaurant; import java.util.ArrayList; import android.app.AlertDialog; import android.content.Context; import android.graphics.drawable.Drawable; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.OverlayItem; public class ListItimizedOverlay extends ItemizedOverlay<OverlayItem> { private Context context; private ArrayList<OverlayItem> arrayListOverlayItem = new ArrayList<OverlayItem>(); public ListItimizedOverlay(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); // TODO Auto-generated constructor stub } public ListItimizedOverlay(Drawable defaultMarker, Context pContext) { super(boundCenterBottom(defaultMarker)); this.context = pContext; } @Override protected OverlayItem createItem(int i) { // TODO Auto-generated method stub return arrayListOverlayItem.get(i); } @Override public int size() { // TODO Auto-generated method stub return arrayListOverlayItem.size(); } @Override protected boolean onTap(int index) { OverlayItem item = arrayListOverlayItem.get(index); AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle(item.getTitle()); dialog.setMessage(item.getSnippet()); dialog.show(); return true; } public void addOverlayItem(OverlayItem overlay) { arrayListOverlayItem.add(overlay); populate(); } }
le manifest :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.recherche_restaurant" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <uses-library android:name="com.google.android.maps" /> <activity android:name="com.example.recherche_restaurant.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Avez vous des idées ? Merci d'avance.
Partager