Android[中级教程]第三章 数据存储之SQLite

 这一章我们来学习Android数据库SQLite,还是接上一章的,对于唐僧师徙去西天,三个徙弟得要杀妖怪啊,那得有个汇总啊,有个记数啊,这里我们就用SQLite来存储各徙弟杀死妖怪的数量,OK,上main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="match_parent"
	android:layout_height="match_parent">
	<TextView android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceMedium"
		android:layout_width="wrap_content" android:text="西游记各主人公杀死妖怪数"
		android:id="@+id/textView1"></TextView>
	<Button android:text="增加一个主角" android:id="@+id/add_btn"
		android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
	<Button android:text="更新主角杀死妖怪数" android:id="@+id/update_btn"
		android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
	<Button android:text="删除一个主角" android:id="@+id/del_btn"
		android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
	<ListView android:layout_height="wrap_content" android:id="@+id/listView1"
		android:layout_width="match_parent"></ListView>

</LinearLayout>

这里定义了三个按钮,一个ListView,接下来又定义了三个Layout,分别显示"增加一个主角","更新主角杀死妖怪数","删除一个主角"的页面,分别如下:

add_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="match_parent"
	android:layout_height="match_parent" android:padding="10dp">
	<TextView android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceMedium"
		android:layout_width="wrap_content" android:text="主角名称"></TextView>
	<EditText android:layout_height="wrap_content"
		android:layout_width="match_parent" android:id="@+id/add_name">
		<requestFocus></requestFocus>
	</EditText>
	<TextView android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceMedium"
		android:layout_width="wrap_content" android:text="杀死妖怪数量"></TextView>
	<EditText android:layout_height="wrap_content"
		android:layout_width="match_parent" android:id="@+id/add_number"
		android:inputType="number"></EditText>

</LinearLayout>

update_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="match_parent"
	android:layout_height="match_parent" android:padding="10dp">
	<TextView android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceMedium"
		android:layout_width="wrap_content" android:text="ID"></TextView>
	<EditText android:layout_height="wrap_content"
		android:layout_width="match_parent" android:id="@+id/update_id"
		android:inputType="number">
		<requestFocus></requestFocus>
	</EditText>
	<TextView android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceMedium"
		android:layout_width="wrap_content" android:text="杀死妖怪数量"></TextView>
	<EditText android:layout_height="wrap_content"
		android:layout_width="match_parent" android:id="@+id/update_number"
		android:inputType="number"></EditText>

</LinearLayout>

delete_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="match_parent"
	android:layout_height="match_parent" android:padding="10dp">
	<TextView android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceMedium"
		android:layout_width="wrap_content" android:text="ID"></TextView>
	<EditText android:layout_height="wrap_content"
		android:layout_width="match_parent" android:id="@+id/delete_id"
		android:inputType="number">
		<requestFocus></requestFocus>
	</EditText>

</LinearLayout>

最后再定义一个List_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="match_parent"
	android:layout_height="match_parent">
	<LinearLayout android:layout_height="wrap_content"
		android:id="@+id/linearLayout1" android:layout_width="match_parent">
		<TextView android:layout_height="wrap_content"
			android:textAppearance="?android:attr/textAppearanceMedium"
			android:layout_width="wrap_content" android:text="ID: "
			android:paddingLeft="10dp"></TextView>
		<TextView android:layout_height="wrap_content"
			android:textAppearance="?android:attr/textAppearanceMedium"
			android:layout_width="wrap_content" android:text="TextView"
			android:id="@+id/id"></TextView>
		<TextView android:layout_height="wrap_content"
			android:textAppearance="?android:attr/textAppearanceMedium"
			android:layout_width="wrap_content" android:text="TextView"
			android:id="@+id/name" android:paddingLeft="30dp"></TextView>
	</LinearLayout>
	<LinearLayout android:layout_height="wrap_content"
		android:id="@+id/linearLayout2" android:layout_width="match_parent">
		<TextView android:layout_height="wrap_content"
			android:layout_width="wrap_content" android:text="杀死了"
			android:paddingLeft="10dp"></TextView>
		<TextView android:text="TextView" android:id="@+id/number"
			android:layout_width="wrap_content" android:layout_height="wrap_content"
			android:textColor="#FF0000"></TextView>
		<TextView android:text="只妖怪" android:layout_width="wrap_content"
			android:layout_height="wrap_content"></TextView>
	</LinearLayout>

