我在Android上做应用程序以获取我附近的地方,当我试图运行时,我做了一切,但得到了这个例外,我不知道造成这种异常的原因是什么
MainActivity
package com.gas;
public class MainActivity extends Activity implements LocationListener{
GoogleMap mGoogleMap;
GoogleMap map;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlaceType = getResources().getStringArray(R.array.place_type);
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
mSprPlaceType.setAdapter(adapter);
Button btnFind;
btnFind = ( Button ) findViewById(R.id.btn_find);
MapFragment fm=(MapFragment) getFragmentManager().findFragmentById(R.id.map);
map=fm.getMap();
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null)
onLocationChanged(location);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
btnFind.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=YOUR_API_KEY");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
}
});
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
@Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
@Override
protected void onPostExecute(List<HashMap<String,String>> list){
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));
String name = hmPlace.get("place_name");
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
mGoogleMap.addMarker(markerOptions);
}
}
}
@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
}
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gas"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<permission
android:name="com.gas.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.gas.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:name="android.hardware.location"
android:required="false" />
<uses-feature
android:name="android.hardware.location.network"
android:required="false" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-feature
android:name="android.hardware.wifi"
android:required="false" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.gas.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>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAtg_enu6Ox2l-WMyT-rpk_dUytQvSZaEw" />
</application>
</manifest>
PlaceJasonParser
package com.gas;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity="-NA-";
String latitude="";
String longitude="";
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Spinner
android:id="@+id/spr_place_type"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentTop="true" />
<Button
android:id="@+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/spr_place_type"
android:text="@string/str_btn_find" />
<fragment
android:id="@+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/spr_place_type"
class="com.google.android.gms.maps.MapFragment" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
logcat的
05-23 04:19:27.233: D/AbsListView(4213): Get MotionRecognitionManager
05-23 04:19:27.573: D/AndroidRuntime(4213): Shutting down VM
05-23 04:19:27.573: W/dalvikvm(4213): threadid=1: thread exiting with uncaught exception (group=0x40c18a68)
05-23 04:19:27.573: E/AndroidRuntime(4213): FATAL EXCEPTION: main
05-23 04:19:27.573: E/AndroidRuntime(4213): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gas/com.gas.MainActivity}: java.lang.NullPointerException
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.ActivityThread.access$600(ActivityThread.java:128)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.os.Looper.loop(Looper.java:137)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.ActivityThread.main(ActivityThread.java:4517)
05-23 04:19:27.573: E/AndroidRuntime(4213): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 04:19:27.573: E/AndroidRuntime(4213): at java.lang.reflect.Method.invoke(Method.java:511)
05-23 04:19:27.573: E/AndroidRuntime(4213): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
05-23 04:19:27.573: E/AndroidRuntime(4213): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
05-23 04:19:27.573: E/AndroidRuntime(4213): at dalvik.system.NativeStart.main(Native Method)
05-23 04:19:27.573: E/AndroidRuntime(4213): Caused by: java.lang.NullPointerException
05-23 04:19:27.573: E/AndroidRuntime(4213): at com.gas.MainActivity.onLocationChanged(MainActivity.java:375)
05-23 04:19:27.573: E/AndroidRuntime(4213): at com.gas.MainActivity.onCreate(MainActivity.java:194)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.Activity.performCreate(Activity.java:4470)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
05-23 04:19:27.573: E/AndroidRuntime(4213): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
05-23 04:19:27.573: E/AndroidRuntime(4213): ... 11 more
05-23 04:21:46.973: D/AbsListView(4760): Get MotionRecognitionManager
05-23 04:21:47.253: D/AndroidRuntime(4760): Shutting down VM
05-23 04:21:47.253: W/dalvikvm(4760): threadid=1: thread exiting with uncaught exception (group=0x40c18a68)
05-23 04:21:47.253: E/AndroidRuntime(4760): FATAL EXCEPTION: main
05-23 04:21:47.253: E/AndroidRuntime(4760): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gas/com.gas.MainActivity}: java.lang.NullPointerException
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.ActivityThread.access$600(ActivityThread.java:128)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.os.Looper.loop(Looper.java:137)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.ActivityThread.main(ActivityThread.java:4517)
05-23 04:21:47.253: E/AndroidRuntime(4760): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 04:21:47.253: E/AndroidRuntime(4760): at java.lang.reflect.Method.invoke(Method.java:511)
05-23 04:21:47.253: E/AndroidRuntime(4760): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
05-23 04:21:47.253: E/AndroidRuntime(4760): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
05-23 04:21:47.253: E/AndroidRuntime(4760): at dalvik.system.NativeStart.main(Native Method)
05-23 04:21:47.253: E/AndroidRuntime(4760): Caused by: java.lang.NullPointerException
05-23 04:21:47.253: E/AndroidRuntime(4760): at com.gas.MainActivity.onLocationChanged(MainActivity.java:375)
05-23 04:21:47.253: E/AndroidRuntime(4760): at com.gas.MainActivity.onCreate(MainActivity.java:194)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.Activity.performCreate(Activity.java:4470)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
05-23 04:21:47.253: E/AndroidRuntime(4760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
05-23 04:21:47.253: E/AndroidRuntime(4760): ... 11 more
答案 0 :(得分:1)
您已发表评论
mGoogleMap = fragment.getMap();
当您尝试移动相机时,方法mGoogleMap
中的onLocationChanged
为空 - &gt; MainActivity中的第375行:
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
答案 1 :(得分:0)
您使用GoogleMap map
代替GoogleMap mGoogleMap
,因此您应该使用此代码:
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(12));
而不是
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
因为mGoogleMap
是null
..