1. 程式人生 > >SharedPreferences+登入的簡單使用

SharedPreferences+登入的簡單使用

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class TwoActivity extends Activity {

private EditText editText1,editText2;
private CheckBox ch_jz,ch_zd;

private Button button;
private SharedPreferences sharedPreferences;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.two_acticity);
    
    //獲取控制元件
    editText1 = (EditText) findViewById(R.id.et1);
    editText2 = (EditText) findViewById(R.id.et2); 
    ch_jz = (CheckBox) findViewById(R.id.ch_jz);
    ch_zd = (CheckBox) findViewById(R.id.ch_zd);
    button = (Button) findViewById(R.id.btn_dl);
    
    //在SD中建立sharedPreferences 的檔案儲存資料   檔案為xml形式
    sharedPreferences = getSharedPreferences("zhao", MODE_PRIVATE);
    
    //獲取isch_jz   裡面儲存了是否點選了記住密碼
    boolean isch_jz = sharedPreferences.getBoolean("isch_jz", false); 
    //如果檔案中沒有第一個引數isch_jz,則返回第二個引數false
    
   //獲取檔案裡的賬號密碼
    String admin = sharedPreferences.getString("admin", "");
    String pwd = sharedPreferences.getString("pwd", "");
    
    //判斷isch_jz,如果為true則記住密碼
    if (isch_jz) {
		editText1.setText(admin);
		editText2.setText(pwd);
		ch_jz.setChecked(true);
	}
    
  //自動登入
    boolean isch_zd = sharedPreferences.getBoolean("isch_zd", false);
    if (isch_zd) {
    //跳轉頁面
		startActivity(new Intent(TwoActivity.this,ThreeActivity.class));
		finish();
	}
    
    button.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
		//獲取輸入框的值並轉換成字串
			String admin = editText1.getText().toString().trim();
			String pwd = editText2.getText().toString().trim();
			
		//判斷登入前是否選中記住密碼
			if (ch_jz.isChecked()) {
			//獲取事物
				Editor editor2 = sharedPreferences.edit();
			//儲存賬號密碼
				editor2.putBoolean("isch_jz", true); //記住密碼儲存true
				editor2.putString("admin", admin);
				editor2.putString("pwd", pwd);
				//提交
				editor2.commit();
			}
		//判斷登入前是否選中記住自動登入
			if (ch_zd.isChecked()) {
				Editor editor2 = sharedPreferences.edit();
				editor2.putBoolean("isch_zd", true);
				editor2.commit();
			}
			startActivity(new Intent(TwoActivity.this,ThreeActivity.class));
			finish();
			
		}
	});
    
}

}