保存列表数组

时间:2015-12-31 12:45:51

标签: java android sharedpreferences

我正在创建一个应用,用户可以输入他们的分数,然后进入列表视图。我希望strArr变量在退出时保存,因此当用户重新打开应用程序时,分数仍然存在。在保存int之前,我已经问了一个类似的问题但是,我很难用ArrayList做同样的事情。这是我的代码,目前在发布时崩溃。

public class AltonDuel extends Activity {

private Button bt;
private ListView lv;
private ArrayList<String> strArr;
private ArrayAdapter<String> adapter;
private EditText et;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alton_duel);
    bt = (Button) findViewById(R.id.button);
    lv = (ListView) findViewById(R.id.listView);
    et = (EditText) findViewById(R.id.editText);
    final Calendar cal = Calendar.getInstance();
    final int dd = cal.get(Calendar.DAY_OF_MONTH);
    final int mm = cal.get(Calendar.MONTH);
    final int yy = cal.get(Calendar.YEAR);

    int rideCountFile;

    final SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("AltonDuelCount", Context.MODE_PRIVATE);

    strArr = (ArrayList<String>) sharedPref.getStringSet("stringArr", new HashSet<String>());


    strArr = new ArrayList<String>();
    adapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1, strArr);
    lv.setAdapter(adapter);
    bt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            strArr.add(dd + "-" + mm + "-" + yy + "    |     " + et.getText().toString());
            adapter.notifyDataSetChanged();

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putStringSet("stringArr", (Set<String>) strArr);
            editor.commit();

        }
    });
}}

更新代码:

public class AltonDuel extends Activity {

private Button bt;
private ListView lv;
private ArrayList<String> strArr;
private ArrayAdapter<String> adapter;
private EditText et;
ArrayList<String> data;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alton_duel);
    bt = (Button) findViewById(R.id.button);
    lv = (ListView) findViewById(R.id.listView);
    et = (EditText) findViewById(R.id.editText);
    final Calendar cal = Calendar.getInstance();
    final int dd = cal.get(Calendar.DAY_OF_MONTH);
    final int mm = cal.get(Calendar.MONTH);
    final int yy = cal.get(Calendar.YEAR);


    int rideCountFile;

    final SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("AltonDuelCount", Context.MODE_PRIVATE);

    data = (ArrayList<String>) sharedPref.getStringSet("stringArr", new HashSet<String>());
    Set<String> data = new HashSet<String>(strArr);

    strArr = new ArrayList<String>();
    adapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1, strArr);
    lv.setAdapter(adapter);
    bt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            strArr.add(dd + "-" + mm + "-" + yy + "    |     " + et.getText().toString());
            adapter.notifyDataSetChanged();


            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putStringSet("stringArr", (Set<String>) strArr);
            editor.commit();

        }
    });
}}

3 个答案:

答案 0 :(得分:1)

以下是将arraylist保存到sharedpreference的示例代码

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mandaptak.android.Models.MatchesModel;
import com.mandaptak.android.Models.Participant;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Prefs {

  public static final String MANDAPTAK_SHARED_PREFERENCES_FILE = "mandapTak";

  public static String MATCHES = "matches";

  public static SharedPreferences getPrefs(Context context) {
    return context.getSharedPreferences(MANDAPTAK_SHARED_PREFERENCES_FILE, Context.MODE_MULTI_PROCESS);
  }


  public static ArrayList<MatchesModel> getMatches(Context context) {
    String json = getPrefs(context).getString(MATCHES, null);
    Type type = new TypeToken<ArrayList<MatchesModel>>() {
    }.getType();
    return new Gson().fromJson(json, type);
  }

  public static void setMatches(Context context, ArrayList<MatchesModel> list) {
    getPrefs(context).edit().putString(MATCHES, new Gson().toJson(list)).commit();
  }
}
  

这里我使用getter和setter来存储和从共享首选项中获取数组列表,其中MatchesModel是我的自定义模型类,包含要存储的属性。

答案 1 :(得分:0)

您正在尝试将ArrayList强制转换为Set。你不能这样做。你可以做的是使用现有的ArrayList创建一个新的HashSet(或Set的任何实现)。像这样:

