求一份,android+sqlite的小案例,在线等

zgycsmb 2018-07-11 03:44:25
求一份,android+sqlite的小案例,只须有
1 对sqlite的表有增删 改查
2 有操作界面
3 代码可运行

大家可发代码到本贴,也可发我邮件350038760@qq.com
thanks
...全文
197 5 点赞 打赏 收藏 举报
写回复
5 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
zgycsmb 2018-07-12
运行不了
1
第二个xml文件不完整,
2 database这个类,没有发出来,
你把整个项目发我邮件吧,
  • 打赏
  • 举报
回复
键盘舞者113 2018-07-11
第三个

<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="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:hint="Enter Name"
android:id="@+id/name"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email:"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:hint="Enter Email"
android:id="@+id/email"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="身高:"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:hint="Enter Height"
android:id="@+id/height"
/>
</LinearLayout>
</LinearLayout>



  • 打赏
  • 举报
回复
键盘舞者113 2018-07-11
接着上面的

package com.androidleaf.sqlite.database;

import android.annotation.TargetApi;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;

/**
* 该类是SQLiteDatabase的帮助类,主要管理数据库的创建和版本的更新
* @author AndroidLeaf
*
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DatabaseOpenHelper extends SQLiteOpenHelper {

private static DatabaseOpenHelper mDatabaseOpenHelper;
/**
* 数据库版本号
*/
private static final int DATABASE_VERSION = 1;
/**
* 数据库名称
*/
private static final String DATABASE_NAME = "manager.db";

/**
* 定义一个事件监听回调,将创建表和更新数据库表的操作让子类实现
*/
public SQLiteDataTable mDataTable;

public interface SQLiteDataTable{
public void onCreate(SQLiteDatabase mSqLiteDatabase);
public void onUpgrade(SQLiteDatabase mSqLiteDatabase);
}

public void setOnSQLiteDataTable(SQLiteDataTable mDataTable){
this.mDataTable = mDataTable;
}
/**
* 初始化数据库信息
* @param context 应用程序上下文
* @param name 数据库名称
* @param factory cursor工厂对象
* @param version 数据库版本号
* @param errorHandler 数据库错误处理对象
*/
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, new DatabaseErrorHandler() {

@Override
public void onCorruption(SQLiteDatabase dbObj) {
// TODO Auto-generated method stub
}
});
// TODO Auto-generated constructor stub
}

/**
* 使用单例模式,获取数据库唯一实例
* @param mContext 应用程序上下文
* @return mDatabaseOpenHelper 该对象用于获取SQLiteDatabase实例
*/
public synchronized static DatabaseOpenHelper getDatabaseOpenHelper(Context mContext){
if(mDatabaseOpenHelper == null){
mDatabaseOpenHelper = new DatabaseOpenHelper(mContext);
}
return mDatabaseOpenHelper;
}

/**
* 创建数据库时调用,一般执行创建表的操作
*/
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//创建一系列的数据库表
mDataTable.onCreate(db);
}

