使用savedInstanceState保存fragmentstate

时间:2012-02-29 11:03:08

标签: java android android-activity save

saveInstanceState()无法正常工作。
我正在尝试读取数据,因此当用户重新选择选项卡时,我不必再次执行查询。片段是操作栏中的选项卡。一切正常,我只是无法将savedInstanceState变成其他任何东西然后是NULL,任何人都有任何想法?

这是我的代码:

public class SpecsFragment extends Fragment {
    private String mText;
    private ArrayList<HashMap> result;
    private Converter c;
    private View fragView;

public SpecsFragment() {
    mText = "specs";
    c = new Converter();
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    fragView = inflater.inflate(R.layout.product_info_fragment, container, false);

    return fragView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    if(savedInstanceState == null) {

        Bundle args = getArguments();
        int id = Integer.parseInt(args.getString("id"));

        String query = "SELECT * FROM products WHERE id = " + id;

        try {
            ZoekQueryTask zoekQueryTask = new ZoekQueryTask(query);
            result = zoekQueryTask.getResults();
        }

        catch (Exception e) {
            Log.e("Afgevangen error", e.getMessage());
        }
    }
    else {
        result = new ArrayList();
        result.add((c.BundleToHashMap(savedInstanceState)));
    }

    TextView text = (TextView) fragView.findViewById(R.id.textView1);
    text.setText(mText);
    text.append("\n\n");
    text.append(result.get(0).get("ean").toString());
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState = c.HashmapToBundle(result.get(0));
}

}

使用

savedInstance.putAll(c.HashmapToBundle(result.get(0)));

仍然无效。

savedInstance.putBundle("results", c.HashmapToBundle(result.get(0)));

也不起作用,任何人都有任何想法?

我通过解决问题解决了问题,而不是尝试存储savedInstanceState。我编写了函数来从片段父活动中获取和设置Bundle,然后使用:

获取活动
YourActivity parent = (YourActivity) this.getactivity();

只需调用函数来获取和设置自己编写的包。

2 个答案:

答案 0 :(得分:1)

我通过解决问题解决问题,而不是尝试存储savedInstanceState。我编写了函数来从片段父活动中获取和设置Bundle,然后使用:

获取活动
YourActivity parent = (YourActivity) this.getactivity(); 

只需调用函数来获取和设置自己编写的包

答案 1 :(得分:0)

如果您的Fragment是在XML布局中定义的,请确保您已指定了android:id!