-2

radiogroup 안에 3 개의 라디오 버튼이 있는데 사용자가 라디오 버튼을 선택하면 사용자가 다른 버튼 (사용자가 앱을 닫을 지 여부)을 확인할 때까지 체크해야합니다. sharedPreferances를 사용하여 선택된 체크 박스 값을 저장하고 액티비티가로드 될 때 다시 검색하지만 체크 박스를 선택하기위한 액티비티를로드 할 때 오류가 발생합니다. 아래는 제 코드입니다. 이 오류를 해결할 수 있도록 도와주세요.안드로이드 응용 프로그램에 오류가 발생했습니다

Activity.java :

public static SharedPreferences pref; 
public static String lang; 
public static String chk; 
public static RadioButton gujarati; 
public static RadioButton hindi; 
public static RadioButton english; 
public static EditText txtV; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.select_language); 
// 
// String chk = pref.getString("key_name", null); 
// if(chk=="Gujarati"){ 
//  gujarati.setChecked(true); 
// } 
// else if(chk=="Hindi"){ 
//  hindi.setChecked(true); 
// } 
// else{ 
    // english.setChecked(true); 
    //} 
    //editor.remove("key_name3"); // will delete key key_name3 
    //editor.remove("key_name4"); // will delete key key_name4 

    // Save the changes in SharedPreferences 
    //editor.commit(); // commit changes 
    //editor.clear(); 
    //editor.commit(); 

    RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1); 
    gujarati = (RadioButton) findViewById(R.id.radio0); 
    hindi = (RadioButton) findViewById(R.id.radio1); 
    english = (RadioButton) findViewById(R.id.radio2); 
    txtV = (EditText) findViewById(R.id.editText1); 

    //int radio_selected = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE).getInt("my_selected_radio",0); 
    //int radio_selected = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE).edit().putInt("my_selected_radio",selectedValue).commit(); 
    chk = pref.getString("key_name", null); 

    if(chk == "Gujarati"){ 
     gujarati.setChecked(true); 
    } 
    if(chk == "Hindi"){ 
     hindi.setChecked(true); 
    } 
    if(chk == "English"){ 
     english.setChecked(true); 
    } 

    group.setOnCheckedChangeListener(new OnCheckedChangeListener(){ 

     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 
      // TODO Auto-generated method stub 
      if(checkedId == R.id.radio0) { 
       lang = "Gujarati"; 
       pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
       Editor editor = pref.edit(); 
       editor.putString("key_name", lang); 
       editor.commit(); 
       chk = pref.getString("key_name", null); 
       txtV.setText(chk); 

      } else if(checkedId == R.id.radio1) { 
       lang = "Hindi"; 
       pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
       Editor editor = pref.edit(); 
       editor.putString("key_name", lang); 
       editor.commit(); 
       chk = pref.getString("key_name", null); 
       txtV.setText(chk); 
      } else { 
       lang = "English"; 
       pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
       Editor editor = pref.edit(); 
       editor.putString("key_name", lang); 
       editor.commit(); 
       chk = pref.getString("key_name", null); 
       txtV.setText(chk); 

      } 

     } 

    }); 

activity.xml :

<RadioGroup 
    android:id="@+id/radioGroup1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/textView1" 
    android:layout_marginTop="25dp" > 

    <RadioButton 
     android:id="@+id/radio0" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="RadioButton" /> 

    <RadioButton 
     android:id="@+id/radio1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="RadioButton" /> 

    <RadioButton 
     android:id="@+id/radio2" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="RadioButton" /> 
</RadioGroup> 


<EditText 
    android:id="@+id/editText1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/radioGroup1" 
    android:layout_below="@+id/radioGroup1" 
    android:layout_marginLeft="15dp" 
    android:ems="10" > 

    <requestFocus /> 
</EditText> 

로그 캣 :

