在 Bundle 中传递一堆数组
Posted
技术标签:
【中文标题】在 Bundle 中传递一堆数组【英文标题】:Passing a Stack of Arrays in a Bundle 【发布时间】:2015-08-03 23:53:26 【问题描述】:有谁知道如何将一堆整数数组放入一个包中,以便我可以将它们拉出来并再次恢复堆栈。我已经尝试过这样但它不起作用。
在 Bundle 中保存数组堆栈:
public Bundle returnBreakStackContents()
Bundle bundle = new Bundle();
int count = breaksStack.size();//Count gives the Bundle Entry A Unique Key
bundle.putInt("breakStackSize",count);
while (!breaksStack.empty())
//Get Break Array From Stack
Integer[] a = breaksStack.pop();
//Convert To List
List b = Arrays.asList(a);
//Convert To ArrayList
ArrayList c = new ArrayList();
c.addAll(b);
//Save Break to the Bundle with a Unique Key
bundle.putIntegerArrayList("breakArray" + count, c);
count--;
return bundle;
从包中拉出数组并再次恢复堆栈:
Bundle newBundle = savedInstanceState.getBundle("breakStack");
if (newBundle != null)
int count = newBundle.getInt("breakStackSize");
Toast.makeText(this,"Number of Breaks: " + count, Toast.LENGTH_SHORT).show();
while (count > 0)
ArrayList a = newBundle.getIntegerArrayList("breakArray" + count);
Integer[] b = new Integer[a.size()];
a.toArray(b);
bAdapter.getBreaksStack().push(b);
count--;
任何帮助将不胜感激。我似乎得到了一个空堆栈异常。但是,似乎对象正在进入堆栈,因为我已记录 Stack.size() 大于 0。
【问题讨论】:
【参考方案1】:java.util.Stack 扩展了 java.util.Vector,java.util.Vector 实现了 Serializable。所以可以直接放入Bundle中。
package com.example.testapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.util.Stack;
public class MainActivity extends Activity
private static final String TAG = "MainActivity";
private Stack<Integer> mStack;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
mStack = (Stack) savedInstanceState.getSerializable("stack");
Log.d(TAG, "Loaded stack from the saved state");
if (mStack == null)
mStack = new Stack<Integer>();
mStack.add(1);
mStack.add(2);
mStack.add(3);
mStack.add(4);
Log.d(TAG, "Created new stack");
Log.d(TAG, "mStack=" + mStack);
@Override
protected void onSaveInstanceState(Bundle outState)
super.onSaveInstanceState(outState);
outState.putSerializable("stack", mStack);
【讨论】:
以上是关于在 Bundle 中传递一堆数组的主要内容,如果未能解决你的问题,请参考以下文章
Android 中使用bundle.putExtra实现Activity之间的参数传递
使用 Bundle 将数组数据传递给 listview click 上的另一个活动
Android基础——使用Bundle在Activity间传递数据