如果要从SharedPreferences检索数据:

Set<String> data = sharedPref.getStringSet("stringArr", new HashSet<String>());
ArrayList<String> myArrayList = new ArrayList<String>(data);

当您想保存数据时:

Set<String> data = new HashSet<String>(strAttr);
sharedPrefEditor.putStringSet("stringArr", data);

答案 2 :(得分:0)

以下是一些代码来获取可序列化对象并将其写入文件,这可能就是您所需要的。使用和ArrayList测试它,它工作正常。您也可以修改输出,而不是将其写入文件,您可以使用extras或其包将其传递给活动。

读取已包含序列化对象的文件:

String ser = SerializeObject.ReadSettings(act, "myobject.dat");
if (ser != null && !ser.equalsIgnoreCase("")) {
    Object obj = SerializeObject.stringToObject(ser);
    // Then cast it to your object and 
    if (obj instanceof ArrayList) {
        // Do something
        give = (ArrayList<String>)obj;
    }
}

将对象写入文件使用:

String ser = SerializeObject.objectToString(give);
if (ser != null && !ser.equalsIgnoreCase("")) {
    SerializeObject.WriteSettings(act, ser, "myobject.dat");
} else {
    SerializeObject.WriteSettings(act, "", "myobject.dat");
}

序列化对象的类:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;

import android.content.Context;
import android.util.Base64InputStream;
import android.util.Base64OutputStream;
import android.util.Log;

/**
 * Take an object and serialize and then save it to preferences
 * @author John Matthews
 *
 */
public class SerializeObject {
    private final static String TAG = "SerializeObject";

    /**
     * Create a String from the Object using Base64 encoding
     * @param object - any Object that is Serializable
     * @return - Base64 encoded string.
     */
    public static String objectToString(Serializable object) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            new ObjectOutputStream(out).writeObject(object);
            byte[] data = out.toByteArray();
            out.close();

            out = new ByteArrayOutputStream();
            Base64OutputStream b64 = new Base64OutputStream(out,0);
            b64.write(data);
            b64.close();
            out.close();

            return new String(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Creates a generic object that needs to be cast to its proper object
     * from a Base64 ecoded string.
     * 
     * @param encodedObject
     * @return
     */
    public static Object stringToObject(String encodedObject) {
        try {
            return new ObjectInputStream(new Base64InputStream(
                    new ByteArrayInputStream(encodedObject.getBytes()), 0)).readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Save serialized settings to a file
     * @param context
     * @param data
     */
    public static void WriteSettings(Context context, String data, String filename){ 
        FileOutputStream fOut = null; 
        OutputStreamWriter osw = null;

        try{
            fOut = context.openFileOutput(filename, Context.MODE_PRIVATE);       
            osw = new OutputStreamWriter(fOut); 
            osw.write(data); 
            osw.flush(); 
            //Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
        } catch (Exception e) {       
            e.printStackTrace(); 
           // Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
        } 
        finally { 
            try { 
                if(osw!=null)
                    osw.close();
                if (fOut != null)
                    fOut.close(); 
            } catch (IOException e) { 
                   e.printStackTrace(); 
            } 
        } 
    }

    /**
     * Read data from file and put it into a string
     * @param context
     * @param filename - fully qualified string name
     * @return
     */
    public static String ReadSettings(Context context, String filename){ 
        StringBuffer dataBuffer = new StringBuffer();
        try{
            // open the file for reading
            InputStream instream = context.openFileInput(filename);
            // if file the available for reading
            if (instream != null) {
                // prepare the file for reading
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);

                String newLine;
                // read every line of the file into the line-variable, on line at the time
                while (( newLine = buffreader.readLine()) != null) {
                    // do something with the settings from the file
                    dataBuffer.append(newLine);
                }
                // close the file again
                instream.close();
            }

        } catch (java.io.FileNotFoundException f) {
            // do something if the myfilename.txt does not exits
            Log.e(TAG, "FileNot Found in ReadSettings filename = " + filename);
            try {
                context.openFileOutput(filename, Context.MODE_PRIVATE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            Log.e(TAG, "IO Error in ReadSettings filename = " + filename);
        }

        return dataBuffer.toString();
    }

}