从2个与用户位置一起使用的AsyncTask中,只有一个适用于Java& Android的

时间:2016-06-03 17:22:23

标签: java android json android-asynctask

我有两个与当前用户位置数据一起使用的AsyncTask,第一个没有任何问题,但第二个,停止应用程序工作,应用程序将崩溃。

请注意,只是在真实设备中,第一个任务才有效,但在虚拟设备中,即使是第一个任务也无效:|

mainActivity的代码:

public class MainActivity extends AppCompatActivity {
Button btnShowLocation;
public static TextView txtTemperature;
public static TextView txtWindSpeed;
public static TextView txtHumidity;
public static TextView txtSummary;
public static TextView txtCityName;
GpsTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnShowLocation = (Button)findViewById(R.id.btnupdate);
    txtTemperature = (TextView) findViewById(R.id.txtTemperature);
    txtWindSpeed = (TextView) findViewById(R.id.txtWindSpeed);
    txtHumidity = (TextView) findViewById(R.id.txthumidity);
    txtSummary = (TextView) findViewById(R.id.txtSummary);
    txtSummary = (TextView) findViewById(R.id.txtCityName);
    //find geoLocation
    btnShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gps = new GpsTracker(MainActivity.this);

            if(gps.canGetLocation()){
                Double lat = gps.getLatitude();
                Double lng = gps.getLongtitude();
                Toast.makeText(getApplicationContext(),
                        "Your location is -\nLat:"+lat+"\nLng:"+lng,
                        Toast.LENGTH_LONG).show();
                String url = "https://api.forecast.io/forecast/KEY/"+lat+","+lng+"?units=ca";
                JsonTask task = new JsonTask(getApplicationContext());
                task.execute(url);
                String url2 = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng;
                CityNameTask city = new CityNameTask(getApplicationContext());
                city.execute(url2);
            }
            else {
                gps.showSettingsAlert();
            }
        }
    });
}
}

第一个AsyncTask工作正常:

