Android Studio: Passing longitude and latitude

757 views Asked by At

My application is a weather api to gather information about weather of the current location. I do this by putting in a postcode and then the ASync gathers the information. I am also using GooglePlayServices to find the location i send to the device using longitude and latitude. What i would like to do is pass the value of Longitude and latitude into my API Class and attach that onto the REST API url to find information. It is hard to explain but my code may make this clear.

Code for REST API and GooglePlayServices:

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.*;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;


public class RESTAPI extends Activity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

private GoogleApiClient mGoogleApiClient;
public static final String TAG = RESTAPI.class.getSimpleName();



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

// start the  AsyncTask for calling the REST service using httpConnect class
    new AsyncTaskParseJson().execute();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

}
// added asynctask class methods below -  you can make this class as a separate class file
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    Bundle bundle = getIntent().getParcelableExtra("bundle");
    LatLng latLng = bundle.getParcelable("latLng");
    // json test string
    String jsonTest;
    // set the url of the web service to call
    String yourServiceUrl = "http://api.apixu.com/v1/current.json?key=e87e62510df946cc84c02652162112&q=" + latLng ;

    @Override
    // this method is used for......................
    protected void onPreExecute() {

    }

    @Override
    // this method is used for...................
    protected String doInBackground(String... arg0) {

        try {
            // create new instance of the httpConnect class
            httpConnect jParser = new httpConnect();

            // get json string from service url
            String json = jParser.getJSONFromUrl(yourServiceUrl);

            // save returned json to your test string
            jsonTest = json.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    // below method will run when service HTTP request is complete
    protected void onPostExecute(String strFromDoInBg) {
        TextView tv1 = (TextView) findViewById(R.id.jsontext);
        tv1.setText(jsonTest);
    }


}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        // Blank for a moment...
    } else {
        handleNewLocation(location);
    }
}

private void handleNewLocation(Location location) {
    Intent i= new Intent(this, AsyncTaskParseJson.class);
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    Log.d(TAG, location.toString());
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);
    Bundle args = new Bundle();
    args.putParcelable("latLng", latLng);
    i.putExtra("bundle", args);
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Location services suspended. Please reconnect.");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}

@Override
protected void onResume() {
    super.onResume();
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}
}

The part of the code where i am trying to get the Long and lat values into a bundle:

 private void handleNewLocation(Location location) {
    Intent i= new Intent(this, AsyncTaskParseJson.class);
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    Log.d(TAG, location.toString());
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);
    Bundle args = new Bundle();
    args.putParcelable("latLng", latLng);
    i.putExtra("bundle", args);
}

and now where i am trying to declare inside my Async class:

 public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

 Bundle bundle = getIntent().getParcelableExtra("bundle");
    LatLng latLng = bundle.getParcelable("latLng");
    // json test string
    String jsonTest;
    // set the url of the web service to call
    String yourServiceUrl = "http://api.apixu.com/v1/current.json?key=e87e62510df946cc84c02652162112&q=" + latLng ;

The result is my application crashing when the activity is selected. I just want to carry these long and lat values over and add them to the end of the URL. I hope this is clear and any advice and better structure to this mess of a class would be appriciated thank you.

12-21 07:04:02.262 3020-3020/com.example.mr_br.healthandfitnessapplication E/AndroidRuntime: FATAL EXCEPTION:

main Process: com.example.mr_br.healthandfitnessapplication, PID: 3020 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mr_br.healthandfitnessapplication/com.example.mr_br.healthandfitnessapplication.RESTAPI}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference at com.example.mr_br.healthandfitnessapplication.RESTAPI$AsyncTaskParseJson.(RESTAPI.java:46) at com.example.mr_br.healthandfitnessapplication.RESTAPI.onCreate(RESTAPI.java:34) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  12-21 07:04:02.268 1500-1782/system_process W/ActivityManager: Force finishing activity 1 com.example.mr_br.healthandfitnessapplication/.RESTAPI

I believe this to be where the crash happens on my application.

0

There are 0 answers