Android資料儲存(3)SQLite簡介和簡單的登入與註冊原始碼
阿新 • • 發佈:2018-12-30
操作SQLite資料的基本操作步驟:
Android群:239123204(在此不考慮用SQLiteOpenHelper類)
1.獲取SQLiteDatabase物件db建立資料庫或連線資料庫:SQLiteDatabasedb = SQLiteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString()+ "/test.dbs", null);如果目錄下有test.dbs資料庫則是連線沒有就是建立
2.用物件db的方法來執行sql語句:db.execSQL(String sql) 此方法木有返回值 所以查詢不好弄。查詢一般用db.rawQuery返回一個Cursor物件(相當與jdbc中的ResultSet),Cursor有如下幾個方法來查詢資料:
2.1 move ToFirst 將記錄指標跳到第一行
2.2 moveToLast將記錄指標跳到最後一行
2.3 moveNext將記錄指標移到下一行
2.4moveToPosition( int ss)將記錄指標跳到指定的ss行
2.5moveToPrevious將記錄指標跳到上一行
將記錄指標跳到指定的行之後就可以通過物件的getXXX方法來獲取資料 :如Cursor cursor = db.rawQuery("select na,pw from user where na=? and pw=?", new String []{name,pwd});
3.回收資源close
當然以SQLiteDatabase物件還可以呼叫許多方法來操作資料庫,不過俺是覺得這幾個方法基本夠了
簡單的登入與註冊原始碼
(僅此來練習SQLite的操作 一般註冊的資訊都樣上傳到伺服器而不會是儲存在手機資料庫)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.xiong.sqlitelogin" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="14" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.android.xiong.sqlitelogin.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.android.xiong.sqlitelogin.RegistersActivity" android:label="@string/app_name" > </activity> </application> </manifest>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:gravity="center_horizontal"
android:textColor="#8a2be2"
android:textSize="35dp"
android:text="登入介面" />
<TextView
android:id="@+id/txtname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/login"
android:layout_marginRight="5dp"
android:layout_marginBottom="30dp"
android:textSize="28dp"
android:text="使用者帳號:"/>
<EditText
android:id="@+id/edname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_below="@id/login"
android:layout_toRightOf="@id/txtname"
android:layout_alignParentRight="true"
android:hint="請輸入使用者帳號"/>
<TextView
android:id="@+id/txtpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/txtname"
android:layout_marginRight="5dp"
android:textSize="28dp"
android:text="使用者密碼:"/>
<EditText
android:id="@+id/edpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/edname"
android:layout_toRightOf="@id/txtpassword"
android:layout_alignParentRight="true"
android:inputType="textPassword"
android:hint="請輸入使用者密碼"/>
<LinearLayout
android:layout_below="@id/edpassword"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal" >
<Button
android:id="@+id/btregister"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="20dp"
android:text="使用者註冊"/>
<Button
android:id="@+id/btlogin"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="使用者登入"/>
</LinearLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:gravity="center_horizontal"
android:text="註冊介面"
android:textColor="#8a2be2"
android:textSize="35dp" />
<TextView
android:id="@+id/txtname1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/txt1"
android:layout_marginBottom="30dp"
android:layout_marginRight="5dp"
android:text="帳號:"
android:textSize="28dp" />
<EditText
android:id="@+id/edname1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@id/txt1"
android:layout_toRightOf="@id/txtname1"
android:layout_marginBottom="30dp" />
<TextView
android:id="@+id/txtpassword1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/txtname1"
android:layout_marginRight="5dp"
android:text="密碼:"
android:textSize="28dp" />
<EditText
android:id="@+id/edpassword1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@id/edname1"
android:layout_toRightOf="@id/txtpassword1" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/edpassword1"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/btregister1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:text="提交資料" />
</LinearLayout>
</RelativeLayout>
package com.android.xiong.sqlitelogin;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
// 帳號和密碼
private EditText edname;
private EditText edpassword;
private Button btregister;
private Button btlogin;
// 建立SQLite資料庫
public static SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edname = (EditText) findViewById(R.id.edname);
edpassword = (EditText) findViewById(R.id.edpassword);
btregister = (Button) findViewById(R.id.btregister);
btlogin = (Button) findViewById(R.id.btlogin);
db = SQLiteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString()
+ "/test.dbs", null);
// 跳轉到註冊介面
btregister.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, RegistersActivity.class);
startActivity(intent);
}
});
btlogin.setOnClickListener(new LoginListener());
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
db.close();
}
class LoginListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = edname.getText().toString();
String password = edpassword.getText().toString();
if (name.equals("") || password.equals("")) {
// 彈出訊息框
new AlertDialog.Builder(MainActivity.this).setTitle("錯誤")
.setMessage("帳號或密碼不能空").setPositiveButton("確定", null)
.show();
} else {
isUserinfo(name, password);
}
}
// 判斷輸入的使用者是否正確
public Boolean isUserinfo(String name, String pwd) {
try{
String str="select * from tb_user where name=? and password=?";
Cursor cursor = db.rawQuery(str, new String []{name,pwd});
if(cursor.getCount()<=0){
new AlertDialog.Builder(MainActivity.this).setTitle("錯誤")
.setMessage("帳號或密碼錯誤!").setPositiveButton("確定", null)
.show();
return false;
}else{
new AlertDialog.Builder(MainActivity.this).setTitle("正確")
.setMessage("成功登入").setPositiveButton("確定", null)
.show();
return true;
}
}catch(SQLiteException e){
createDb();
}
return false;
}
}
// 建立資料庫和使用者表
public void createDb() {
db.execSQL("create table tb_user( name varchar(30) primary key,password varchar(30))");
}
@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;
}
}
package com.android.xiong.sqlitelogin;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
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;
public class RegistersActivity extends Activity {
private EditText edname1;
private EditText edpassword1;
private Button btregister1;
SQLiteDatabase db;
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
db.close();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
edname1 = (EditText) findViewById(R.id.edname1);
edpassword1 = (EditText) findViewById(R.id.edpassword1);
btregister1 = (Button) findViewById(R.id.btregister1);
btregister1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = edname1.getText().toString();
String password = edpassword1.getText().toString();
if (!(name.equals("") && password.equals(""))) {
if (addUser(name, password)) {
DialogInterface.OnClickListener ss = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
// 跳轉到登入介面
Intent in = new Intent();
in.setClass(RegistersActivity.this,
MainActivity.class);
startActivity(in);
// 銷燬當前activity
RegistersActivity.this.onDestroy();
}
};
new AlertDialog.Builder(RegistersActivity.this)
.setTitle("註冊成功").setMessage("註冊成功")
.setPositiveButton("確定", ss).show();
} else {
new AlertDialog.Builder(RegistersActivity.this)
.setTitle("註冊失敗").setMessage("註冊失敗")
.setPositiveButton("確定", null);
}
} else {
new AlertDialog.Builder(RegistersActivity.this)
.setTitle("帳號密碼不能為空").setMessage("帳號密碼不能為空")
.setPositiveButton("確定", null);
}
}
});
}
// 新增使用者
public Boolean addUser(String name, String password) {
String str = "insert into tb_user values(?,?) ";
MainActivity main = new MainActivity();
db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()
+ "/test.dbs", null);
main.db = db;
try {
db.execSQL(str, new String[] { name, password });
return true;
} catch (Exception e) {
main.createDb();
}
return false;
}
}