2016-01-21 56 views
0

我試圖將ArrayAdapter保存爲共享首選項。我可以得到一個字符串恢復使用此代碼,但只有一個,我無法恢復整個ArrayAdapter我想將arrayadapter保存到sharedpreferences

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

    } 
} 
+0

爲了在SharedPreferences中保存原始數據類型以外的任何東西,請參閱http://stackoverflow.com/questions/7145606/how-android-sharedpreferences-save-store-object – bwegs

回答