</LinearLayout>

OK,定义完了,,我们就来创建数据库了,创建一个DatabaseHelper.java

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper
{
	//数据库名称
	private static final String DB_NAME = "SQLiteDemo.db";
	//数据库版本
	private static final int DB_VERSION = 1;
	
	//表名
	public static final String TABLE_NAME = "demo";
	
	private static final String DB_CREATE = "create table " + TABLE_NAME +  " (_id integer primary key autoincrement, name varchar(20), number varchar(10))";

	public DatabaseHelper(Context context)
	{
		super(context, DB_NAME, null, DB_VERSION);
		
	}
	
	/**
	 * 创建表
	 */
	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL(DB_CREATE);

	}

	/**
	 * 更新表
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
//		db.execSQL("drop table if exists " + TABLE_NAME);
//		onCreate(db);

	}

}

另外再创建一个数据库操作辅助类DatabaseServer.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseServer
{
	private DatabaseHelper dbHelper;

	public DatabaseServer(Context context)
	{
		this.dbHelper = new DatabaseHelper(context);
	}

	/**
	 * 插入数据
	 * 
	 * @param name
	 *            名字
	 * @param number
	 *            数据
	 * @return 如果成功则返回true,否则返回false
	 */
	public boolean insert(String name, String number)
	{
		//创建或打开数据库
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		ContentValues cv = new ContentValues();
		cv.put("name", name);
		cv.put("number", number);
		//插入数据,返回插入数据ID
		long id = db.insert(dbHelper.TABLE_NAME, null, cv);
		if (id != 0)
		{
			return true;
		}

		return false;
	}

	/**
	 * 更新数据
	 * 
	 * @param id
	 *            数据列_id
	 * @param number
	 *            数量
	 * @return 如果成功则返回true,否则返回false
	 */
	public boolean update(int id, String number)
	{

		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		//Android自带的ContetValues,类似于Map,提供了put(String key, XXX value)的方法存入数据
		ContentValues cv = new ContentValues();
		cv.put("number", number);
		
		//通过ContentValues更新数据表,返回更新的ID值
		int result = db.update(dbHelper.TABLE_NAME, cv, "_id=?",
				new String[] { String.valueOf(id) });

		if (result != 0)
		{
			return true;
		}

		return false;
	}

	/**
	 * 删除数据
	 * 
	 * @param id
	 *            数据列_id
	 * @return
	 */
	public boolean delete(int id)
	{

		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		//删除指定ID值
		int result = db.delete(dbHelper.TABLE_NAME, "_id=?",
				new String[] { String.valueOf(id) });

		if (result != 0)
		{
			return true;
		}

		return false;
	}

	/**
	 * 查询数据
	 * 
	 * @return 返回数据列表
	 */
	public Cursor fetchAll()
	{

		SQLiteDatabase db = dbHelper.getReadableDatabase();
		//查询数据表中所有字段
		Cursor cursor = db.query(dbHelper.TABLE_NAME, null, null, null, null,
				null, "_id desc");
		if (cursor != null)
		{
			return cursor;
		}
		return null;

	}
}

