使用SharedPreference保存字符串数组

时间:2013-11-03 21:35:09

标签: android arrays sharedpreferences android-logcat

我有4个数组,我希望能够在内部保存到设备中:

String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];

我的完整onCreate就在这里:

package biz.midl.debtsnowball;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class DebtList<T> extends Activity {

    String[] debtName = new String[10];
    String[] debtAmount = new String[10];
    String[] debtRate = new String[10];
    String[] debtPayment = new String[10];

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.debtlist);

        Bundle extras = getIntent().getExtras();

        int trigger = 0;

        //Load Data
        SharedPreferences sharedPrefs= getSharedPreferences("chaosdata", 0);

        Set<String> retrievedName = sharedPrefs.getStringSet("debtNames", null);
        List<String> list = new ArrayList<String>(retrievedName);   //Line 41 where it appears the issues is originating.
        for(int i = 0; i < list.size(); i++) debtName[i] = list.get(i);
        //End Load

        for (int i=0;i<10;i++)
        {
            if (debtName[i] == null && extras != null && trigger==0)
            {
                debtName[i] = extras.getString("debtName");
                debtAmount[i] = extras.getString("debtAmount");
                debtRate[i] = extras.getString("debtRate");
                debtPayment[i] = extras.getString("debtPayment");
                trigger = 1;
            }
        }

        TableLayout tl = (TableLayout) findViewById(R.id.debtListTableView);

        for (int i=0;i<10;i++)
        {
            if (debtName[i] != null)
            {

                TableRow tr = new TableRow(this);
                TextView tv0 = new TextView(this);
                TextView tv1 = new TextView(this);
                TextView tv2 = new TextView(this);
                TextView tv3 = new TextView(this);
                TableRow.LayoutParams trlp = new TableRow.LayoutParams();
                //LayoutParams tvlp = new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f);
                tv0.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                tv1.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                tv2.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                tv3.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                /**
                tv0.setLayoutParams(tvlp);
                tv1.setLayoutParams(tvlp);
                tv2.setLayoutParams(tvlp);
                **/
                trlp.span = 3;
                tr.setLayoutParams(trlp);
                tv0.setText("" + debtName[i]);
                tv1.setText("" + debtAmount[i]);
                tv2.setText("" + debtPayment[i]);
                tv3.setText("Holder");
                tr.addView(tv0);
                tr.addView(tv1);
                tr.addView(tv2);
                tr.addView(tv3);
                tl.addView(tr);
            }
        }


        List listName = Arrays.asList(debtName);
        Set setName = new HashSet(listName);

        //Save Data
        SharedPreferences.Editor editor= sharedPrefs.edit();
        editor.putStringSet("debtNames", setName);
        editor.commit();

        //End Save
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.debt_list, menu);
        return true;
    }

}

这一次用于保存和加载我的数组。当我进行用户数据擦除时,它停止工作。以下是LogCat:

11-03 20:47:31.485: V/TLINE(516): new: android.text.TextLine@408e0738
11-03 20:47:32.005: V/TLINE(516): new: android.text.TextLine@40907608
11-03 20:47:34.745: D/dalvikvm(516): GC_CONCURRENT freed 127K, 4% free 9004K/9287K, paused 6ms+12ms
11-03 20:47:37.336: D/AndroidRuntime(516): Shutting down VM
11-03 20:47:37.336: W/dalvikvm(516): threadid=1: thread exiting with uncaught exception (group=0x40014760)
11-03 20:47:37.356: E/AndroidRuntime(516): FATAL EXCEPTION: main
11-03 20:47:37.356: E/AndroidRuntime(516): java.lang.RuntimeException: Unable to start activity ComponentInfo{biz.midl.debtsnowball/biz.midl.debtsnowball.DebtList}: java.lang.NullPointerException
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.app.ActivityThread.access$1500(ActivityThread.java:122)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.os.Looper.loop(Looper.java:132)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.app.ActivityThread.main(ActivityThread.java:4025)
11-03 20:47:37.356: E/AndroidRuntime(516):  at java.lang.reflect.Method.invokeNative(Native Method)
11-03 20:47:37.356: E/AndroidRuntime(516):  at java.lang.reflect.Method.invoke(Method.java:491)
11-03 20:47:37.356: E/AndroidRuntime(516):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
11-03 20:47:37.356: E/AndroidRuntime(516):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
11-03 20:47:37.356: E/AndroidRuntime(516):  at dalvik.system.NativeStart.main(Native Method)
11-03 20:47:37.356: E/AndroidRuntime(516): Caused by: java.lang.NullPointerException
11-03 20:47:37.356: E/AndroidRuntime(516):  at java.util.ArrayList.<init>(ArrayList.java:97)
11-03 20:47:37.356: E/AndroidRuntime(516):  at biz.midl.debtsnowball.DebtList.onCreate(DebtList.java:41)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
11-03 20:47:37.356: E/AndroidRuntime(516):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
11-03 20:47:37.356: E/AndroidRuntime(516):  ... 11 more
11-03 20:47:38.876: I/Process(516): Sending signal. PID: 516 SIG: 9

1 个答案:

答案 0 :(得分:1)

将数组转换为集合并直接存储:

SharedPreferences.Editor editor= sharedPref.edit();
Set<T> debtSet = new HashSet<T>(Arrays.asList(debtNames));
editor.putStringSet("debtNames", debtSet);

检索时使用debtSet.toArray()

要检索:

debtNames = sharedPrefs.getStringSet("debtNames").toArray();

debtSet = sharedPrefs.getStringSet("debtNames");
debtNames = debtSet.toArray();

通常,阵列很难使用。您可以考虑将Set用于所有内容,尤其是ArrayList<String>

要存储Arraylist而不必将其转换为Set /从editor.putString("debtNames", ObjectSerializer.serialize(debtNames)); 转换:

debtNames

ArrayList<String>ArrayList

的位置

要检索debtNames = (ArrayList<String) ObjectSerializer.deserialize(prefs.getString("debtNames", ObjectSerializer.serialize(new ArrayList<String>())));

ObjectSerializer

您可以获取editor.commit() here或使用其他序列化类。

请注意,我使用新的Arraylist作为默认值。

至于你的空指针,我看不到你在哪里调用ShardPreference。如果您不这样做,您的值永远不会保存到{{1}}。