使用SQLite将用户账号密码保存到本地

//Db工具类
package com.example.test;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Db extends SQLiteOpenHelper {

	private static final String DBAdapter = null;

	public Db(Context context) {
		super(context, "NewDB", null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
                //创建user表
		db.execSQL("CREATE TABLE user(" + "_id integer primary key autoincrement,"
				+ "userid text not null," 
				+ "psw text not null )");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

}

package com.example.test;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity{
	
	private Button button = null;
	private EditText editText = null;
	public Db db = new Db(this);
	
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button)findViewById(R.id.button1);
		editText = (EditText)findViewById(R.id.editText1);
                //向user表插入数据
		sqliteinsert();
                //查询user表数据
                sqlitequery();		
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
                                //单击按钮后将edittext置空
				editText.setText("");
                                //删除user表数据
				sqlitedelete();
//				sqliteinsert();
				sqlitequery();
			}
		});
	}
	public void sqlitequery() {
		final SQLiteDatabase dbRead = db.getReadableDatabase();
		Cursor cursor = dbRead.query("user", null, null, null, null, null, null);
		while (cursor.moveToLast()) {
			String userid = cursor.getString(cursor.getColumnIndex("userid"));
			String psw = cursor.getString(cursor.getColumnIndex("psw"));
                        //读出数据显示在edittext中
			editText.setText(userid+psw);
			break;
		}
		cursor.close();
	}
	public void sqliteinsert() {
		final SQLiteDatabase dbWrite = db.getReadableDatabase();
		String str_userid = "userid2";
		String str_psw = "psw";
                //以键值对的形式存入数据
		ContentValues cv = new ContentValues();
		cv.put("userid", str_userid);
		cv.put("psw", str_psw);
		dbWrite.insert("user", null, cv);
}
	public void sqlitedelete() {	
		final SQLiteDatabase dbRead = db.getReadableDatabase();
		dbRead.delete("user", null, null);
	}	
}

你可能感兴趣的:(Android)