这里将插入,更新,删除,查询分别做了简单的封装,OK,最后就是Activity类了

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SQLiteDemo extends Activity implements OnClickListener
{
	private Button add_btn;
	private Button update_btn;
	private Button del_btn;
	private ListView listView;
	private DatabaseServer dbServer;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sqlite);

		add_btn = (Button) findViewById(R.id.add_btn);
		add_btn.setOnClickListener(this);

		update_btn = (Button) findViewById(R.id.update_btn);
		update_btn.setOnClickListener(this);

		del_btn = (Button) findViewById(R.id.del_btn);
		del_btn.setOnClickListener(this);

		listView = (ListView) findViewById(R.id.listView1);
		dbServer = new DatabaseServer(this);
		//自定义方法
		SetInAdapter();
	}
	
	/**
	 * 将数据库里查询到的数据匹配进ListView中
	 */
	private void SetInAdapter()
	{
		Cursor cursor = dbServer.fetchAll();
		
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.list_item, cursor, new String[] { "_id", "name",
						"number" },
				new int[] { R.id.id, R.id.name, R.id.number });
		listView.setAdapter(adapter);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.add_btn:
			
			//数据插入
			data_add();
			
			break;

		case R.id.update_btn:
			
			//数据更新
			data_update();

			break;

		case R.id.del_btn:
			
			//数据删除
			data_delete();
			
			break;
		}

	}
	
	/**
	 * 删除主角
	 */
	private void data_delete()
	{
		//通过扩展,将delete_item.xml放入视图中
		final View delete_view = LayoutInflater.from(this).inflate(R.layout.delete_item, null);
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("删除主角");
		//设置显示视图为delete_item.xml
		dialog.setView(delete_view);
		dialog.setPositiveButton("确定", new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				//取得delete_item.xml中的EditText控件
				EditText delete_id = (EditText)delete_view.findViewById(R.id.delete_id);
				//取得输入的ID值
				int id = Integer.parseInt(delete_id.getText().toString());
				
				//调用数据库辅助类中的删除数据方法
				boolean flag = dbServer.delete(id);
				
				if(flag){
					showToast("主角删除成功");
				}else{
					showToast("主角删除失败");
				}
				
				dialog.dismiss();
				
				//调用自定义方法更新ListView
				SetInAdapter();
				
			}
		});
		dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				//对话框取消
				dialog.dismiss();
				
			}
		});
		dialog.show();
		
	}

	/**
	 * 更新主角杀死妖怪数
	 */
	private void data_update()
	{
		//同上
		final View update_view = LayoutInflater.from(this).inflate(R.layout.update_item, null);
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("更新主角杀死ID数");
		dialog.setView(update_view);
		dialog.setPositiveButton("确定", new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				EditText update_id = (EditText)update_view.findViewById(R.id.update_id);
				int id =Integer.parseInt(update_id.getText().toString());
				
				EditText update_number = (EditText)update_view.findViewById(R.id.update_number);
				String number_str = update_number.getText().toString();
				
				boolean flag = dbServer.update(id, number_str);
				
				if(flag){
					showToast("主角数据更新成功");
				}else{
					showToast("主角数据更新失败");
				}
				
				dialog.dismiss();
				
				SetInAdapter();
				
			}
		});
		dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				
			}
		});
		dialog.show();
	}

	/**
	 * 增加一个主角方法
	 */
	private void data_add()
	{
		//同上
		final View add_view = LayoutInflater.from(this).inflate(R.layout.add_item, null);
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("增加一个主角");
		dialog.setView(add_view);
		dialog.setPositiveButton("确定", new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				EditText add_name = (EditText)add_view.findViewById(R.id.add_name);
				String name_str = add_name.getText().toString();
				
				EditText add_number = (EditText)add_view.findViewById(R.id.add_number);
				String number_str = add_number.getText().toString();
				
				boolean flag = dbServer.insert(name_str, number_str);
				
				if(flag){
					showToast("主角增加成功");
				}else{
					showToast("主角增加失败");
				}
				
				dialog.dismiss();
				
				SetInAdapter();
				
			}
		});
		dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				
			}
		});
		dialog.show();
		
	}

	/*
	 * 按指定内容显示Toast
	 */
	protected void showToast(String string)
	{
		Toast.makeText(this, string, 1).show();
	}
}

这里有点长,希望大家能够看完,其实不是太难,这里上图:



下一章我们将介绍Android中的单元测试TestCase,谢谢,如果哪位同学想要源码的,请留邮箱,我会及时给你发过去.



 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值