2014-07-12 2 views
1

내 GPSTracker 클래스에서 위도를 가져 오는 라인에서 널 포인터 예외가 발생합니다. 어떤 아이디어? DDMS가 아닌 모바일 장치도 사용하고 있습니다. 나는 System.out.println(gps.getLatitude())을 수행했으며 실제로 null을 반환하지만 그 이유를 알 수는 없습니다. 내 휴대 전화에 GPS가 아니라 여기에nullpointer LocationManager getLatitude

켜져 나의 클래스 내 json으로

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

import org.apache.http.client.ClientProtocolException; 
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 = ""; 
     // constructor 
     public JSONParser() { 
     } 
     public JSONObject getJSONFromUrl(String myurl) { 
     // Making HTTP request 
     try { 
      // defaultHttpClient 
      URL url = new URL(myurl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(10000 /* milliseconds */); 
      conn.setConnectTimeout(15000 /* milliseconds */); 
      conn.setRequestMethod("GET"); 
      conn.setDoInput(true); 
      // Starts the query 
      conn.connect(); 
      int response = conn.getResponseCode(); 
      Log.d("HttpConnection", "The response is: " + response); 
      is = conn.getInputStream(); 
     } 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()); 
     } 
     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 
     // return JSON String 
     return jObj; 
     } 
    } 

내 주요 활동을 분석

public class GPSTracker extends Service implements LocationListener{ 

    private final Context mContext; 
    boolean isGPSEnabled = false; 
    boolean isNetworkEnabled = false; 
    boolean canGetLocation = false; 

    Location location; 
    Double latitude; 
    Double longitude; 

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 meters 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; //1 minute 
    protected LocationManager locationManager; 

    public GPSTracker (Context context){ 
     this.mContext = context; 
     getLocation(); 
    } 

    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 

      //getting GPS status 
      isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
      System.out.println(location.getLatitude()); 

      if(!isGPSEnabled && !isNetworkEnabled){ 
       //no network provider is enabled 
      } else{ 
       this.canGetLocation = true; 
       // First get location from Network provider 
       if (isNetworkEnabled){ 
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if(locationManager != null){ 
         location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if(location != null){ 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
       if (isGPSEnabled){ 
        if(location == null){ 
         locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if(locationManager != null){ 
          location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if(location != null){ 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 
     } catch (Exception e){ 
      e.printStackTrace(); 
     } 
     return location; 
    } 
    /** 
    * Function to get latitude 
    * */ 
    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
      System.out.println(latitude); 
      return 0.0; 
     } 
     System.out.println(latitude); 
     return latitude; 
    } 
    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
      System.out.println(longitude); 
      return 0.0; 
     } 
     return longitude; 
    } 

    /** 
    * Function to show setting alert dialog 
    */ 
    public void showSettingsAlert(){ 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

     //Setting Dialog Title 
     alertDialog.setTitle("GPS is settings"); 
     //Setting Dialog Message 
     alertDialog.setMessage("GPS is not enabled. Do you want to go to settings and enable GPS?"); 
     //Setting Icon to Dialog 
     //alertDialog.setIcon(R.drawable.delete); 
     //On Pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         mContext.startActivity(intent); 

      } 
     }); 
     //on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){ 
      public void onClick(DialogInterface dialog, int which){ 
       dialog.cancel(); 
      } 
     }); 
     //Showing alert message 
     alertDialog.show(); 
    } 

    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 
    @Override 
    public void onLocationChanged(Location location){  
    } 
    @Override 
    public void onProviderDisabled(String provider){   
    } 
    @Override 
    public void onProviderEnabled(String provider){  
    } 
    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras){   
    } 
    @Override 
    public IBinder onBind(Intent arg0){ 
     return null; 
    } 
} 

입니다

