[英]Problem with sending data from one activity to another
解決:我解決了這個問題。 感謝Ted指向我正確的方向,結果代碼返回0。然后我意識到當再次調用主Activity時。 它正在取消結果。 所以我檢查了清單文件,並啟用了單實例。
我在這個問題上花了很多時間。 用Google搜索答案。 但是我似乎什么也做不了。 我是Android的新手,也是Stack Overflow上的新手,所以抱歉,如果我修改了格式。
好的,所以我有一個主要活動的應用程序。 在此活動中,我有一個登錄按鈕。 當用戶單擊登錄按鈕時,它將在新的活動(登錄活動)中打開,該活動基本上允許用戶登錄。 所有這些都在工作和測試。 但是我的問題是,當用戶登錄時,我想將他的名字,姓氏和userID傳遞回主要活動。 為了嘗試在兩個活動之間傳遞數據,我嘗試遵循http://developer.android.com/resources/faq/commontasks.html#opennewscreen (位於“從屏幕返回結果”標題下)。
好的,這是有關我如何執行此操作的代碼:主要活動代碼:
logIn = (Button)this.findViewById(R.id.LogInButton);
logIn.setVisibility(View.INVISIBLE);
logIn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent loginIntent = new Intent(Main.this, Login.class);
startActivityForResult(loginIntent, LOGIN_CODE);
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (LOGIN_CODE) : {
if (resultCode == Activity.RESULT_OK) {
this.setLogin(data);
}
break;
}
}
}
這是登錄活動的代碼:
/**
* Login to user.
*/
private void loginCheck()
{
firstName = firstNameET.getText().toString();
lastName = lastNameET.getText().toString();
patientID = patientIDET.getText().toString();
password = passwordET.getText().toString();
boolean loginCorrect = management.isLoginCorrect(patientID, firstName, lastName, password);
if(loginCorrect == true)
{
//Pass login data to main(QOLMeasurment) activity and bring us back to that activity.
Intent intent = new Intent(Login.this, QOLMeasurement.class);
Bundle bundle = new Bundle();
bundle.putString("firstName", firstName);
bundle.putString("lastName", lastName);
bundle.putString("patientID", patientID);
intent.putExtras(bundle);
setResult(Activity.RESULT_OK, intent);
Log.d("TEST", "TEST!");
Login.this.finish();
Log.d("TEST", "TEST:(");
}
else
{
Toast.makeText(this, "Login Failed.", Toast.LENGTH_LONG).show();
}
}
所以我的問題是我似乎無法將數據返回到主要活動中。 嘗試對它進行故障排除是我的困難。 據我了解,方法startActivityForResult()將開始偵聽結果,並且結果將由onActivityResult()方法處理; 因此,在我的登錄活動中,我先設置了setResult(),然后關閉了將resultCode傳遞給onActivityResult()的活動,這種理解對嗎?
如果是這樣,那么手頭的問題似乎是當我調用Login.this.finish();時。 它似乎沒有完成活動,因此resultCode從未更新。 有什么幫助嗎? 我真的為此陷入困境。 謝謝你的時間!!! 鮑比
在登錄活動的代碼中,替換為:
Intent intent = new Intent(Login.this, Main.class);
與
Intent intent = new Intent();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.