使用SharedPreference写入数据

来源:互联网 发布:淘宝网盆栽鲜花 编辑:程序博客网 时间:2024/05/11 00:50

package cn.com.zjh.keepintouch;


import android.app.Activity;

import android.content.Intent;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;


public class RegActivity extends Activity {

private  EditText user;

private  EditText password;

private  EditText  repassword;

private  Button  reg;

private  Button cancel;

private SharedPreferences  sp;


@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.reg_layout);

user=(EditText) this.findViewById(R.id.reg_username);

password=(EditText) this.findViewById(R.id.reg_password);

repassword=(EditText) this.findViewById(R.id.reg_repassword);

reg=(Button) this.findViewById(R.id.reg);

cancel=(Button) this.findViewById(R.id.cancel);

sp=getSharedPreferences("userinfo", MODE_PRIVATE);

reg.setOnClickListener(new  View.OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

String  username=user.getText().toString();

String  pw=password.getText().toString();

String  rpw=repassword.getText().toString();

if(username!=null  &&  pw!=null  &&  rpw!=null  && rpw.equals(pw)){

Editor  editor=sp.edit();

editor.putString("user", username);

editor.putString("password", pw);

editor.commit();

if(editor.commit()){

Toast.makeText(RegActivity.this, R.string.success, Toast.LENGTH_LONG).show();

Intent  intent= new Intent(RegActivity.this, LoginActivity.class);

startActivity(intent);

}else{

Toast.makeText(RegActivity.this, R.string.fail, Toast.LENGTH_LONG).show();

}

}else{

Toast.makeText(RegActivity.this, R.string.error, Toast.LENGTH_LONG).show();

return;

}

}

});

cancel.setOnClickListener(new  View.OnClickListener() {

@Override

public void onClick(View arg0) {

// TODO Auto-generated method stub

RegActivity.this.fileList();

}

});

}

}


0 0