/**
* 当数据库需要修改的时系统会自动调用此方法。一般我们在这个方法里边删除数据库表,
* 并建立新的数据库表,当然是否还需要其它操作,完全取决于应用的需求
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
mDataTable.onUpgrade(db);
onCreate(db);
}
}



package com.androidleaf.sqlite.database;

import android.content.ContentValues;

import java.util.ArrayList;


public interface IDatabaseManager {
public boolean insert(ContentValues mContentValues);
public <T> ArrayList<T> query(String sql);
public Object query(int id);
public boolean update(ContentValues mContentValues);
public boolean delete(int id);
public void execSQL(String sql);
public void closeDB();
}



package com.androidleaf.sqlite.database;

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

import com.androidleaf.sqlite.entity.Person;

import java.util.ArrayList;

public class PersonTableBusiness extends DataBaseManager<Person> {

//表的名称
private static final String PERSON_TABLE_NAME = "person";
private static final String PERSON_FIELD_ID = "_id";
private static final String PERSON_FIELD_PERSONNAME = "name";
private static final String PERSON_FIELD_EMAIL = "email";
private static final String PERSON_FIELD_HEIGHT = "height";
//定义主键是否为空
private static final int PRIMAY_KEY_IS_NULL = -1;

public PersonTableBusiness(Context mContext) {
super(mContext);
// TODO Auto-generated constructor stub
}

public void insertPerson(String name, String email, float height) {
ContentValues mContentValues = createParams(PRIMAY_KEY_IS_NULL, name,
email, height);
insert(mContentValues);
}

public void insertPersonObject(Person mPerson) {
insert(createParams(mPerson));
}

public void insertListPerson(ArrayList<Person> mPersons) {
for (Person mPerson : mPersons) {
insert(createParams(mPerson));
}
}

public void updatePerson(int id, String name, String email, float height) {
update(createParams(id, name, email, height));
}

public void updatePersonObject(Person mPerson) {
update(createParams(mPerson));
}

public void updatePersonList(ArrayList<Person> mPersons) {
for (Person mPerson : mPersons) {
update(createParams(mPerson));
}
}

public void deletePersonById(int id) {
delete(id);
}


public ArrayList<Person> queryAllPersons() {
String sql = "select * from " + PERSON_TABLE_NAME;
return query(sql);
}

public Person querySinglePersonById(int id) {
return query(id);
}

/**
* 实现回调方法,这里实现创建表的操作
*/
@Override
public void onCreate(SQLiteDatabase mSqLiteDatabase) {
// TODO Auto-generated method stub
// 创建表的SQL语句
String DATABASE_CREATE_PERSON_TABLE = "CREATE TABLE "
+ PERSON_TABLE_NAME + " (" + "" + PERSON_FIELD_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + ""
+ PERSON_FIELD_PERSONNAME + " VARCHAR(20) NOT NULL," + ""
+ PERSON_FIELD_EMAIL + " VARCHAR(20) NOT NULL," + ""
+ PERSON_FIELD_HEIGHT + " FLOAT(10) NOT NULL" + ")";
// 执行创建表的操作
mSqLiteDatabase.execSQL(DATABASE_CREATE_PERSON_TABLE);
}

/**
* 实现回调方法,这里执行删除表的操作
*/
@Override
public void onUpgrade(SQLiteDatabase mSqLiteDatabase) {
// TODO Auto-generated method stub
mSqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + PERSON_TABLE_NAME);
}

/**
* 创建参数集合
* @param mPerson
* @return mValues
*/
public ContentValues createParams(Person mPerson) {
ContentValues mValues = new ContentValues();
if (mPerson.getId() != PRIMAY_KEY_IS_NULL) {
mValues.put(PERSON_FIELD_ID, mPerson.getId());
}
mValues.put(PERSON_FIELD_PERSONNAME, mPerson.getName());
mValues.put(PERSON_FIELD_EMAIL, mPerson.getEmail());
mValues.put(PERSON_FIELD_HEIGHT, mPerson.getHeight());
return mValues;
}

/**
* 创建参数集合
* @param id
* @param name
* @param email
* @param height
* @return mValues
*/
public ContentValues createParams(int id, String name, String email,
float height) {
ContentValues mValues = new ContentValues();
if (id != PRIMAY_KEY_IS_NULL) {
mValues.put(PERSON_FIELD_ID, id);
}
mValues.put(PERSON_FIELD_PERSONNAME, name);
mValues.put(PERSON_FIELD_EMAIL, email);
mValues.put(PERSON_FIELD_HEIGHT, height);
return mValues;
}

@Override
public String getTableName() {
// TODO Auto-generated method stub
return PERSON_TABLE_NAME;
}

@Override
public String getPrimayKeyID() {
// TODO Auto-generated method stub
return PERSON_FIELD_ID;
}

/**
* 通过获取到的Cursor转换成Person对象
*/
@Override
public Person getResultFromCursor(Cursor mCursor) {
// TODO Auto-generated method stub
Person mPerson = new Person();
mPerson.setId(mCursor.getInt(mCursor.getColumnIndex(PERSON_FIELD_ID)));
mPerson.setName(mCursor.getString(mCursor
.getColumnIndex(PERSON_FIELD_PERSONNAME)));
mPerson.setEmail(mCursor.getString(mCursor
.getColumnIndex(PERSON_FIELD_EMAIL)));
mPerson.setHeight(mCursor.getFloat(mCursor
.getColumnIndex(PERSON_FIELD_HEIGHT)));
return mPerson;
}
}




package com.androidleaf.sqlite.entity;


