gpt4 book ai didi

java - ParseQuery - 正确处理 IndexOutOfBoundsException - Parse.com?

转载 作者:行者123 更新时间:2023-12-02 04:17:36 24 4
gpt4 key购买 nike

如何正确处理 throwIndexOutOfBoundsException?基本上,我正在查询用户。如果用户存在,它会显示他们的个人资料。但是,如果找不到条目,​​它会使我的应用程序崩溃并引发异常。我应该在“else”语句中添加什么内容才能使应用程序不会崩溃?

                    @Override
public void done(List<ParseUser> parseUsers, ParseException e) {
if (e == null) {
// The query was successful.
ParseUser user = parseUsers.get(0);
String userId = user.getObjectId();
showProfileActivity(userId);

} else {
// The query was unsuccessful.

}
}
});

这是日志猫:

10-14 21:27:06.888  28595-28595/com.app.social E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.elgami.customizer, PID: 28595
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.elgami.feed.SearchActivity$1$1.done(SearchActivity.java:74)
at com.elgami.feed.SearchActivity$1$1.done(SearchActivity.java:67)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

最佳答案

您可以检查列表是否为空:

 @Override
public void done(List<ParseUser> parseUsers, ParseException e) {
if (!parseUsers.isEmpty()) {
// The query was successful.
ParseUser user = parseUsers.get(0);
String userId = user.getObjectId();
showProfileActivity(userId);

} else {
// The query was unsuccessful.

}
}
});

或者如果你想捕获异常,请使用 try -catch ,如下所示:

 @Override
public void done(List<ParseUser> parseUsers, ParseException e) {
if (e==null) {
// The query was successful.
try{
ParseUser user = parseUsers.get(0);
String userId = user.getObjectId();
}
catch(ArrayIndexOutOfBoundsException e)
{
// Print message for user does not exist .
}
showProfileActivity(userId);
}
else {
// The query was unsuccessful.
}
}
});

关于java - ParseQuery - 正确处理 IndexOutOfBoundsException - Parse.com?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com