android:使用SQLite实现登录和注册功能及登录验证

先看效果:
android:使用SQLite实现登录和注册功能及登录验证_第1张图片
android:使用SQLite实现登录和注册功能及登录验证_第2张图片

首先写一个帮助类继承自SQLiteOpenHelper,在该类中创建数据表

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(Context context, String name, CursorFactory factory,
		int version) {
	super(context, name, factory, version);
	// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
	// TODO Auto-generated method stub
	//创建数据表
	String sql = "create table user(id integer primary key autoincrement,name varchar(20),password varchar(20),sex varchar(2),hobby varchar(20),birth varchar(20),city varchar(20))";
	sqLiteDatabase.execSQL(sql);
}
//将注册信息添加到数据表user中
public void addData(SQLiteDatabase sqLiteDatabase,String name,String password,String sex,String hobby,String birth,String city){
	ContentValues values = new ContentValues();
	values.put("name", name);
	values.put("password", password);
	values.put("sex", sex);
	values.put("hobby", hobby);
	values.put("birth", birth);
	values.put("city", city);
	sqLiteDatabase.insert("user", null, values);
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
	// TODO Auto-generated method stub

}

}

注册界面的布局设计register.xml

  
	
	


	
	


	
	
	    
    	
	


	
    
    
    
    


	
	


	
	


注册页面的Activity:Register.java

public class Register extends Activity implements View.OnClickListener,
RadioGroup.OnCheckedChangeListener,Spinner.OnItemSelectedListener{

DBHelper helper;
SQLiteDatabase sqLiteDatabase;

private String name_str="";
private String paswd_str="";
private String sex_str="男";
private String hobby_str="1";
private String birth_str="";
private String city_str="";

EditText name_deit,paswd_deit,birth_deit;
RadioGroup sex_group;
RadioButton nan_btn,nv_btn;
CheckBox study,play,music;
Spinner spinner;
Button btn;

final String[] city = new String[]{"北京","安徽","武汉","南京","南昌"};

@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.register);
	
	name_deit = (EditText) findViewById(R.id.name);
	paswd_deit = (EditText) findViewById(R.id.paswd);
	birth_deit = (EditText) findViewById(R.id.birth);
	sex_group = (RadioGroup) findViewById(R.id.sex);
	nan_btn = (RadioButton) findViewById(R.id.nan);
	nv_btn = (RadioButton) findViewById(R.id.nv);
	study = (CheckBox) findViewById(R.id.study);
    play = (CheckBox) findViewById(R.id.play);
    music = (CheckBox) findViewById(R.id.music);
    spinner = (Spinner) findViewById(R.id.spinner);
    btn = (Button) findViewById(R.id.reg_btn);
    
    sex_group.setOnCheckedChangeListener(this);
    spinner.setOnItemSelectedListener(this);
    birth_deit.setOnClickListener(this);
    btn.setOnClickListener(this);
    
    helper = new DBHelper(Register.this, "user_db", null, 1);
	sqLiteDatabase = helper.getWritableDatabase();
	
    ArrayAdapteradapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,city);
    spinner.setAdapter(adapter);
 
}

