2013-06-10 2 views
0

내 응용 프로그램에서 위치 데이터 및 다른 데이터를 서버로 전송하는 위치 지정 및 AsynnTask를 담당하는 서비스를 사용합니다. AsyncTask에서는 응용 프로그램 파일의 데이터를 읽는 함수를 사용합니다. PostData.javaNull 포인트 예외 서비스

class PostData extends AsyncTask<Void, Void, Void> { 
// GPSTracker class 
    GPSTracker gps; 
    Context rdContext; 
//определяем переменную главного активити 
    MainActivity ma; 
    Teleport_user_profile_activity UP; 
    ReadData RD; 

    public PostData (GPSTracker gps, ReadData RD, Context c) { 
     this.gps = gps; 
     this.RD = RD; 
     rdContext = c; 
    } 


    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     // do stuff before posting data 
     super.onPreExecute(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // TODO Auto-generated method stub 
     postData(); 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     // TODO Auto-generated method stub 
     // do stuff after posting data 
     super.onPostExecute(result); 
    } 

    public void postData() { 
     // TODO Auto-generated method stub 
     // Create a new HttpClient and Post Header 
     //переводим значение double в стринг 
     double latitudep = gps.getLatitude(); 
     double longitudep = gps.getLongitude(); 
     double totalLatitude = latitudep; 
     double totalLongitude = longitudep; 
     String stotalLatitude = String.valueOf(totalLatitude); 
     String stotalLongitude = String.valueOf(totalLongitude); 
     // временная переменная для определения времени устройства 
     Time nowTime = new Time(); 
     nowTime.setToNow(); 
     String snowTime = String.valueOf(nowTime); 
     //берем информацию о юзере 
     RD = new ReadData(rdContext); 
     String UserInfo = RD.readSavedDataLogin(); 
     String UserPass = RD.readSavedDataPass(); 
     //посылка данных на сервер 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://myheart.pp.ua/Android_in.php"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); 

     nameValuePairs.add(new BasicNameValuePair("latitude", stotalLatitude)); 
     nameValuePairs.add(new BasicNameValuePair("longitude", stotalLongitude)); 
     nameValuePairs.add(new BasicNameValuePair("Android_device_time", snowTime)); 
     nameValuePairs.add(new BasicNameValuePair("user_info", UserInfo)); 
     nameValuePairs.add(new BasicNameValuePair("user_pass", UserPass)); 
     nameValuePairs.add(new BasicNameValuePair("separator", "______________________________________")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     httpclient.execute(httppost); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } catch (NullPointerException e) { 
     e.printStackTrace(); 
    } 

GPSTracker.java

public class GPSTracker extends Service implements LocationListener { 

    private final Context mContext; 


    //определяем переменную главного активити 
     MainActivity ma; 

     GPSTracker gps; 
     Teleport_user_profile_activity UP; 
     ReadData RD; 
     PostData PD; 
     Context rdContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

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

    public static String UserLoginFile; 
    public static String UserPassFile; 
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    // Функция для определения местоположения 
    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       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 GPS Enabled get lat/long using GPS Services 
       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; 
    } 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    /** 
    * Stop using GPS listener 
    * Calling this function will stop using GPS in your app 
    * */ 
    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(GPSTracker.this); 
     }  
    } 

    /** 
    * Function to get latitude 
    * */ 
    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 
    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

    /** 
    * Function to check GPS/wifi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    /** 
    * Function to show settings alert dialog 
    * On pressing Settings button will lauch Settings Options 
    * */ 
    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 menu?"); 

     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
      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(); 
    } 



    //события которые происходят если позиция поменялась 
    @Override 
    public void onLocationChanged(Location location) { 
     //Отправка местоположения если позиция изменилась 10_06_2013 
     GPSTracker gps = new GPSTracker(this); // работает 
     ReadData RD = new ReadData(rdContext); //не работает вызывает ошибку 
     new PostData(gps, RD, getBaseContext()).execute(); // работает 


    } 

    @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; 
    } 

