android - 使用 SharedPreference 保存字符串数组

标签 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

最佳答案

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

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

其中 debtNamesArrayList<String>

检索 ArrayList :

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

您可以获得 ObjectSerializer here 或使用其他一些序列化类。

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

至于你的空指针,我看不到你在哪里调用 editor.commit() 。如果您不这样做,您的值将永远不会保存到 ShardPreference

关于android - 使用 SharedPreference 保存字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19758432/

相关文章:

android - 如何将自定义适配器中的数组列表保存到 SharedPreference

android - 比较 2 个变量

java - 如何将 json 数据存储到共享首选项?

java - Android 覆盖库/库中的文件

java - 当我打开 map Activity 时自动打开 GPS

javascript - 我们如何根据 Node js中的另一个对象数组值对对象数组进行排序

c - 如何在 C 编程代码中从文本文件中读取数据数组?

c++ - 使用 initializer_list 初始化数组?

Android:元数据也存在于

android - Xamarin Android 自定义 ListView 错误