She*_*lam 77 java android activity-lifecycle android-lifecycle android-activity
以下是我的应用程序的布局:
我怎样才能做到这一点?
这是我的MainActivity:
@Override
protected void onResume(){
super.onResume();
isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(!isLoggedIn){
showLoginActivity();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的LoginActivity:
@Override
protected void onPostExecute(JSONObject json) {
String authorized = "200";
String unauthorized = "401";
String notfound = "404";
String status = new String();
try {
// Get the messages array
JSONObject response = json.getJSONObject("response");
status = response.getString("status");
if(status.equals(authorized)){
Toast.makeText(getApplicationContext(), "You have been logged into the app!",Toast.LENGTH_SHORT).show();
prefs.edit().putBoolean("isLoggedIn",true);
setResult(RESULT_OK, getIntent());
finish();
}
else if (status.equals(unauthorized)){
Toast.makeText(getApplicationContext(), "The username and password you provided are incorrect!",Toast.LENGTH_SHORT).show();
prefs.edit().putBoolean("isLoggedIn",true);
}
else if(status.equals(notfound)){
Toast.makeText(getApplicationContext(), "Not found",Toast.LENGTH_SHORT).show();
prefs.edit().putBoolean("isLoggedIn",true);
}
} catch (JSONException e) {
System.out.println(e);
} catch (NullPointerException e) {
System.out.println(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
用户成功登录后:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "BOOM SHAKA LAKA!",Toast.LENGTH_SHORT).show();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,在onActivityResult()之前调用onResume(),因此当用户成功登录时,我的主活动不会得到通知,因为首先调用onResume().
提示登录的最佳位置在哪里?
Yon*_*lan 94
对onActivityResult的调用实际上发生在onResume之前(参见文档).您确定实际上是在启动所需的活动,startActivityForResult
并且RESULT_OK
在将值返回到您的活动之前设置了被调用活动的结果吗?尝试Log
在您onActivityResult
的日志中添加一个语句来记录该值,并确保它被命中.另外,您在哪里设置isLoggedIn
首选项的值?看起来你应该true
在你的登录活动中设置它,然后才能返回,但这显然不会发生.
Phi*_*hil 29
使用片段,它甚至不像onActivityResult()
在调用之前调用那么简单onResume()
.如果您要返回的活动在过渡期间被处理掉,您会发现对(例如)getActivity()
from的调用onActivityResult()
将返回null.但是,如果活动尚未处理,则调用getActivity()
将返回包含活动.
这种不一致可能是难以诊断的缺陷的来源,但您可以通过启用开发人员选项"不要保留活动"来检查应用程序的行为.我倾向于保持这种状态 - 我宁愿看到NullPointerException
开发中而不是生产中.
归档时间: |
|
查看次数: |
44337 次 |
最近记录: |