gpt4 book ai didi

android - 保存 Intent

转载 作者:行者123 更新时间:2023-11-29 17:35:21 29 4
gpt4 key购买 nike

我有 3 个 Activity

第一个 Activity 调用第二个 Activity ,第二个 Activity 调用第三个 Activity 。

第二个 Activity 使用第一个 Activity 的额外 Intent 。

因此,当我从第 3 个 Activity 返回(使用操作栏后退按钮)到第 2 个 Activity 时,我在提取额外 Intent 的地方得到了一个 nullpointerexception。注意:如果我按下导航栏后退按钮,则不会发生这种情况。

按下操作栏后退按钮时,它正在重新启动 Activity,因此没有 Intent 。

在按下导航栏后退按钮时,它正在恢复 fragment ,因此我能够显示我的可解析数据。

关于如何保存 intent extras 的任何线索?我认为的一种解决方法是将其保存为共享首选项,但我想知道执行此操作的最佳做​​法。

编辑:添加代码

来自 Activity 1 的 fragment 。

Intent intent = new Intent(getActivity(), TopTenTracksActivity.class)
.putExtra(Intent.EXTRA_TEXT, new String[]{artistId, artistName});
startActivity(intent);

在 Activity fragment 2 中获取 Intent

String[] artistInfo = getActivity().getIntent().getExtras().getStringArray(Intent.EXTRA_TEXT);

获取上面的空指针错误。

错误日志

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] android.os.Bundle.getStringArray(java.lang.String)' on a null object reference
at com.plusgaurav.spotifystreamer.TopTenTracksActivityFragment.onCreateView(TopTenTracksActivityFragment.java:62)

编辑:这是我的以下代码:

public class TopTenTracksActivity extends AppCompatActivity {

public static String[] artistInfo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (savedInstanceState != null) {

artistInfo = savedInstanceState.getStringArray("savedArtistInfo");

} else {

// get intent info
artistInfo = getIntent().getExtras().getStringArray(Intent.EXTRA_TEXT);

}

setContentView(R.layout.activity_top_ten_tracks);

// set subtitle in the actionbar
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setSubtitle(artistInfo[1]);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

// save intent
outState.putStringArray("savedArtistInfo", artistInfo);
}

还是会进入上面说的else循环。我的问题是为什么当我按下 ActionBar 时 savedInstanceState 为空。

最佳答案

ActionBar 背面实际上是“向上”按钮。它和设备后退按钮之间的区别在于“向上”按钮意味着在屏幕层次结构中上升(返回到父 Activity 的实例),而设备后退按钮意味着按时间顺序返回(字面意思是下一个)返回堆栈上的 Activity )。

根据您启动 Activity 的方式和为该 Activity 指定的启动模式,当您点击“向上”按钮时,您可能会被定向到该父 Activity 的新实例,而不是现有实例。

请阅读以下内容了解更多详情:http://developer.android.com/training/implementing-navigation/ancestral.html#NavigateUp

我的猜测是发生了什么(从我链接的页面):

If the parent activity has launch mode <standard>, and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP, the parent activity is popped off the stack, and a new instance of that activity is created on top of the stack to receive the intent.

尝试将您的 Activity 2(或任何您似乎正在失去额外费用的 Activity)的启动模式设置为 singleTop

关于android - 保存 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30688443/

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