public class Person {

private int id;
private String name;
private String email;
private float height;

public Person(){}

public Person(int id,String name,String email,float height){
this.id = id;
this.name = name;
this.email = email;
this.height = height;
}

public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}

}




<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>




<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="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/person_id"
android:layout_alignParentLeft="true"
android:text="person ID"
android:layout_centerVertical="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/person_name"
android:layout_toRightOf="@id/person_id"
android:layout_marginLeft="20dp"
android:text="Person Name"
android:layout_centerVertical="true"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="person_height"
android:id="@+id/person_height"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="p
  • 打赏
  • 举报
回复
键盘舞者113 2018-07-11
你运行


package com.androidleaf.sqlite.activity;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;

import com.androidleaf.sqlite.adapter.PersonListAdapter;
import com.androidleaf.sqlite.database.PersonTableBusiness;
import com.androidleaf.sqlite.entity.Person;

import java.util.ArrayList;

public class MainActivity extends ListActivity {

PersonTableBusiness mPersonTableBusiness;

public static final int INSERT_ACTION = 0;
public static final int UPDATE_ACTION = 1;
public static final int DELETE_ACTION = 2;

PersonListAdapter mAdapter = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}

/**
* 初始化数据,展现数据列表
*/
public void init(){

mPersonTableBusiness = new PersonTableBusiness(this);
//添加一些默认数据
if(mPersonTableBusiness.queryAllPersons().size()==0)
mPersonTableBusiness.insertListPerson(initData());

mAdapter = new PersonListAdapter(this,mPersonTableBusiness.queryAllPersons());
//适配器绑定数据
setListAdapter(mAdapter);
//将ListView列表添加到上下文Menu中
this.registerForContextMenu(getListView());
}

/**
* 插入数据
*/
public void insertPerson(){
createDialog("添加", INSERT_ACTION, -1,null);
}

/**
* 删除数据
* @param id 列表ID
*/
public void deletePerson(final int id){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this)
.setTitle("是否删除?")
.setPositiveButton("确定", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
mPersonTableBusiness.deletePersonById(id);
//重新设置数据
mAdapter.setData(mPersonTableBusiness.queryAllPersons());
//更新数据列表
mAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("取消", null);
mBuilder.show();
}

/**
* 更新数据
* @param id 列表ID
*/
public void updatePerson(int id,Person mPerson){
createDialog("更新", UPDATE_ACTION, id,mPerson);
}

/**
* 初始化一些测试数据
* @return
*/
public ArrayList<Person> initData(){
ArrayList<Person> mList = new ArrayList<Person>();
for(int i = 0; i < 20;i++){
Person mPerson = new Person(-1,"Steve P.Jobs "+ i, "45936455"+ i +"@qq.com", (170 + i));
mList.add(mPerson);
}
return mList;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, Menu.NONE, "添加");
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
insertPerson();
return super.onOptionsItemSelected(item);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
menu.setHeaderTitle("文件操作");
menu.add(0, 1, Menu.NONE, "修改");
menu.add(0, 2, Menu.NONE, "删除");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
// 得到当前被选中的item信息
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
.getMenuInfo();
int id = -1;
Person mPerson = null;
if(mAdapter != null){
mPerson = (Person)mAdapter.getItem(menuInfo.position);
id = mPerson.getId();
}

switch (item.getItemId()) {
case UPDATE_ACTION:
updatePerson(id,mPerson);
break;
case DELETE_ACTION:
deletePerson(id);
break;
default:
break;
}
return true;
}

/**
* 创建Dialog实例
* @param title 设置Dialog标题
* @param action 设置操作类型 ,UPDATE_ACTION为更新操作,INSERT_ACTION为插入操作
* @param id 被选中的选项ID
*/
public void createDialog(String title,final int action,final int id,final Person mPerson){

final View mView = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_operation, null);
String titlName = getResources().getString(R.string.operation, new Object[]{title});

final EditText mEditText_name = (EditText)mView.findViewById(R.id.name);
final EditText mEditText_email = (EditText)mView.findViewById(R.id.email);
final EditText mEditText_height = (EditText)mView.findViewById(R.id.height);

//初始化数据
if(action == UPDATE_ACTION){
mEditText_name.setText(mPerson.getName());
mEditText_email.setText(mPerson.getEmail());
mEditText_height.setText(String.valueOf(mPerson.getHeight()));
}

