我得到了一个nullpointerexception。 我检查库和所有但无法解决它。 也许可能是背景? ontext。 或者是我在代码中遗漏的东西。
任何帮助都会被贬低。 调试只是说.... nullpointerex ... 这是我的java类:
package bla;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.MapFragment;
import android.support.v4.app.FragmentManager;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
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.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.os.Bundle;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
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;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class RiverFragment extends Fragment implements LocationListener {
protected LocationManager locationManager;
// GoogleMap googleMap;
LatLng myPosition;
private SupportMapFragment map;
private GoogleMap mMapView;
int fragVal2;
static Context ontext;
private static View view;
//lo que se ocupa para construir los sitios
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Array of place types
mPlaceType = getResources().getStringArray(R.array.rivers);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.rivers2);
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.fragment_layout, container,
false);
android.support.v4.app.FragmentManager fm = getFragmentManager();
map = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (map == null) {
map = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, map).commit();
}
// mMapView = fm.getMap();
mMapView = map.getMap();
// Enabling MyLocation Layer of Google Map
mMapView.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) ontext.getSystemService(Context.LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Getting reference to the TextView of the Fragment
//TextView tv = (TextView) view.findViewById(R.id.tv_content);
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
// List of rivers
String[] rivers = getResources().getStringArray(R.array.rivers);
// Setting currently selected river name in the TextView
String type = mPlaceType[position];
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=yeah");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
// Updating the action bar title
// getActivity().getActionBar().setTitle(rivers[position]);
//return layoutView;
// Retrieving the currently selected item number
// int position = getArguments().getInt("position");
// List of rivers
// String[] rivers = getResources().getStringArray(R.array.rivers);
// Creating view correspoding to the fragment
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
return view;
}
/** 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);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
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;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
@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]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mMapView.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mMapView.addMarker(markerOptions);
}
}
}
/* @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} */
@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mMapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMapView.animateCamera(CameraUpdateFactory.zoomTo(12));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
/*
@Override
public void onDestroyView() {
super.onDestroyView();
MapFragment f = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
} */
}
错误在于此部分:
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) ontext.getSystemService(Context.LOCATION_SERVICE);
日志说
06-10 19:58:53.423: E/AndroidRuntime(30871): FATAL EXCEPTION: main
06-10 19:58:53.423: E/AndroidRuntime(30871): java.lang.NullPointerException
06-10 19:58:53.423: E/AndroidRuntime(30871): at in.wptrafficanalyzer.navigationdrawerdemo.RiverFragment.onCreateView(RiverFragment.java:163)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.os.Handler.handleCallback(Handler.java:615)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.os.Handler.dispatchMessage(Handler.java:92)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.os.Looper.loop(Looper.java:153)
06-10 19:58:53.423: E/AndroidRuntime(30871): at android.app.ActivityThread.main(ActivityThread.java:4987)
06-10 19:58:53.423: E/AndroidRuntime(30871): at java.lang.reflect.Method.invokeNative(Native Method)
06-10 19:58:53.423: E/AndroidRuntime(30871): at java.lang.reflect.Method.invoke(Method.java:511)
06-10 19:58:53.423: E/AndroidRuntime(30871): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
06-10 19:58:53.423: E/AndroidRuntime(30871): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
06-10 19:58:53.423: E/AndroidRuntime(30871): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
您的变量ontext
(上下文)在引用时为空
我没看到你在哪里初始化它。
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);