ReadData.java

public class ReadData { 
    private final Context rdContext; 
// private final Context pContext; 

    public ReadData(Context context) { 
     this.rdContext = context; 
//  this.pContext = context; 
     readSavedDataLogin (); 
     readSavedDataPass (); 
    } 

    public String readSavedDataLogin () { 
     String datax = "" ; 
     String FILENAME = "TeleportSAASUser.txt"; 
     if(datax != null){ 
     try { 
      FileInputStream fIn = rdContext.openFileInput(FILENAME); 
      InputStreamReader isr = new InputStreamReader (fIn) ; 
      BufferedReader buffreader = new BufferedReader (isr) ; 

      String readString = buffreader.readLine () ; 
      while (readString != null) { 
       datax = datax + readString ; 
       readString = buffreader.readLine () ; 
      } 

      isr.close () ; 
     } catch (IOException ioe) { 
      ioe.printStackTrace () ; 
     } 
     } 
     return datax ; 
    } 
    public String readSavedDataPass () { 
     String datax = "" ; 
     String FILENAME = "TeleportSAASPass.txt"; 
     if(datax != null){ 
     try { 
      FileInputStream fIn = rdContext.openFileInput (FILENAME) ; 
      InputStreamReader isr = new InputStreamReader (fIn) ; 
      BufferedReader buffreader = new BufferedReader (isr) ; 

      String readString = buffreader.readLine () ; 
      while (readString != null) { 
       datax = datax + readString ; 
       readString = buffreader.readLine () ; 
      } 

      isr.close () ; 
     } catch (IOException ioe) { 
      ioe.printStackTrace () ; 
     } 
     } 
     return datax ; 
    } 

하지만 onLocationChanged에 오류 NPE가 -가 ReadData RD = 새가 ReadData (rdContext); 어딘가 변수를 초기화하지 않았지만 어디에서 이해할 수 없는지 이해합니다. 이 문제를 해결하도록 도와주세요.

06-10 18:56:56.671: E/AndroidRuntime(2801): FATAL EXCEPTION: main 
06-10 18:56:56.671: E/AndroidRuntime(2801): java.lang.NullPointerException 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at com.teleport.saas.ReadData.readSavedDataLogin(ReadData.java:26) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at com.teleport.saas.ReadData.<init>(ReadData.java:17) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at com.teleport.saas.GPSTracker.onLocationChanged(GPSTracker.java:203) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:237) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:170) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:186) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at android.os.Handler.dispatchMessage(Handler.java:99) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at android.os.Looper.loop(Looper.java:137) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at android.app.ActivityThread.main(ActivityThread.java:4745) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at java.lang.reflect.Method.invokeNative(Native Method) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at java.lang.reflect.Method.invoke(Method.java:511) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
06-10 18:56:56.671: E/AndroidRuntime(2801):  at dalvik.system.NativeStart.main(Native Method) 
+0

이는 PostData의 행 번호 65입니까? –

+0

RD = 새로운 ReadData (rdContext); 새 로그 파일을 게시했습니다. 이 메서드는 서버에 완벽하게 작동하지만 완벽하게 작동하지만 onLocationChanged 서비스를 사용하려면 NPE – Alex

답변

0

다음 코드를 변경하십시오.

당신은

new PostData(gps, RD, mContext).execute(); 

내 생각, 당신의 RD = new ReadData(rdContext); 코드에

new PostData(gps, RD, getBaseContext()).execute(); 

변경이 쓴, rdContext이 없습니다. 그래서 내 코드로 변경하고 코드를 실행하십시오.

FileInputStream fIn = rdContext.openFileInput(FILENAME); 

당신이 rdContext이 사실 널 (null)에 있는지 확인하기 위해 디버그 포인트를 설정 :

+1

이 코드는 오류를 발생시키지 않지만 위도와 경도는 어떤 이유로 든 0이됩니다. – Alex

0

내 생각 엔 당신의 컨텍스트가 null 때문에이 라인의 예외를 던지고 있다는 점이다?