如何获取经度和纬度并将其放入JSON链接?

时间:2015-06-05 16:27:49

标签: android json getter-setter locationlistener

我一直在尝试使用LocationListener获取经度和纬度,并将其作为int放入JSON链接,以便我可以使用当前用户位置的数据。当我尝试启动它时我的应用程序崩溃,但我可以得到经度和纬度坐标。我已经破坏了我的应用程序,只是简单地从一个活动中获取经度和纬度,并尝试在另一个活动中获取这些值,我将放置我的JSON活动。有什么我想念的吗?

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="viaan.carl.mytest" >

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

主要活动

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;

import android.view.Menu;

import android.widget.Toast;


public class MainActivity extends Activity implements LocationListener {

LocationManager locationmanager;
myGPS gps = new myGPS(this);


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

    locationmanager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Criteria cri=new Criteria();
    String provider=locationmanager.getBestProvider(cri,false);

    if(provider!=null & !provider.equals(""))
    {
        Location location=locationmanager.getLastKnownLocation(provider);
        locationmanager.requestLocationUpdates(provider,2000,1,this);
        if(location!=null)
        {
            onLocationChanged(location);
        }
        else{
            Toast.makeText(getApplicationContext(),"location not found",Toast.LENGTH_LONG ).show();
        }
    }
    else
    {
        Toast.makeText(getApplicationContext(),"Provider is null",Toast.LENGTH_LONG).show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public void onLocationChanged(Location location) {

    int lat;
    gps.setLat((int) location.getLatitude());
    int lng;
    gps.setLng((int) location.getLongitude());

    //TextView textView2=(TextView)findViewById(R.id.textview2);

    //TextView textView3=(TextView)findViewById(R.id.textview3);

    //textView2.setText("Latitude"+location.getLatitude());
    //textView3.setText("Longitude" + location.getLongitude());

}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}

}

Getter&amp; Setter Class

import android.app.Activity;
import android.content.SharedPreferences;

public class myGPS {

private int lat;
private int lng;
SharedPreferences prefs;

public myGPS(Activity activity) {
    prefs = activity.getPreferences(Activity.MODE_PRIVATE);
}


void setLng(int lng) {
    this.lng = lng;
}

int getLat() {
    return lat;
}

int getLng() {
    return lng;
}

void setLat(int lat) {
    this.lat = lat;
}
}

JSON所在的新类(目前只是试图显示数据)

import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class LocationDisplay extends Fragment {

TextView textView2;
TextView textView3;

myGPS gps;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_wind, container, false);
    textView2 = (TextView)rootView.findViewById(R.id.textview2);
    textView3 = (TextView)rootView.findViewById(R.id.textview3);

    return rootView;
}

public LocationDisplay () {
    textView2.setText("Latitude: " + gps.getLat());
    textView3.setText("Longitude: " + gps.getLng());
}
}

logcat的

06-05 11:36:52.499    1943-1943/? D/dalvikvm﹕ Late-enabling CheckJNI
06-05 11:36:52.567    1943-1943/viaan.carl.mytest E/Trace﹕ error opening trace file: No such file or directory (2)
06-05 11:36:52.575    1943-1943/viaan.carl.mytest D/AndroidRuntime﹕ Shutting down VM
06-05 11:36:52.575    1943-1943/viaan.carl.mytest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa619f908)
06-05 11:36:52.583    1943-1943/viaan.carl.mytest E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{viaan.carl.mytest/viaan.carl.mytest.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
        at android.app.Activity.getLocalClassName(Activity.java:4415)
        at android.app.Activity.getPreferences(Activity.java:4449)
        at viaan.carl.mytest.myGPS.<init>(myGPS.java:16)
        at viaan.carl.mytest.MainActivity.<init>(MainActivity.java:29)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1319)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

你正在以旧的方式获得Location。谷歌发布了新的Places API这个IO。您还可以通过以下方式获取用户的current location on Android

PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
    .getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
  @Override
  public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
    for (PlaceLikelihood placeLikelihood : likelyPlaces) {
      // this is your Location
      Log.i(TAG, String.format("Place '%s' has likelihood: %g",
          placeLikelihood.getPlace().getName(),
          placeLikelihood.getLikelihood()));
    }
    likelyPlaces.release();
  }
});

如果您想要当前位置,则无需进行API调用。您可以通过以下方式获取started。您可以从Location对象获取纬度/经度。

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