@Override
public void onClick(View view) {
	// TODO Auto-generated method stub
	switch (view.getId()) {
		case R.id.birth:
			Calendar cal = Calendar.getInstance();
			DatePickerDialog date = new DatePickerDialog(Register.this, new OnDateSetListener() {
				
				@Override
				public void onDateSet(DatePicker arg0, int year, int month, int day) {
					// TODO Auto-generated method stub
					birth_deit.setText(year+"年"+(month+1)+"月"+day+"日"); 
				}
			}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)+1);
			date.show();
			break;
		case R.id.reg_btn:
			new AlertDialog.Builder(Register.this).setTitle("系统提示")
			.setMessage("是否确定提交?")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					name_str = name_deit.getText().toString();
					paswd_str = paswd_deit.getText().toString();
					hobby_str ="";
					if(study.isChecked()){
						hobby_str += study.getText().toString();
					}if(play.isChecked()){
						hobby_str += play.getText().toString();
					}if(music.isChecked()){
						hobby_str += music.getText().toString();
					}
					birth_str = birth_deit.getText().toString();
					
					Cursor cursor = sqLiteDatabase.query("user", new String[]{"name"}, "name=?", new String[]{name_str}, null, null, null);
					if(cursor.getCount()!=0){
						Toast.makeText(Register.this, "该用户已注册!", Toast.LENGTH_SHORT).show();
					}else{
						helper.addData(sqLiteDatabase, name_str, paswd_str, sex_str, hobby_str, birth_str, city_str);
						Toast.makeText(Register.this, "注册成功,请登录!", Toast.LENGTH_SHORT).show();
						Intent intent = new Intent(Register.this,MainActivity.class);
						startActivity(intent);
						finish();
					}
				}
			}).setNegativeButton("返回", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
			}).show();
			break;
		default:
			break;
	}
}

@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
	// TODO Auto-generated method stub
	RadioButton rb = (RadioButton) findViewById(i);
	sex_str=rb.getText().toString();
}

@Override
public void onItemSelected(AdapterView arg0, View view, int i,
		long l) {
	// TODO Auto-generated method stub
	city_str = city[i];
}

@Override
public void onNothingSelected(AdapterView arg0) {
	// TODO Auto-generated method stub
	
}

}

登录界面布局:activity_main.xml



    

    

    







    

登录页面Activity:MainActivity.java

public class MainActivity extends Activity implements View.OnClickListener{

private SharedPreferences sp;
private EditText user, psw;
private CheckBox rem_psw;
private Editor editor;
private Button btn;
private TextView news;

DBHelper helper;
SQLiteDatabase sqLiteDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    user=(EditText) findViewById(R.id.names);
    psw=(EditText) findViewById(R.id.password);
    rem_psw=(CheckBox) findViewById(R.id.jizhu);
    btn = (Button) findViewById(R.id.login_button);
    news = (TextView) findViewById(R.id.news);
    btn.setOnClickListener(this);  
    news.setOnClickListener(this);
    
    helper = new DBHelper(MainActivity.this, "user_db", null, 1);
	sqLiteDatabase = helper.getWritableDatabase();
	
    sp = getSharedPreferences("user_mes", MODE_PRIVATE);
	editor = sp.edit();
	if (sp.getBoolean("flag", false)) {
		String user_read = sp.getString("user", "");
		String psw_read = sp.getString("psw", "");
		user.setText(user_read);
		psw.setText(psw_read);
	}
      
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


@Override
public void onClick(View view) {
	// TODO Auto-generated method stub
	switch (view.getId()) {
	case R.id.login_button:
		String user_str = user.getText().toString();
		String psw_str = psw.getText().toString();
		if (user_str.equals("") || user_str.equals("")) {
            Toast.makeText(this, "账号或密码不能为空", Toast.LENGTH_SHORT).show();
        }else {
        	Cursor cursor = sqLiteDatabase.query("user", new String[]{"password"}, "name=?", new String[]{user_str}, null, null, null);
			if(cursor.moveToNext()){
				String psw_query=cursor.getString(cursor.getColumnIndex("password"));
				if(psw_str.equals(psw_query)){
				    //记住密码
					if (rem_psw.isChecked()) {
						editor.putBoolean("flag", true);
						editor.putString("user", user_str);
						editor.putString("psw", psw_str);
						editor.commit();
						Toast.makeText(MainActivity.this, "成功记住密码", Toast.LENGTH_LONG).show();
					} else {
						editor.clear();
						editor.commit();
					}
					Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
					
				}else{
					Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show();
				}
			}else{
				Toast.makeText(this, "账号不存在,请先注册!", Toast.LENGTH_SHORT).show();
			}
        }
		break;
	case R.id.news:
		Intent intent = new Intent(MainActivity.this, Register.class);
		startActivity(intent);
		break;
	default:
		break;
}
}

}

你可能感兴趣的:(android开发)