TQC-208 設定偏好、並讀取偏好資料

  • 2195
  • 0

TQC-208 設定偏好、並讀取偏好資料

這是TQC的208題,

程式碼為自行撰寫,

僅供參考。

 

主要練習設定偏好、跟讀取偏好資料。

 


package COM.TQC.GDD02;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class GDD02 extends Activity {
	
    	
	public static final String PREF_NAME = "GDA02_PREF";
	  public static final String key01 = "key01";
	  public static final String key02 = "key02";
	  public static final String key03 = "key03";
	  private Button BtnEnd;
	  private EditText EditText01;
	  private EditText EditText02;
	  private EditText EditText03;
	  
	  public void onCreate(Bundle paramBundle)
	  {
	    super.onCreate(paramBundle);
	    setContentView(R.layout.main);
	    
	    findview();
	    setlinsenter();
	    setpreferences();	    
	    
	  }
	  
	  public void findview()
	  {
		  EditText01 = (EditText)findViewById(R.id.editText1);
		  EditText02= (EditText)findViewById(R.id.editText2);
		  EditText03= (EditText)findViewById(R.id.editText3);
		  BtnEnd = (Button)findViewById(R.id.button1);
	  }
	  
	  public void setlinsenter()
	  {
		  BtnEnd.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				GDD02.this.finish();
			}});
	  }
	  
	  public void setpreferences()
	  {
		  SharedPreferences settings = getSharedPreferences(PREF_NAME, 0);
	        String str1 = settings.getString(key01, "");
	        String str2 = settings.getString(key02, "");
	        String str3= settings.getString(key03, "");
	        if(! "".equals(str1))
	        {
	        	EditText01.setText(str1);
	        }
	        if(! "".equals(str1))
	        {
	        	EditText02.setText(str2);
	        }
	        if(! "".equals(str3))
	        {
	        	EditText03.setText(str3);
	        }  
	  }
	  
	  
	    @Override
	    protected void onPause(){
	            super.onPause();
	            // Save user preferences. use Editor object to make changes.
	            SharedPreferences settings = getSharedPreferences(PREF_NAME, 0);
	            settings.edit()
	              .putString(key01, EditText01.getText().toString())
	              .putString(key02, EditText02.getText().toString())
	              .putString(key03, EditText03.getText().toString())
	              .commit();
	    }    
	    
	    @Override
	    protected void onStop()
	    {
	      super.onStop();
          //SharedPreferences settings = getSharedPreferences(PREF_NAME, 0);
          //settings.edit().putString(key01, EditText01.getText().toString()).commit();
          //settings.edit().putString(key02, EditText02.getText().toString()).commit();
          //settings.edit().putString(key03, EditText03.getText().toString()).commit();
	    }
}

 

 

自我LV~