01-05 04:21:35.055: E/AndroidRuntime(2665): FATAL EXCEPTION: main 
01-05 04:21:35.055: E/AndroidRuntime(2665): Process: com.finaldbparse.finaldbparse, PID: 2665 
01-05 04:21:35.055: E/AndroidRuntime(2665): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.finaldbparse.finaldbparse/com.finaldbparse.finaldbparse.SelectLanguage}: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.ActivityThread.access$800(ActivityThread.java:144) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.os.Handler.dispatchMessage(Handler.java:102) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.os.Looper.loop(Looper.java:135) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.ActivityThread.main(ActivityThread.java:5221) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at java.lang.reflect.Method.invoke(Native Method) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at java.lang.reflect.Method.invoke(Method.java:372) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
01-05 04:21:35.055: E/AndroidRuntime(2665): Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at com.finaldbparse.finaldbparse.SelectLanguage.onCreate(SelectLanguage.java:55) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.Activity.performCreate(Activity.java:5933) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 
01-05 04:21:35.055: E/AndroidRuntime(2665):  ... 10 more 
+1

logcat은 어디에 있습니까? –

+0

로그를 추가하십시오 – VicJordan

+0

또한 logcat 오류를 게시하십시오. – GrIsHu

답변

1

onCheckedChangeListener 이벤트를 구현 했으므로 활동이 시작될 때마다 항상 자동으로 호출됩니다. 그래서 귀하의 sharedpreference 값이 정확하지만 문제가 발생하지만 바로 그 후 귀하의 CheckedChangeListener 귀하의 환경 설정에서 가지고있는 값을 가져옵니다 그래서 당신은 잘못된 결과를 얻는 호출됩니다.

그래서 다른 라디오 버튼을 확인할 때마다 이전 값을 제거한 것입니다.

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.select_language); 

    group.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 
      // TODO Auto-generated method stub 
      pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
      Editor editor1 = pref.edit(); 
      editor1.remove("key_name"); 
      if (checkedId == R.id.radio0) { 
       lang = "Gujarati"; 
       pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
       Editor editor = pref.edit(); 
       editor.putString("key_name", lang); 
       editor.commit(); 
       // chk = pref.getString("key_name", null); 
       txtV.setText(lang); 

      } else if (checkedId == R.id.radio1) { 
       lang = "Hindi"; 
       pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
       Editor editor = pref.edit(); 
       editor.putString("key_name", lang); 
       editor.commit(); 
       // chk = pref.getString("key_name", null); 
       txtV.setText(lang); 
      } else if (checkedId == R.id.radio2) { 
       lang = "English"; 
       pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
       Editor editor = pref.edit(); 
       editor.putString("key_name", lang); 
       editor.commit(); 
       // chk = pref.getString("key_name", null); 
       txtV.setText(lang); 

      } 
     } 

    }); 

    pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
    chk = pref.getString("key_name", null); 
    System.err.println("Get value is=====" + chk); 
    if (chk != null) { 
     if (chk.equals("Gujarati")) { 
      gujarati.setChecked(true); 
     } 
     if (chk.equals("Hindi")) { 
      hindi.setChecked(true); 
     } 
     if (chk.equals("English")) { 
      english.setChecked(true); 
     } 
    } 
} 
+1

'문자열 변수 값을 비교하고 싶다면 if (chk == "Gujarati")'는 유효하지 않습니다. –

+0

코드를 추가 했는데도 응용 프로그램을 다시 시작할 때 체크 된 라디오 버튼에 대한 모든 상태를 잊어 버렸습니다. –

+0

도와주세요. –

1

당신은

0123에서 NPE 때문에 pref=NULL있어

chk = pref.getString("key_name", null);

는 사용 전에 pref 초기화합니다.

pref = getApplicationContext().getSharedPreferences("MyPref", 0); in onCreate(....) 
3
여기

같이 수행

CHK = pref.getString ("KEY_NAME", NULL);

1. 당신은 SharedPreferencespref 인스턴스를 초기화하지만 getString 메소드를 호출하지 않습니다. 로 수행

pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
chk = pref.getString("key_name", null); 

2 대신 ==

3. 다음 필요 다시 같은 현재 당신이 setOnCheckedChangeListener

에서 일을 초기화하지 않으려면 onCreate 방법 pref 초기화의 문자열 비교를 사용 String.equals
관련 문제