2013-08-01 7 views
0

"InitialPreferences"활동에서 sharedpreferences를 사용하여 일부 영구 데이터를 저장하려고하는이 코드는 "StartScreen"활동이 다음에 응용 프로그램이 시작될 때 저장된 환경 설정을 검색하고 사용자를 "InitialPreferences"또는 "MainActivity"로 변경하십시오. 제 문제는 데이터가 저장되지 않고 문제가 보이지 않는다는 것입니다. 문제를 직접 알려주고 잘못된 것을 보여줄 수 있습니까?SharedPreferences가 데이터를 저장하거나로드하지 않음

감사

StartScreen 활동 :

public class StartScreen extends Activity { 

CountDownTimer waitTimer; 
public static final String APP_PREFERENCES = "AppPrefs"; 
SharedPreferences settings; 
SharedPreferences.Editor prefEditor; 

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

    settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE); 
    // prefEditor = settings.edit(); 

    waitTimer = new CountDownTimer(5000, 300) { 

     public void onTick(long millisUntilFinished) { 
      //called every 300 milliseconds, which could be used to 
      //send messages or some other action 
     } 
     public void onFinish() { 
      //After 5000 milliseconds (5 sec) finish current 
      //if you would like to execute something when time finishes 
      getPreferences(); 
     } 
    }.start(); 
} 

private void getPreferences() { 
    // TODO Auto-generated method stub 
    String UserName = settings.getString("UserName", ""); 

    if (UserName != null) { 
     // the key does not exist 
       Intent intent=new   Intent(StartScreen.this,InitialPreferences.class); 
       startActivity(intent); 
      } 
    if (UserName.equals("UserName")){ 
     // handle the value 
       Intent intent=new Intent(StartScreen.this,MainActivity.class); 
       startActivity(intent); 
    }  
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.start_screen, menu); 
    return true; 
} 
} 

InitialPreferences 활동 :

public class InitialPreferences extends Activity implements OnClickListener { 

EditText editText1; 
Button button1; 
TextView textView1; 
RadioGroup radioGroup; 
RadioButton radioPosistionButton; 

public static final String APP_PREFERENCES = "AppPrefs"; 
SharedPreferences settings; 
SharedPreferences.Editor prefEditor; 

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

    textView1 = (TextView)findViewById(R.id.textView1); 
    editText1 = (EditText)findViewById(R.id.editText1); 
    button1 = (Button)findViewById(R.id.button1); 
    radioGroup = (RadioGroup) findViewById(R.id.radioGroup); 

    settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE); 
     prefEditor = settings.edit(); 

    LoadPreferences(); 
} 

@Override 
public void onClick(View v) { 

SavePreferences(); 
LoadPreferences(); 
} 

private void SavePreferences() { 
// TODO Auto-generated method stub 

String Uname_input = editText1.getText().toString(); 
int checkedButton = radioGroup.getCheckedRadioButtonId(); 
prefEditor.clear(); 
prefEditor.putString("UserName", Uname_input); 
prefEditor.putInt("posistion", checkedButton); 
prefEditor.apply(); 
prefEditor.commit(); 
} 

private void LoadPreferences(){ 

String UserName = settings.getString("UserName", ""); 
editText1.setText(UserName + ""); 
Toast.makeText(getApplicationContext(), UserName, Toast.LENGTH_SHORT).show(); 
} 
} 
+0

실제로 InitialPreferences 활동을 본 적이 있습니까? 너처럼 보이지 않는다. –

+0

내가 왜 ... 왜 안할거야? –

+0

원래 약간의 조건문을 잘못 읽었지만 아래의 대답은 여전히 ​​적용됩니다. –

답변

1

첫 번째 문제는 (UserName != null) 항상 사실이다. UserNameString UserName = settings.getString("UserName", "");으로 받고 있습니다. 기본값은 빈 문자열입니다. 기본 설정을 찾을 수없는 경우 설정이 null을 반환하도록하려면 settings.getString("UserName", null)으로 전화해야합니다.

두 번째 문제는 사용자의 InitialPreferences 활동의 모든보기에서 결코 setOnClickListener(this)으로 전화하지 않는다는 것입니다. 따라서 onClick()은 호출되지 않으며 아무 일도 발생하지 않습니다. onCreate()button1.setOnClickListener(this)으로 전화하기를 원합니다.

+0

안녕하세요, 답변 주셔서 감사합니다.이 사이트는 항상 초보자에게 도움이됩니다. 이제 settings.getString ("UserName", null)으로 변경 한 후 nullpointerexception이 발생합니까? 어떤 생각? 왜?. 클릭리스트를 찾아 주셔서 감사합니다. –

+0

안녕하세요. 왜 그것이 nullpointer를 던지고 그것을 해결했는지 알 수없는 프로젝트를 청소했습니다. 나는 또한 (UserName.equals ("UserName")) {if (UserName.equals (UserName)) { –

관련 문제