import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.widget.TextView; 


    public class MainActivity extends Activity { 

     public TextView weather = null; 
     public TextView summary = null; 
     public TextView icon = null; 
     public JSONObject currentTemperature = null; 
     public String temperature = ""; 
     public String weatherSummary = ""; 
     public String weatherIcon = ""; 
     public GPSTracker gps; 
     public double latitude = 0; 
     public double longitude = 0; 
     public String myUrl; 
     public TextView latitudeView = null; 
     public TextView longitudeView = null; 

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

      weather = (TextView) findViewById(R.id.weather); 
      summary = (TextView) findViewById(R.id.weather_summary); 
      icon = (TextView) findViewById(R.id.string_icon);   
      // we will using AsyncTask during parsing 
      new AsyncTaskParseJson().execute(); 

      gps = new GPSTracker(MainActivity.this); 
      myUrl = "https://api.forecast.io/forecast/5530508d3568e57848d53bf10cfade1f/35.9033,-79.0440"; 
       //gps.getLatitude() + "," + gps.getLongitude(); 

      double lat = gps.getLatitude(); 
      double longitude = gps.getLatitude(); 
      latitudeView.setText(String.valueOf(lat)); 
      longitudeView.setText(String.valueOf(longitude)); 
     } 

     /* public String convertLatitude(){ 
      latitude = gps.getLatitude(); 
      String latitude2 = Double.toString(latitude); 

      return latitude2; 
     }*/ 

     /* public String convertLongitude(){ 
      longitude = gps.getLongitude(); 
      String longitude2 = Double.toString(longitude); 

      return longitude2; 
     }*/ 

     //do in background method to call JSON Parser 
     public class AsyncTaskParseJson extends AsyncTask<String, String, String> { 
      final String TAG = "AsyncTaskParseJson.java";  

      @Override 
      protected String doInBackground(String... arg0){ 

       try { 


        // instantiate our json parser 
        JSONParser jParser = new JSONParser(); 
        // get json string from url 
        JSONObject json = jParser.getJSONFromUrl(myUrl); 


        JSONObject current = json.getJSONObject("currently"); 
        temperature = current.getString("temperature"); 

        weatherSummary = current.getString("summary"); 
        weatherIcon = current.getString("icon");    

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


      } 

      @Override 
      protected void onPostExecute(String strFromDoInBg) { 

       weather.setText(temperature); 
       summary.setText(weatherSummary); 
       icon.setText(weatherIcon); 

      } 
     } 
    } 

그리고 내 LogCat

