[英]NullPointerException when i call a class from an android service
This is my first Android App. 这是我的第一个Android应用程序。 I'm trying to call a function in a service from a different class i am using foursquare API.
我正在尝试使用Foursquare API从其他类调用服务中的函数。 I tried this function earlier in an activity and it worked perfectly but in a service im getting a NullPointerException.
我在一个活动中较早地尝试了此功能,它工作得很好,但是在服务中却收到了NullPointerException。 This is the code i am using:
这是我正在使用的代码:
public class GuideMeService extends Service implements LocationListener {
LocationManager locationManager;
Geocoder geocoder;
// private CalendarContentResolver Calendar;
public FoursquareApp mFsqApp;
public ArrayList<FsqVenue> mNearbyList;
private static String TAG = "Service Class";
double lat;
double lng;
public static final String[] FIELDS = { CalendarContract.Calendars.NAME,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.CALENDAR_COLOR,
CalendarContract.Calendars.VISIBLE };
public static ArrayList<String> Events = new ArrayList<String>();
public static final Uri CALENDAR_URI = Uri
.parse("content://com.android.calendar/calendars");
public static final Uri EVENTS_URI = Uri
.parse("content://com.android.calendar/events");
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
public static String query = "";
Set<String> calendars = new HashSet<String>();
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "GuideMe Servise started");
//this.stopSelf();
locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
Events = readCalendarEvent(getApplicationContext());
for(int i = 0 ; i < Events.size() ; i++){
query += Events.toArray()[i].toString() + " ";
}
Thread thread = new Thread()
{
@Override
public void run() {
try {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mNearbyList = mFsqApp.SearchBykeyword(location.getLatitude(), location.getLongitude(), query);
}catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
Im getting The error on this line : 我在这条线上得到错误:
mNearbyList = mFsqApp.SearchBykeyword(location.getLatitude(), location.getLongitude(), query);
And this is the function i'm calling in the mFsqApp class: 这是我在mFsqApp类中调用的函数:
public ArrayList<FsqVenue> SearchBykeyword(double latitude, double longitude, String query) throws Exception {
ArrayList<FsqVenue> venueList = new ArrayList<FsqVenue>();
try {
String ll = String.valueOf(latitude) + "," + String.valueOf(longitude);
URL url = new URL(API_URL + "/venues/search?ll=" + ll + "&query=" + query + "&radius=" + 50 + "&oauth_token=" + mAccessToken + "&v=20120610");
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray groups = (JSONArray) jsonObj.getJSONObject("response").getJSONArray("groups");
int length = groups.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
JSONObject group = (JSONObject) groups.get(i);
JSONArray items = (JSONArray) group.getJSONArray("items");
int ilength = items.length();
for (int j = 0; j < ilength; j++) {
JSONObject item = (JSONObject) items.get(j);
FsqVenue venue = new FsqVenue();
venue.id = item.getString("id");
venue.name = item.getString("name");
JSONObject location = (JSONObject) item.getJSONObject("location");
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(Double.valueOf(location.getString("lat")));
loc.setLongitude(Double.valueOf(location.getString("lng")));
venue.location = loc;
//venue.address = location.getString("address");
venue.distance = location.getInt("distance");
//venue.herenow = item.getJSONObject("hereNow").getInt("count");
venue.type = group.getString("type");
venueList.add(venue);
}
}
}
} catch (Exception ex) {
throw ex;
}
return venueList;
}
Updates: 更新:
07-08 21:26:18.580: W/System.err(24365): java.lang.NullPointerException
07-08 21:26:18.580: W/System.err(24365): at com.android.guideme.GuideMeService$1.run(GuideMeService.java:86)
You're declaring the (unfortunately public) mFsqApp
variable here: 您在这里声明了(不幸的是公开的)
mFsqApp
变量:
public FoursquareApp mFsqApp;
but you haven't shown any code to assign it a value - so it will have the default value of null
, causing a NullPointerException
when you dereference it. 但您没有显示任何代码来为其分配值-因此它将具有默认值
null
,当您取消引用它时会导致NullPointerException
。 You need to assign a non-null value to it before you dereference it, eg with 在取消引用之前,您需要为其分配一个非空值,例如
mFsqApp = new FoursquareApp();
... or using a value passed in elsewhere (eg to the constructor). ...或使用传入其他地方的值(例如,传递给构造函数)。 It's hard to tell which of those is appropriate in this case, but something has to assign a non-null value to it.
这很难说哪种情况在这种情况下适当的事 ,但有一个非空值分配给它。 You say similar code worked earlier in an activity - so look back at that code and see where the value was coming from there.
您说类似的代码在活动的早期就起作用了-因此,请回顾该代码,看看该值从何而来。
(Then improve your code to avoid public variables, avoid static variables where possible, avoid catching Exception
, avoid just continuing in the face of an exception unless you're really handled it etc.) (然后改进代码以避免公共变量,在可能的情况下避免静态变量,避免捕获
Exception
,除非在真正处理异常之前,否则避免继续面对异常等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.