class JsonTask extends AsyncTask<String, String, String> {
private Context mContext;
public JsonTask (Context context){
    mContext = context;
}
protected void onPreExecute() {
    super.onPreExecute();
}
protected String doInBackground(String... params) {
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {
        URL url = new URL(params[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        InputStream stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        String data = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line+"\n");
            //Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)
            try{
                JSONObject jsonObject= new JSONObject(line).getJSONObject("currently");
                data=
                        jsonObject.getString("temperature")+","+
                        jsonObject.getString("windSpeed")+","+
                        jsonObject.getString("humidity")+","+
                        jsonObject.getString("summary");

            }
            catch(JSONException e)
            {
            }
        }
        return data.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    String string = result;
    String[] parts = string.split(",");
    String temperature = parts[0];
    String windSpeed = parts[1];
    String humidity = parts[2];
    String summary = parts[3];
    MainActivity.txtTemperature.setText(temperature);
    MainActivity.txtWindSpeed.setText(windSpeed);
    MainActivity.txtHumidity.setText(humidity);
    MainActivity.txtSummary.setText(summary);
}
}

第二个失败的任务:

class CityNameTask extends AsyncTask<String, String, String> {
private Context mContext;
public CityNameTask (Context context){
    mContext = context;
}
protected void onPreExecute() {
    super.onPreExecute();
}
protected String doInBackground(String... params) {
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {
        URL url = new URL(params[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        InputStream stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        String data = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line+"\n");
        }
        Log.d("Response: ", "> " + line);
        try {
            JSONObject  jsonRootObject = new JSONObject(line);

            JSONArray jsonArray = jsonRootObject.optJSONArray("results");
            for(int i=0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                data = jsonObject.getString("formatted_address");

            }

        } catch (JSONException e) {e.printStackTrace();}
        return data.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    MainActivity.txtCityName.setText(result);
}
}

- 编辑:logcat:

06-03 22:00:07.998 2804-2804/com.mortezaaghili.havamoon E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.mortezaaghili.havamoon, PID: 2804
                                                                          java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
                                                                              at com.mortezaaghili.havamoon.GpsTracker.getLatitude(GpsTracker.java:131)
                                                                              at com.mortezaaghili.havamoon.MainActivity$1.onClick(MainActivity.java:54)
                                                                              at android.view.View.performClick(View.java:5198)
                                                                              at android.view.View$PerformClick.run(View.java:21147)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

再次编辑: 这是GPSTracker类:​​

public class GpsTracker extends Service implements LocationListener {
    private final Context context;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    Location location;
    Double latitude;
    Double longtitude;
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
    protected LocationManager locationManager;
    public GpsTracker(Context context){
        this.context = context;
        getLocation();
    }
    public Location getLocation(){
        try {
            locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled){}
            else{
                this.canGetLocation = true;
                if(isNetworkEnabled){
                    try {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES,
                                this);

                        if (locationManager != null){
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                            if(location != null){
                                latitude = location.getLatitude();
                                longtitude = location.getLongitude();

                            }
                        }
                    }
                    catch (SecurityException e)
                    {

                    }
                }
                if(isGPSEnabled){
                    if (location == null){
                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES,
                                    this);

                            if (locationManager != null){
                                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                                if(location != null){
                                    latitude = location.getLatitude();
                                    longtitude = location.getLongitude();

                                }
                            }
                        }
                        catch (SecurityException e)
                        {
                        }
                    }
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    return location;
    }
    public void stopUsingGPS(){
        if (locationManager != null){
            try{
                locationManager.removeUpdates(GpsTracker.this);
            }
            catch(SecurityException e){
            }
        }
    }
    public double getLatitude(){
        if (locationManager != null){
            latitude = location.getLatitude();
        }
        return latitude;
    }
    public double getLongtitude(){
        if (locationManager != null) {
            longtitude = location.getLongitude();
        }
        return longtitude;

    }
    public boolean canGetLocation(){
        return this.canGetLocation;
    }
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setTitle("GPS is setting");
        alertDialog.setMessage("GPS is not enabled. do you want go to settings?");
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(intent);
            }
        });
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        alertDialog.show();
    }
    @Override
    public void onLocationChanged(Location location) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    }

4 个答案:

答案 0 :(得分:1)

看起来您的location变量未从GpsTracker类初始化。 因此,当您扩展Service类并实现LocationListener时,您将覆盖名为getLocation()的方法,该方法应返回Location对象,但在您的情况下返回{{1} }}

如果你可以发布该文件的代码,或者自己调试它。

答案 1 :(得分:0)

可能你的GpsTracker类必须包含以下内容:

public double getLatitude() {
    if(location != null) { // here must be checked if location is available and it's not null, coz now you probably get crash coz this has not been checked
        latitude = location.getLatitude();
    }
    return latitude;
}

答案 2 :(得分:0)

为了避免获取Null Locations,您需要使用google play locations API 这是谷歌推荐的。

同时尝试

    String line = ""; 
    String data = "";
    while ((line = reader.readLine()) != null) {
        buffer.append(line+"\n");
    } 

在此循环结束时,line对象为null    因此,在一些变量中保存最后一行元素的副本    然后在其上应用以下代码。

    Log.d("Response: ", "> " + line);
    try { 
        JSONObject  jsonRootObject = new JSONObject(line);

        JSONArray jsonArray = jsonRootObject.optJSONArray("results");
        for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            data = jsonObject.getString("formatted_address");

        } 

答案 3 :(得分:0)

堆栈跟踪的相关部分是:

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object
reference at com.mortezaaghili.havamoon.GpsTracker.getLatitude(GpsTracker.java:131)

提到破碎的代码:

public double getLatitude(){
        if (locationManager != null){
            latitude = location.getLatitude();
        }
        return latitude;
    }

您正在检查空locationManager,但随后调用location上的某个方法,该方法可能在getLocation()设置方法中的大尝试/抓住吞咽时无效在GPSTracker构造函数中。

检查location null:

public double getLatitude(){
        if (location != null){
            latitude = location.getLatitude();
        }
        return latitude;
    }