07-12 15:13:31.373: W/System.err(32167): java.lang.NullPointerException 
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.GPSTracker.getLocation(GPSTracker.java:42) 
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.GPSTracker.<init>(GPSTracker.java:33) 
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.MainActivity.onCreate(MainActivity.java:39) 
07-12 15:13:31.378: W/System.err(32167): at android.app.Activity.performCreate(Activity.java:5451) 
07-12 15:13:31.378: W/System.err(32167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093) 
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377) 
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471) 
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.access$900(ActivityThread.java:175) 
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
07-12 15:13:31.378: W/System.err(32167): at android.os.Handler.dispatchMessage(Handler.java:102) 
07-12 15:13:31.378: W/System.err(32167): at android.os.Looper.loop(Looper.java:146) 
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.main(ActivityThread.java:5602) 
07-12 15:13:31.378: W/System.err(32167): at java.lang.reflect.Method.invokeNative(Native Method) 
07-12 15:13:31.378: W/System.err(32167): at java.lang.reflect.Method.invoke(Method.java:515) 
07-12 15:13:31.378: W/System.err(32167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
07-12 15:13:31.378: W/System.err(32167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
07-12 15:13:31.378: W/System.err(32167): at dalvik.system.NativeStart.main(Native Method) 
07-12 15:13:31.378: I/System.out(32167): null 
07-12 15:13:31.378: D/AndroidRuntime(32167): Shutting down VM 
07-12 15:13:31.378: W/dalvikvm(32167): threadid=1: thread exiting with uncaught exception (group=0x41886c08) 
07-12 15:13:31.378: W/System.err(32167): java.net.MalformedURLException 
07-12 15:13:31.378: W/System.err(32167): at java.net.URL.<init>(URL.java:152) 
07-12 15:13:31.378: W/System.err(32167): at java.net.URL.<init>(URL.java:125) 
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.JSONParser.getJSONFromUrl(JSONParser.java:29) 
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:76) 
07-12 15:13:31.378: E/AndroidRuntime(32167): FATAL EXCEPTION: main 
07-12 15:13:31.378: E/AndroidRuntime(32167): Process: rafa.weatherapp, PID: 32167 
07-12 15:13:31.378: E/AndroidRuntime(32167): java.lang.RuntimeException: Unable to start activity ComponentInfo{rafa.weatherapp/rafa.weatherapp.MainActivity}: java.lang.NullPointerException 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.access$900(ActivityThread.java:175) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.os.Handler.dispatchMessage(Handler.java:102) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.os.Looper.loop(Looper.java:146) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.main(ActivityThread.java:5602) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at java.lang.reflect.Method.invokeNative(Native Method) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at java.lang.reflect.Method.invoke(Method.java:515) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at dalvik.system.NativeStart.main(Native Method) 
07-12 15:13:31.378: E/AndroidRuntime(32167): Caused by: java.lang.NullPointerException 
07-12 15:13:31.378: E/AndroidRuntime(32167): at rafa.weatherapp.GPSTracker.getLatitude(GPSTracker.java:92) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at rafa.weatherapp.MainActivity.onCreate(MainActivity.java:43) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.Activity.performCreate(Activity.java:5451) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093) 
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377) 
07-12 15:13:31.378: E/AndroidRuntime(32167): ... 11 more 
07-12 15:13:31.383: W/ActivityManager(2431): Force finishing activity rafa.weatherapp/.MainActivity 
07-12 15:13:31.388: W/System.err(32167): at rafa.weatherapp.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:1) 
07-12 15:13:31.388: W/System.err(32167): at android.os.AsyncTask$2.call(AsyncTask.java:288) 
07-12 15:13:31.388: W/System.err(32167): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
07-12 15:13:31.388: W/System.err(32167): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
07-12 15:13:31.388: W/System.err(32167): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
07-12 15:13:31.388: W/System.err(32167): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
07-12 15:13:31.388: W/System.err(32167): at java.lang.Thread.run(Thread.java:841) 
07-12 15:13:31.388: E/Buffer Error(32167): Error converting result java.lang.NullPointerException: lock == null 
07-12 15:13:31.393: E/JSON Parser(32167): Error parsing data org.json.JSONException: End of input at character 0 of 
+0

매니페스트에 적절한 권한을 설정 했습니까? ACCESS_COARSE_LOCATION 또는 ACCESS_FINE_LOCATION – Naveed

+0

ACCESS_FINE_LOCATION – Rafa

+0

에 getLongitude도 null을 반환합니까? 또는 위도는? – reidisaki

답변

0

사용 권한의 위치가 매니페스트의 적절한 위치에 있는지 확인하십시오. 매니페스트의 내용을 게시하는 경우 도움이 될 수 있습니다.

0

대체 모든

System.out.println("") 

Log.d("", ""); 
0

교체하려고 :

gps = new GPSTracker(MainActivity.this); 

gps = new GPSTracker(getApplicationContext()); 
로 당신이 실제로 전에 위치를받은 적이 없다면도 getLastKnownLocation에

   locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("GPS Enabled", "GPS Enabled"); 
       if(locationManager != null){ 
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        if(location != null){ 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 

는 널 (null) 일 수 있습니다. 위도 = location.getLatitude() 호출을 onLocationChanged 메소드에 넣으면 비동기 적으로 정확한 위치를 얻을 수 있습니다.

관련 문제