//创建Dialog实例对象
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this)
.setTitle(titlName)
.setView(mView)
.setPositiveButton("确定", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

String name = mEditText_name.getText().toString().trim();
String email = mEditText_email.getText().toString().trim();
float height = Float.parseFloat(mEditText_height.getText().toString().trim());

if(!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email) &&
!TextUtils.isEmpty(mEditText_height.getText().toString().trim())){
switch (action) {
case INSERT_ACTION:
mPersonTableBusiness.insertPerson(name, email, height);
break;
case UPDATE_ACTION:
mPersonTableBusiness.updatePerson(id, name, email, height);
break;
default:
break;
}
//重新设置数据
mAdapter.setData(mPersonTableBusiness.queryAllPersons());
//更新数据列表
mAdapter.notifyDataSetChanged();
}
}
})
.setNegativeButton("取消", null);
mBuilder.show();
}

/**
* 当退出当前界面时,关闭数据库
*/
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mPersonTableBusiness.closeDB();
}
}




package com.androidleaf.sqlite.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.androidleaf.sqlite.activity.R;
import com.androidleaf.sqlite.entity.Person;

import java.util.ArrayList;

public class PersonListAdapter extends BaseAdapter {

private Context mContext;
private ArrayList<Person> mList;

public PersonListAdapter(Context mContext,ArrayList<Person> mList){
this.mContext = mContext;
this.mList = mList;
}

public void setData(ArrayList<Person> mList){
this.mList = mList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mList.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mList.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder mViewHolder = null;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.layout_item, null);
mViewHolder = new ViewHolder();
mViewHolder.mTextView_id = (TextView)convertView.findViewById(R.id.person_id);
mViewHolder.mTextView_name = (TextView)convertView.findViewById(R.id.person_name);
mViewHolder.mTextView_height = (TextView)convertView.findViewById(R.id.person_height);
mViewHolder.mTextView_email = (TextView)convertView.findViewById(R.id.person_email);
convertView.setTag(mViewHolder);
}else{
mViewHolder = (ViewHolder)convertView.getTag();
}
mViewHolder.mTextView_id.setText(mList.get(position).getId()+"");
mViewHolder.mTextView_name.setText(mList.get(position).getName());
mViewHolder.mTextView_height.setText(mList.get(position).getHeight()+"");
mViewHolder.mTextView_email.setText(mList.get(position).getEmail());
return convertView;
}

class ViewHolder{
TextView mTextView_id;
TextView mTextView_name;
TextView mTextView_height;
TextView mTextView_email;
}

}



package com.androidleaf.sqlite.database;

import java.util.ArrayList;

import com.androidleaf.sqlite.database.DatabaseOpenHelper.SQLiteDataTable;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;


public abstract class DataBaseManager<T> implements IDatabaseManager,SQLiteDataTable{

private static final String TAG = "sqlite_log";
private SQLiteDatabase mSqLiteDatabase;

public DataBaseManager(Context mContext){
DatabaseOpenHelper mDatabaseOpenHelper = DatabaseOpenHelper.getDatabaseOpenHelper(mContext);
//设置事件监听
mDatabaseOpenHelper.setOnSQLiteDataTable(this);
//获取SQLiteDatabase对象,创建或打开数据库
mSqLiteDatabase = mDatabaseOpenHelper.getWritableDatabase();
}

/**
* 插入数据操作
* @param mContentValues 插入的数据集合
* @return boolean 布尔值,true为插入成功,false插入失败
*/
@Override
public boolean insert(ContentValues mContentValues) {
// TODO Auto-generated method stub
mSqLiteDatabase.beginTransaction();
try {
long rowId = mSqLiteDatabase.insertOrThrow(getTableName(), null, mContentValues);
mSqLiteDatabase.setTransactionSuccessful();
return rowId != -1;
} catch (Exception e) {
// TODO: handle exception
Log.e(TAG, "The insert operation failed");
}finally{
mSqLiteDatabase.endTransaction();
}
return false;
}

/**
* 更新数据操作
* @param mContentValues 需要更新的数据集合
* @return boolean 布尔值,true为更新成功,false更新失败
*/
@Override
public boolean update(ContentValues mContentValues)
  • 打赏
  • 举报
回复
相关推荐
发帖
Android
加入

7.9w+

社区成员

移动平台 Android
申请成为版主
帖子事件
创建了帖子
2018-07-11 03:44
社区公告
暂无公告