【发布时间】:2015-10-25 16:10:37
【问题描述】:
我有一个名为 ShowBoardList 的类,我在其中检查用户是否已登录。如果用户尚未登录,那么我想返回 MainActivity,它为用户提供登录按钮不同的服务。
我的 AndroidManifests.xml 看起来像这样:
<application
<activity android:name="im.chaitanya.TaskTimer.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="im.chaitanya.TaskTimer.WebViewActivity" >
</activity>
<activity android:name="im.chaitanya.TaskTimer.ShowBoardList"
android:label="Your Tasks">
</activity>
</application>
ShowBoardList.java 看起来像这样:
...
Intent mainActivityIntent = new Intent(ShowBoardList.this, im.chaitanya.TaskTimer.MainActivity.class);
Intent intent = getIntent();
String url = intent.getStringExtra(WebViewActivity.EXTRA_MESSAGE); //url can be null here
Keys keys = new Keys(); //this gets an API key
SharedPreferences settings = getSharedPreferences("mySettings", 0);
String savedToken = settings.getString("token", "Empty");
if (MyUtils.equalsWithNulls(url,"tasktimer://oauthresponse#token=")) {
Log.d("From ME:", "I've reached inside url check");
mainActivityIntent.putExtra(caller, "ShowBoardList");
//caller is a String. I'm storing the name of the current activity (ShowBoardList) in it.
//So that the main activity (which I'm trying to call) will know where the call came from.
startActivity(mainActivityIntent);
}
if(savedToken.equals("Empty") || savedToken.equals("")) {
String searchString = "#token=";
int tokenIndex = url.indexOf(searchString) + searchString.length(); //Since url can be null there can be an error here
String token = url.substring(tokenIndex);
savedToken = token;
SharedPreferences.Editor editor = settings.edit();
editor.putString("token", token);
editor.apply();
}
...
条件 equalsWithNulls 检查 url 是否为 null 或等于参数中的字符串。我在那里有日志语句来检查控制是否到达 if 语句内部。然而,主要活动没有开始。
编辑: MainActivity.java 的 onCreate() 看起来像这样:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences("mySettings", 0);
String token = settings.getString("token", "Empty");
Intent intent = new Intent(this, ShowBoardList.class);
if(token != "Empty") {
startActivity(intent);
}
intent = getIntent();
String callerActivity = intent.getStringExtra(ShowBoardList.caller);
View coordinatorLayoutView = findViewById(R.id.snackbarPosition);
if (callerActivity!=null && callerActivity == "ShowBoardList") {
Snackbar
.make(coordinatorLayoutView, "Permission Denied", Snackbar.LENGTH_LONG)
.show();
}
setContentView(R.layout.activity_main);
}
【问题讨论】:
-
有什么错误吗?发生了什么?请使用 LogCat。
-
我使用调试器检查发生了什么。控件越过该语句并继续到 if 语句之外的下一行。那里没有错误。 is 稍后出现错误,但那是因为主要活动未启动,程序尝试调用空对象上的函数。
-
我添加了更多代码。这应该让我更清楚我想要完成的事情。但就像我说的,在 startActivity() 语句中没有错误。
-
startActivity()不同步。它立即返回,活动稍后开始。这是你的问题吗? -
可能是这样。如何等待活动开始?