问题描述
我知道这里有几个问题都有相同的主题和错误,但没有一个表明我的问题同样如此,所以我决定在这里发帖,希望有人帮我指出原因。
所以我正在尝试在我的应用程序中实现登录功能,这里是代码:
I know that there are several questions posted on here with the same topic and error, but none of them indicate the same problem as mine, so I decided to post my question here, hoping that someone would help me point out the cause.So I'm trying to implement the login feature in my app and here's the code:
if (tag.equalsIgnoreCase(login_tag)){
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(mContext);
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
logoutUser(mContext);
Toast.makeText(mContext, json.toString(3), Toast.LENGTH_LONG).show();
db.addUser(json_user.getString(KEY_EMAIL), json_user.getString(KEY_NAME), json.getString(KEY_UID), json.getString(KEY_AVA), json_user.getString(KEY_BDAY), json_user.getString(KEY_COUNTRY), json_user.getString(KEY_PREF), json_user.getString(KEY_SPEND));
// Launch Dashboard Screen
Intent dashboard = new Intent(mContext, DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(dashboard);
// Close Login Screen
((Activity) mContext).finish();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
这是我登录时收到的JSON响应:
And this is the JSON response I got when logging in:
{
"tag": "login",
"success": 1,
"error": 0,
"uid": "5123",
"user": {
"email": "abcxyz@gmail.com",
"name": "abc",
"avatar": "avatars/img_hzsxda_2013-03-18-11-03-33.jpg",
"bday": "1991-02-01",
"country": "Australia",
"preferences": "none",
"spending": "none"
}
}
显然,头像
有一个值,但我仍然有这个我的logcat警告:
So apparently there is a value for avatar
, but I still got this warning in my logcat:
03-18 12:06:36.972: W/System.err(24574): org.json.JSONException: No value for avatar
由于没有得到任何价值的头像,我无法完成 addUser
,因此登录失败。
请帮我找出错误以及如何解决。谢谢。
Since no value avatar is got, I can't complete addUser
, hence login fails.Please help me find the error and how to solve it. Thank you.
推荐答案
您使用了错误的对象来获取头像
这里的值 json.getString(KEY_AVA)
。它应该是 json_user.getString(KEY_AVA)
。
You are using the wrong object to get avatar
value here json.getString(KEY_AVA)
. It should be json_user.getString(KEY_AVA)
.
此外,你可以使用 optString
而不是 getString
如果值不存在则返回 null
而不是抛出例外。
Also, you can use optString
instead of getString
which just returns null
if value doesn't exist, instead of throwing an exception.
这篇关于Android - JSONException没有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!