关闭

Android入门之SQLiteDatabase联习

标签: sqliteSQLiteDatabaseAndroidFielOutputStreamFile
778人阅读 评论(1) 收藏 举报
分类:

上一篇文章SQLite就那么一回事http://blog.csdn.net/imlanbin/article/details/17102717

main.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/et_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:hint="请输入名字" />

    <EditText
        android:id="@+id/et_email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:hint="请输入Email" />

    <Button
        android:id="@+id/insertContact"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickInsertContact"
        android:text="增加一个联系人" />

    <Button
        android:id="@+id/getAllContacts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickGetAllContacts"
        android:text="检索所有联系人" />

    <Button
        android:id="@+id/getContacts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickGetContact"
        android:text="检索单个联系人" />

    <Button
        android:id="@+id/updateContact"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickUpdateContact"
        android:text="更新联系人" />

    <Button
        android:id="@+id/deleteContact"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickDeleteContact"
        android:text="删除联系人" />
 	<Button
        android:id="@+id/bindDatabase"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickBindDatabase"
        android:text="捆绑数据库" />
    
    <TextView
        android:id="@+id/display"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="显示消息"
        android:textColor="#EE1100" 
        android:gravity="center"/>
</LinearLayout>

DBAdapter.java

import java.sql.SQLException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
	static final String KEY_ROWID = "_id";
	static final String KEY_NAME = "name";
	static final String KEY_EMAIL = "email";
	static final String TAG = "DBAdapt";
	static final String DATABASE_NAME = "MyDB.txt";
	static final String DATABASE_TABLE = "contacts";
	static final int DATABASE_VERSIOIN = 1;
	static final String DATABASE_CREATE = "CREATE TABLE contacts(_id,INTEGER PRIMARY KEY,"
			+"name TEXT NOT NULL,email TEXT NOT NULL)";
	final Context context;
	MyDatabaseHelper DBHelper;
	SQLiteDatabase db;
	public DBAdapter(Context context){
		this.context = context;
		DBHelper = new MyDatabaseHelper(context);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	private static  class MyDatabaseHelper extends SQLiteOpenHelper{

		public MyDatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}
		public MyDatabaseHelper(Context context){//为了方便,重载构造方法
			super(context, DATABASE_NAME, null, DATABASE_VERSIOIN);
		}
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			
			Log.w(TAG, "Upgrding database from version"+"oldVersion"+"to"+"newVersion"
					+",which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS contacts");
			onCreate(db);
		}
	}
	
	public DBAdapter open() throws SQLException{
		db = DBHelper.getWritableDatabase();
		return this;
	}
	
	public void close(){
		DBHelper.close();
	}
	
	public long insertContact(String name, String email){
		ContentValues values = new ContentValues();
		values.put(KEY_NAME, name);
		values.put(KEY_EMAIL, email);
		return db.insert(DATABASE_TABLE, null, values);
	}
	
	public boolean deleteContact(long rowId){	
		return db.delete(DATABASE_TABLE, KEY_ROWID+"="+rowId,null) > 0;				
	}
	
	public Cursor getAllContact(){
		return db.query(DATABASE_TABLE, null,null , null, null, null, null);
	}
	
	public Cursor getContact(long rowId) throws SQLException{
		Cursor mCursor = db.query(true, DATABASE_TABLE, new String []{
				KEY_ROWID,KEY_NAME,KEY_EMAIL}, KEY_ROWID+"="+rowId
				, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	public boolean udataContact(long rowId,String name,String email){
		ContentValues args = new ContentValues();
		args.put(KEY_NAME,name);
		args.put(KEY_EMAIL, email);
		return db.update(DATABASE_TABLE, args, KEY_ROWID+"="+rowId, null) > 0;
	}
}

DatabaseActivity.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DatabaseActivity extends Activity {
	private EditText editName,editEmail;
	private TextView display;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_database);	
		editName = (EditText)findViewById(R.id.et_name);
		editEmail = (EditText)findViewById(R.id.et_email);
		display = (TextView)findViewById(R.id.display);
	}
	//增加联系人
	public void onClickInsertContact(View v) throws SQLException{
		DBAdapter db = new DBAdapter(getBaseContext());
		db.open();
		String aName = editName.getText().toString();
		String aEmail = editEmail.getText().toString();
		long id = db.insertContact(aName, aEmail);
		Toast.makeText(getBaseContext(), "你已成功添加了一个联系人", 
				Toast.LENGTH_SHORT).show();	
		editName.setText("");
		editEmail.setText("");
		db.close();		
	}
	
	//检索所有联系人
	public void onClickGetAllContacts(View v) throws SQLException{
		DBAdapter db = new DBAdapter(getBaseContext());
		db.open();	
		Cursor c = db.getAllContact();
		if (c.moveToFirst()) {
			do {
				DisplayContact(c);
			} while (c.moveToNext());
		}
	}
	
	//检索单个联系人
	public void onClickGetContact(View v) throws SQLException{
		DBAdapter db = new DBAdapter(getBaseContext());
		db.open();
		Cursor c = db.getContact(2);
		if (c.moveToFirst()) {
			DisplayContact(c);
		}else{
			Toast.makeText(getBaseContext(), "找不到任何联系人", 
					Toast.LENGTH_SHORT).show();
		}
		db.close();
	}
	
	//更新联系人
	public void onClickUpdateContact(View v) throws SQLException{
		DBAdapter db = new DBAdapter(getBaseContext());
		db.open();
		if (db.udataContact(1, "欧阳锋", "ouyangfeng@163.com")) {
			Toast.makeText(getBaseContext(), "更新成功!", 
					Toast.LENGTH_LONG).show();
		}else {
			Toast.makeText(getBaseContext(), "更新失败!", 
					Toast.LENGTH_SHORT).show();
		}
		db.close();
	}
	
	//删除联系人
	public void updateDatabseupdateDatabse(View v) throws SQLException{
		DBAdapter db = new DBAdapter(getBaseContext());
		db.open();
		if (db.deleteContact(1)) {
			Toast.makeText(getBaseContext(), "删除成功!", 
					Toast.LENGTH_SHORT).show();
		}else {
			Toast.makeText(getBaseContext(), "删除失败!", 
					Toast.LENGTH_SHORT).show();
		}
		db.close();
	}
	
	//捆绑一个数据库
	public void onClickBindDatabase(View v) throws FileNotFoundException, SQLException{
		DBAdapter db = new DBAdapter(getBaseContext());
		try {
			String destPath = "/data/data/"+getPackageName() +"/databases";
			File f = new File(destPath);
			if (!f.exists()) {
				f.mkdirs();
				f.createNewFile();
				CopyDB(getBaseContext().getAssets().open("mydb"),
						new FileOutputStream(destPath+"/MyDB.txt"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		db.open();
		Cursor c = db.getAllContact();
		if (c.moveToFirst()) {
			do {
				DisplayContact(c);
			} while (c.moveToNext());
		}
		db.close();
	}
	
	public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int length;
		while ((length = inputStream.read(buffer)) > 0) {
			outputStream.write(buffer,0,length);
		}
		inputStream.close();
		outputStream.close();
	}
	public void DisplayContact(Cursor c) {
		display.setText(c.getString(0)+c.getString(1)+"姓名: "
				+c.getString(2)+",E-mail: "+c.getString(3)+"\n");
	}
	
}


对于这方法,我觉得自己java的IO流部分还是比较薄弱的,还是得补啊!学习是一条漫长的路,要有效率又不能浮躁!

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:61740次
    • 积分:822
    • 等级:
    • 排名:千里之外
    • 原创:32篇
    • 转载:4篇
    • 译文:1篇
    • 评论:22条
    文章分类
    最新评论