我想从Facebook获取user's location
,但获取Null Pointer Exception
(NPE)和log
看起来像这样:
D/dalvikvm(3116): GC_FOR_ALLOC freed 413K, 15% free 2863K/3336K, paused 32ms, total 32ms
W/System.err(3116): java.lang.NullPointerException
W/System.err(3116): at com.example.loginfb.MainActivity$2.onUserInfoFetched(MainActivity.java:50)
W/System.err(3116): at com.facebook.widget.LoginButton$2.onCompleted(LoginButton.java:770)
W/System.err(3116): at com.facebook.Request$1.onCompleted(Request.java:280)
W/System.err(3116): at com.facebook.Request$4.run(Request.java:1658)
W/System.err(3116): at android.os.Handler.handleCallback(Handler.java:730)
W/System.err(3116): at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err(3116): at android.os.Looper.loop(Looper.java:137)
W/System.err(3116): at android.app.ActivityThread.main(ActivityThread.java:5103)
W/System.err(3116): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(3116): at java.lang.reflect.Method.invoke(Method.java:525)
W/System.err(3116): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
W/System.err(3116): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
W/System.err(3116): at dalvik.system.NativeStart.main(Native Method)
MainActivity.java: -
public void onUserInfoFetched(GraphUser user) {
try {
if (user != null) {
String strName = user.getFirstName();
String strLocation = user.getLocation().toString();
textUserName.setText("Welcome, " + user.getName()) ;
textUserInformation.setText
(
"Name: " + strName + "\n"
+
"Location: " + strLocation
);
} else {
textUserName.setText("You are not Logged In");
textUserInformation.setText("");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
我想我正面临这个问题,因为有not given Location details on Facebook
,但我想要显示"地址未提及"用户not provided to Facebook
以及其他详细信息。
答案 0 :(得分:4)
将String strLocation = user.getLocation().toString();
划分为:
Object userLocation = user.getLocation();
String strLocation = (userLocation != null)? userLocation.toString() : "Address not mentioned";
我不知道Location对象的类型,但如果user.getLocation()
返回null
,则代码中会有java.lang.NullPointerException
。