簡體   English   中英

在活動之間傳輸int不能正常工作

[英]Transfering int between activities does not work correctly

我需要在2個活動之間轉移User和int,這發生在單擊列表視圖活動1中的項目時:

Intent intent = new Intent(GameActivity.this,ServerActivity.class);
intent.putExtra("serverNum",position);
intent.putExtra("currentUser",currentUser);
Log.d("position", position + "");
startActivity(intent);
finish();

該位置是通過取消用戶單擊的項目的編號來實現的。log.d確實顯示了當前位置,但是當我嘗試在活動2中獲取該Int時,其始終為0。

在活動2中:

Log.d("Server Number",getIntent().getExtras().getInt("serverNum")+"");

此log.d始終顯示為0。盡管用戶傳輸良好。

編輯

我發現它與清單中的android:launchMode =“ singleTask”有關,由於某種原因,該活動打開兩次,一個很好打開,一個由於某種原因而打開,且多余的“ serverNum”等於0,關於如何解決這個問題?

在練習2中嘗試此操作。

int id=getIntent().getIntExtra("serverNum", 0);

Log.d("ServerNumber",id+"");

嘗試覆蓋方法並在那里檢查值

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
int id=intent.getIntExtra("serverNum", 0);
Log.d("ServerNumber",id+"");
setIntent(intent);

}

您應該擺脫android:launchMode="singleTask" 原因是這僅創建活動的一個實例。 一旦回到它,它將多余的值重置為0。在這里您可以閱讀啟動類型: https : //inthecheesefactory.com/blog/understand-android-activity-launchmode/en

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM