【问题标题】:android null pointer exceptions in AsyncTask [closed]AsyncTask中的android空指针异常[关闭]
【发布时间】:2013-11-12 08:20:44
【问题描述】:

刚开始在android下写,遇到了不知道怎么解决的问题

PostData.java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;

import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

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

        @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;
            String stotalLatitude = String.valueOf(totalLatitude);
            double totalLongitude = longitudep;
            String stotalLongitude = String.valueOf(totalLongitude);
            // временная переменная для определения времени устройства
            Time nowTime = new Time();
            nowTime.setToNow();
            String snowTime = String.valueOf(nowTime);
            //берем информацию о юзере
                UP.LoadUserInfoFromFile();
                UP.LoadUserInfopassFromFile();
                String UserInfo = Teleport_user_profile_activity.UserLoginFile;
                String UserPass = Teleport_user_profile_activity.UserPassFile;
            //посылка данных на сервер
            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();
        } 

}
}

MainActivity.java

 R.id.menu_send_location_manual: {

             GPSdetermination();
             new PostData().execute();


            // postData(); - вызывает ошибку на реальном устройстве
             Toast.makeText(getApplicationContext(), R.string.location_send_manuall_toast, Toast.LENGTH_LONG).show();
        break;
    }

 public void GPSdetermination() {       
     // create class object
     gps = new GPSTracker(MainActivity.this);

     // check if GPS enabled        
     if(gps.canGetLocation()){

         double latitude = gps.getLatitude();
         double longitude = gps.getLongitude();

         // \n is for new line
         Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();   
     }else{
         // can't get location
         // GPS or Network is not enabled
         // Ask user to enable GPS/network in settings
         gps.showSettingsAlert();
     }

 } 

GPSTracker.java

    public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

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

// 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 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) {
}

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

当我尝试调用 PostData 时,此代码中出现错误 java.lang.NullPointerException

double latitudep = gps.getLatitude();
double longitudep = gps.getLongitude();

似乎无法弄清楚如何解决它。

【问题讨论】:

  • 你不能像这样创建一个新的 Service() 。你必须启动它。
  • 我不认为这真的值得谁给它 -1 投票

标签: android gps nullpointerexception postdata


【解决方案1】:

你已经在你的 AsyncTask 中声明了GPSTracker gps;,它似乎永远不会被初始化。换句话说,它是空的。因此,NullPointerException

我猜你需要一个 AsyncTask 的构造函数来设置它:

public PostData (GPSTracker gps) {
    this.gps = gps;
}

然后在MainActivity

new PostData(gps).execute();

AsyncTask 只是一个与其他任何类一样的类,具有成员变量,如果您想使用它们,则需要设置它们。

【讨论】:

  • 此方法有效且不会导致错误,但由于某种原因,只有值经度才会到达服务器。
  • 似乎这是一个不同的问题 :) 无论如何,在您的代码中,您似乎已经注释掉了那些 url 参数。
  • 如果我需要为 Teleport_user_profile_activity UP 创建一个构造函数,是否需要创建一个新的构造函数,或者我可以向其中添加数据?
【解决方案2】:

gpsnull 因为它没有被实例化。在doInBackground() 你可以实例化它

gps = new GPSTracker();

但是由于您的GPSTracker 构造函数需要Context,因此您必须向您的AsyncTas 添加一个接受Context 的构造函数

异步

pubic class PostData extends AsyncTask<Void, Void, Void> {
   Context mContext;

    MainActivity ma;
    Teleport_user_profile_activity UP;
    public PostData(Context c)
   {
         mContext = c;
   }

然后在doInBackground()

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

然后在 MainActivity 中像这样调用你的 AsyncTask

 R.id.menu_send_location_manual: {

         GPSdetermination();
         PostData task = new PostData(MainActivity.this);
         task.execute();
         new PostData().execute();

【讨论】:

    【解决方案3】:

    您的问题是 GPS 只能在常规线程中收听,例如 UI 线程,而不是 AsyncTaskdoInBackground() 方法。这与它需要Looper 才能正常工作有关。这是一个与您的问题非常相似的good post

    首先在onCreate 中获取您的GPS 数据,然后您可以将该数据作为可变参数传输到您的AsyncTask 并以这种方式在doInBackground 中使用它。

    【讨论】:

      猜你喜欢
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      相关资源
      最近更新 更多