0

如何保存我的 List onSaveInstanceState 方法的状态?

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private List<RssItem> items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.listView);

        onStartCommand();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putStringArrayList("return", items);
    }

    private void onStartCommand() {
        Intent intent = new Intent(getBaseContext(), RssIntentService.class);
        intent.putExtra(RssIntentService.RECEIVER, resultReceiver);
        startService(intent);
    }

    private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            items = (List<RssItem>) resultData.getSerializable(RssIntentService.ITEMS);
            if (items != null) {
                RssAdapter adapter = new RssAdapter(getBaseContext(), items);
                listView.setAdapter(adapter);
            } else
                Toast.makeText(getBaseContext(), "Não foi possível encontrar seu feed", Toast.LENGTH_SHORT).show();
        }
    };
}

该代码向我返回以下错误:

Error:(45, 17) error: method putStringArrayList in class Bundle cannot be applied to given types;
required: String,ArrayList<String>
found: String,List<RssItem>
reason: actual argument List<RssItem> cannot be converted to ArrayList<String> by method invocation conversion
4

1 回答 1

1

您可以将您的列表声明为 ArrayList:

private ArrayList<RssItem> items;

在你的onReceiveResult方法中使用arraylist而不是list:

items = (ArrayList<RssItem>) resultData.getSerializable(RssIntentService.ITEMS);

那么代码不应该抛出任何错误。

于 2015-09-17T20:17:44.780 回答