2014-09-15 1 views
0

저는 오래 전에 사용자가 실제로 그것을하지 않고 목록 환경 설정에서 선택 사항을 변경하는 방법을 찾아 내려고 노력했습니다. 내가해야 할 일은 목록 환경 설정에서 옵션 중 하나를 무작위로 선택하는 방법입니다. 이 작업은 "무작위 화"확인란을 선택한 경우에만 수행됩니다. 그 부분은 제대로 작동 할 수 있지만 실제 무작위 화가 작동하지 않습니다. 여기에 내가 가진 무엇 : 여기 프로그래밍 방식으로 목록 환경 설정 선택 변경

목록 기본 설정을

<ListPreference 
      android:key="location_preference" 
      android:title="@string/location" 
      android:summary="@string/location_summary" 
      android:entries="@array/locations" 
      android:entryValues="@array/locationValues" 
      android:defaultValue="Canyon" 
      android:dialogTitle="@string/location" /> 

이며, 여기에 내가 뭘 잘못 선택을

protected static void setRandomLocation(Context context){ 
    SharedPreferences preferences = getPreferences(context); 
    Set<String> locs = preferences.getStringSet("location_preference", null); 
    int idx = new Random().nextInt(locs.toArray().length); 
    String random = (String) (locs.toArray()[idx]); 
    preferences.edit().putString("location_preference", random); 
    preferences.edit().commit(); 
} 
private static SharedPreferences getPreferences(Context context) { 
    return PreferenceManager.getDefaultSharedPreferences(context); 
} 

을 랜덤 해낸 방법입니다/방법 해야합니까?

편집 : 그래서 다음과 같이 시도해 보았습니다. 작동하지 않았습니다.

protected static void setRandomLocation(Context context){ 
    Resources res = context.getResources(); 
    SharedPreferences preferences = getPreferences(context); 
    String curr = preferences.getString("location_preference", null); 
    int idx = new Random().nextInt(res.getStringArray(R.array.locationValues).length); 
    String random = (String) (res.getStringArray(R.array.locationValues)[idx]); 
    if(random == curr) 
     setRandomLocation(context); 
    preferences.edit().putString("location_preference", random); 
    preferences.edit().commit(); 
} 
+0

지금은 확인할 수 없습니다. 'if (random == curr)'을'if (random.equals (curr))'로 변경하십시오. return 문을 사용하면 광고를 더 많이 호출하게됩니다. 스택이 푸는 순간 첫 번째 커브가 다시 삽입 될 가능성이 큽니다. – greenapps

+0

idx가'int idx = new Random(). nextInt (6); '에서 얻을 수있는 값을 알려주십시오. – greenapps

+0

0부터 6까지의 임의의 정수, 6을 포함하지 않음 – jxn

답변

0
Set<String> locs = preferences.getStringSet("location_preference", null); 

android:key="location_preference"에 대한 stringset 없습니다.

당신은 미리 정의 된 배열 android:entryValues="@array/locationValues"에서 모든 문자열을 얻고 그들로부터 무작위로 하나를 가지고 하나 "location_preference"를 저장해야
String location = preferences.getString("location_preference", null; 

: 하나의 문자열 만 있습니다.

+0

어떻게하는지 보여주기 위해 신경 써야합니까? – jxn

+0

물론 아닙니다. 직접 시험해보십시오. 코드 작성에 문제가 있으면 우리가 볼 수 있습니다. – greenapps

+0

나는 무언가를 시도했다, 그것이 작동하고보고하는 경우에 나는 볼 것이다. – jxn