在捆绑中传递一堆数组

时间:2015-08-03 23:53:26

标签: android arrays save stack bundle

有没有人如何将Stack of Integer Arrays放入一个bundle中,这样我就可以将它们拉出来并再次恢复Stack。我已经尝试过这样但是它不起作用。

在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 个答案:

答案 0 :(得分:0)

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);
    }
}