我正在尝试将arrayadapter保存到共享首选项

时间:2016-01-21 15:40:55

标签: java android

我正在尝试将ArrayAdapter保存到共享首选项。我可以使用此代码恢复一个字符串,但只有一个,我无法恢复整个ArrayAdapter

package com.example.eduleito.listacompras;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

  private EditText edt_item;
  private Button btn_limpar;
  private ImageButton btn_adcionar;
  private ListView lst_item;
  private ArrayAdapter adp_item;

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

    edt_item = (EditText) findViewById(R.id.edt_item);
    btn_limpar = (Button) findViewById(R.id.btn_limpar);
    btn_adcionar = (ImageButton) findViewById(R.id.btn_adcionar);
    lst_item = (ListView) findViewById(R.id.lst_item);
    btn_adcionar.setOnClickListener(this);
    btn_limpar.setOnClickListener(this);
    adp_item = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
    lst_item.setAdapter(adp_item);

    loadSavedPreferences();

  }

  private void loadSavedPreferences(){
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String item = sharedPreferences.getString("storeditem", "");
    adp_item.add(item);
   }

  private void savePreferences(String key, String value){
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
  }

  @Override
  public void onClick(View v) {

    if (v == btn_adcionar) {
      String item = edt_item.getText().toString();
      adp_item.add(item);
      savePreferences("storeditem", item);
      edt_item.setText("");
    } else if (v == btn_limpar) {
      adp_item.clear();
    }

  }
}

1 个答案:

答案 0 :(得分:0)

谷歌: Storage Options on developer.android.com

SharedPreferences类提供了一个通用框架,允许您保存和检索原始数据类型的持久键值对