0

在我的应用程序中,我使用负责定位的服务和将位置数据和其他数据传输到服务器的 AsynсTask。在 AsyncTask 中,我使用了一个从应用程序文件中读取数据的函数。PostData.java

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

读取数据.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 = new 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)
4

2 回答 2

0

我的猜测是您的 Context 为空,并且由于这一行而引发异常:

FileInputStream fIn = rdContext.openFileInput(FILENAME);

您是否设置了调试点以查看 rdContext 实际上是否为空?

于 2013-06-10T19:11:25.943 回答
0

在服务中更改以下代码。

你写

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

将其更改为

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

我认为,您的RD = new ReadData(rdContext);代码没有rdContext. 所以改变我的代码,并尝试运行你的代码。

于 2013-06-10T19:07:26.987 回答