1. 程式人生 > >android——SQLite實現簡單的註冊登陸

android——SQLite實現簡單的註冊登陸

  1 package com.example.dbtest;
  2 
  3 import android.app.Activity;
  4 import android.app.AlertDialog;
  5 import android.app.AlertDialog.Builder;
  6 import android.content.DialogInterface;
  7 import android.content.Intent;
  8 import android.database.Cursor;
  9 import android.database.sqlite.SQLiteDatabase;
10 import android.database.sqlite.SQLiteException; 11 import android.database.sqlite.SQLiteOpenHelper; 12 import android.os.Bundle; 13 import android.view.View; 14 import android.view.View.OnClickListener; 15 import android.widget.Button; 16 import android.widget.EditText; 17 import android.widget.Toast;
18 19 public class MainActivity extends Activity { 20 21 private EditText et_id, et_name; 22 private Button btn_test, btn_local; 23 //1,SQLite的宣告 24 SQLiteOpenHelper helper; 25 private String _id; 26 private String _name; 27 28 @Override 29 protected
void onCreate(Bundle savedInstanceState) { 30 super.onCreate(savedInstanceState); 31 setContentView(R.layout.activity_main); 32 // 2,資料庫的建立,及呼叫 33 helper = new Sqliteopenhelper(this); 34 helper.getWritableDatabase(); 35 36 et_id = (EditText) findViewById(R.id.editText1); 37 et_name = (EditText) findViewById(R.id.editText2); 38 btn_test = (Button) findViewById(R.id.button1); 39 btn_local = (Button) findViewById(R.id.button2); 40 41 btn_test.setOnClickListener(new testListener()); 42 btn_local.setOnClickListener(new localListener()); 43 44 } 45 46 class testListener implements OnClickListener { 47 48 @Override 49 public void onClick(View v) { 50 // TODO Auto-generated method stub 51 Intent intent = new Intent(MainActivity.this, Register.class); 52 startActivity(intent); 53 } 54 55 } 56 //登陸按鈕 57 58 class localListener implements OnClickListener { 59 60 @Override 61 public void onClick(View v) { 62 // TODO Auto-generated method stub 63 _id = et_id.getText().toString(); 64 _name = et_name.getText().toString(); 65 if (_name.equals("") || _id.equals("")) { Toast.makeText(getApplicationContext(), "請輸入賬號密 碼!",Toast.LENGTH_SHORT).show(); 66 } else { 67 sureuser(_id, _name); 68 } 69 } 70 71 } 72 73 private void sureuser(String userid, String username) { 74 //3,資料庫的操作,查詢 75 SQLiteDatabase sdb = helper.getReadableDatabase(); 76 try { 77 String sql = "select * from student where id=? and name=?"; 78 // 實現遍歷id和name 79 Cursor cursor = sdb.rawQuery(sql, new String[] { _id, _name }); 80 if (cursor.getCount() > 0) { 81 Intent intent = new Intent(MainActivity.this, User.class); 82 Bundle bundle = new Bundle(); 83 bundle.putString("name", _name); 84 intent.putExtras(bundle); 85 startActivity(intent); 86 } else { 87 Toast.makeText(getApplicationContext(), "登入失敗", 88 Toast.LENGTH_SHORT).show(); 89 } 90 cursor.close(); 91 sdb.close(); 92 } catch (SQLiteException e) { 93 oast.makeText(getApplicationContext(), "親,請註冊!", 94 Toast.LENGTH_SHORT).show(); 95 } 96 } 97 98 99 100 101 }