如何在SharedPreferences中使用getStringSet()方法?

时间:2014-01-02 10:10:43

标签: android android-fragments sharedpreferences hashset

我的应用中有两个不同的活动。第一个活动包含3个片段,其中包含按钮以向SharedPreferences添加字符串,第二个活动用于显示添加的所有字符串。由于我添加了多个字符串,因此我发现必须使用getStringSet()方法。我的片段代码中没有任何错误,但由于ClassCastException,它在调试模式下崩溃。根据堆栈,问题是由于getStringSet。堆栈消息是:

  

“SharedPreferencesImpl.getStringSet(String,Set)line:234”)

这是片段中的代码:

public class FirstFragment extends Fragment {

    public static final String filename = "imagine_dragons";
    SharedPreferences someData;
    Button bMer;
    String merStr = "string from first fragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_first, container,
                false);

        bMer = (Button) rootView.findViewById(R.id.bMer);
        bMer.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                 someData = getActivity().getSharedPreferences(filename,0);
                 SharedPreferences.Editor editor = someData.edit();
                 Set<String> sharedString = someData.getStringSet("sharedString", new HashSet<String>());
                 sharedString.add("merStr");
                 editor.putStringSet("sharedString", sharedString);
                 editor.commit();
            }
        });
        return rootView;
    }
}

这是第二项活动的代码。这是关于setText的另一个挑战。由于我们在SharedPreference中使用字符串集,因此我们不能使用setText方法来显示字符串集。因此,此代码包含错误(EDITED):

public class SecAct extends Activity {
   public static final String filename = "imagine_dragons";
   SharedPreferences someData;
   TextView tvSec;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      setContentView(R.layout.sec);
      tvSec = (TextView) findViewById(R.id.tvSec);
            someData = getSharedPreferences(filename, 0);
    Set<String> sharedString=someData.getStringSet("sharedString", new HashSet<String>());
    if(sharedString != null){

        Iterator<String> iterator = sharedString.iterator();

        while(iterator.hasNext()){

            String id = iterator.next();

            int start = id.indexOf("[") + 1;
            int end = id.indexOf("]")-1;

            String items = String.copyValueOf(id.toCharArray(), start, end);


        }
    }
   }
}

我的minSDK值为14,因此它支持getStringSet()方法。

这是LogCat:

    01-02 16:02:39.727: W/asset(7824): Copying FileAsset 0x57249048 (zip:/data/app/com.example.ikincitaslak-1.apk:/resources.arsc) to buffer size 9272 to make it aligned.
01-02 16:02:39.732: W/ActivityThread(7824): Application com.example.ikincitaslak is waiting for the debugger on port 8100...
01-02 16:02:43.512: E/(7824): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
01-02 16:02:49.827: W/dalvikvm(7824): threadid=1: thread exiting with uncaught exception (group=0x40f33a08)
01-02 16:02:49.847: E/AndroidRuntime(7824): FATAL EXCEPTION: main
01-02 16:02:49.847: E/AndroidRuntime(7824): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ikincitaslak/com.example.ikincitaslak.Sepet}: java.lang.StringIndexOutOfBoundsException: length=9; regionStart=0; regionLength=-2
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2463)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.ActivityThread.access$600(ActivityThread.java:162)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.os.Looper.loop(Looper.java:158)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.ActivityThread.main(ActivityThread.java:5751)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at java.lang.reflect.Method.invokeNative(Native Method)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at java.lang.reflect.Method.invoke(Method.java:511)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at dalvik.system.NativeStart.main(Native Method)
01-02 16:02:49.847: E/AndroidRuntime(7824): Caused by: java.lang.StringIndexOutOfBoundsException: length=9; regionStart=0; regionLength=-2
01-02 16:02:49.847: E/AndroidRuntime(7824):     at java.lang.String.failedBoundsCheck(String.java:587)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at java.lang.String.<init>(String.java:419)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at java.lang.String.copyValueOf(String.java:716)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at com.example.ikincitaslak.Sepet.onCreate(Sepet.java:36)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.Activity.performCreate(Activity.java:5165)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1103)
01-02 16:02:49.847: E/AndroidRuntime(7824):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2419)
01-02 16:02:49.847: E/AndroidRuntime(7824):     ... 11 more

2 个答案:

答案 0 :(得分:1)

TextView没有setText方法,该方法将Set<Strings>作为参数。 如果您希望集合中的所有字符串都显示在TextView中,则必须创建一个字符串,该字符串是该集合的组合。

有很多关于如何做这件事的教程:one such method

答案 1 :(得分:1)

根据您的解释,听起来您已经有一个映射到"sharedString"的值,它不是字符串集。因此,当您运行someData.getStringSet()时,您会获得ClassCastException

原因可能是在应用程序的生命周期中的某个时刻,它正在为"sharedString"保存不同类型的值,这仍然是因为您正在更新相同的现有应用程序。我建议您从正在测试的设备/模拟器上卸载应用程序,然后重试。