累的我够够的!!
运行效果图:
①
② 连击两下点击‘增’加数据按钮 并重启程序:
③重启程序后 点击一下 改 按钮:
④ 点击查询 按钮:
⑤ 点击删除按钮 并重启程序:
项目框架图:
一:MyDatabaseHelper.java的全部代码:
package cn.example.d2_sqlite_book2.activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class MyDatabaseHelper extends SQLiteOpenHelper
{
public static final String Animal = "create table animal()";
private Context mContext;
public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(Animal);
Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
二:StudyAnimalActivity.java的全部代码:
package cn.example.d2_sqlite_book2.activity;
import java.util.List;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import cn.example.d2_sqlite_book2.R;
import cn.example.d2_sqlite_book2.adapter.AnimalAdapter;
import cn.example.d2_sqlite_book2.dao.AnimalDao;
import cn.example.d2_sqlite_book2.entity.Animal;
import cn.example.d2_sqlite_book2.util.DialogUtil;
public class StudyAnimalActivity extends Activity
{
private List<Animal> animalList;
private AnimalDao animalDao;
private ListView lvAnimalList;
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animal);
dbHelper = new MyDatabaseHelper(this, "idioms14.db", null, 122);
initAnimals();
lvAnimalList = (ListView) findViewById(R.id.lvAnimalList);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
AnimalAdapter animalAdapter = new AnimalAdapter(this, R.layout.animal_item, animalList);
lvAnimalList.setAdapter(animalAdapter);
lvAnimalList.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
Animal animal = animalList.get(position);
String result = animal.getName() + "\n" + animal.getPronounce() + "\n【解释】: " + animal.getExplain()
+ "\n【近义词】: " + animal.getHomoionym() + "\n【反义词】: " + animal.getAntonym() + "\n【来源】: "
+ animal.getDerivation() + "\n【示例】: " + animal.getExamples();
DialogUtil.showDialog(result, StudyAnimalActivity.this);
}
});
button1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("name", "陈祥");
values.put("pronounce", "chen xiang");
values.put("explain", "滨州学院的一名学生");
values.put("antonym", "chen");
values.put("homoionym", "滨州学院的一名学生");
values.put("derivation", "滨州学院的一名学生");
values.put("examples", "滨州学院的一名学生");
db.insert("animal", null, values); // 插入第一条数据
}
});
button2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("animal", "name = ?", new String[] { "陈祥" });
}
});
button3.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("antonym", "山东菏泽的同学");
values.put("homoionym", "山东菏泽的同学");
values.put("derivation", "山东菏泽的同学");
values.put("examples", "山东菏泽的同学");
db.update("animal", values, "name = ?", new String[] { "陈祥" });
}
});
button4.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 查询Book表中所有的数据
Cursor cursor = db.query("animal", null, null, null, null, null, null);
if (cursor.moveToFirst())
{
do
{
// 遍历Cursor对象,取出数据并打印
String name = cursor.getString(cursor.getColumnIndex("name"));
String pronounce = cursor.getString(cursor.getColumnIndex("pronounce"));
String explain = cursor.getString(cursor.getColumnIndex("explain"));
String antonym = cursor.getString(cursor.getColumnIndex("antonym"));
Log.d("MainActivity", "book name is " + name);
Log.d("MainActivity", "book pronounce is " + pronounce);
Log.d("MainActivity", "book explain is " + explain);
Log.d("MainActivity", "book antonym is " + antonym);
} while (cursor.moveToNext());
}
cursor.close();
}
});
}
private void initAnimals()
{
animalDao = AnimalDao.getInstance(this);
animalList = animalDao.getAllAnimals();
}
}
三 :animalAdpter.java的全部代码:
package cn.example.d2_sqlite_book2.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import cn.example.d2_sqlite_book2.R;
import cn.example.d2_sqlite_book2.entity.Animal;
public class AnimalAdapter extends ArrayAdapter<Animal>
{
private int resourceId;
public AnimalAdapter(Context context, int resource, List<Animal> objects)
{
super(context, resource, objects);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
Animal animal = getItem(position); // 获取当前项的Animal实例
View view;
ViewHolder viewHolder;
if (convertView == null)
{
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
viewHolder.btnSave = (ImageButton) view.findViewById(R.id.btnSave);
viewHolder.btnSave.setFocusable(false);
viewHolder.btnSave.setFocusableInTouchMode(false);
view.setTag(viewHolder); // 将ViewHolder存储在View中
} else
{
view = convertView;
viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder
}
viewHolder.tvName.setText(animal.getName());
return view;
}
class ViewHolder
{
TextView tvName;
ImageButton btnSave;
}
}
四:AnimalDao.java的全部代码:
package cn.example.d2_sqlite_book2.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.example.d2_sqlite_book2.db.DBOpenHelper;
import cn.example.d2_sqlite_book2.entity.Animal;
public class AnimalDao
{
private static AnimalDao animalDao;
private SQLiteDatabase db;
/**
* 将构造方法私有化
*/
private AnimalDao(Context context)
{
DBOpenHelper dbHelper = new DBOpenHelper(context);
db = dbHelper.openDatabase();
}
/**
* 获取AnimalDao的实例。
*/
public synchronized static AnimalDao getInstance(Context context)
{
if (animalDao == null)
{
animalDao = new AnimalDao(context);
}
return animalDao;
}
/**
* 从数据库读取所有的动物类成语。
*/
public List<Animal> getAllAnimals()
{
List<Animal> list = new ArrayList<Animal>();
Cursor cursor = db.query("animal", null, null, null, null, null, null);
if (cursor.moveToFirst())
{
do
{
Animal animal = new Animal();
animal.setId(cursor.getInt(cursor.getColumnIndex("_id")));
animal.setName(cursor.getString(cursor.getColumnIndex("name")));
animal.setPronounce(cursor.getString(cursor.getColumnIndex("pronounce")));
animal.setAntonym(cursor.getString(cursor.getColumnIndex("antonym")));
animal.setHomoionym(cursor.getString(cursor.getColumnIndex("homoionym")));
animal.setDerivation(cursor.getString(cursor.getColumnIndex("derivation")));
animal.setExamples(cursor.getString(cursor.getColumnIndex("examples")));
list.add(animal);
} while (cursor.moveToNext());
}
return list;
}
}
五:DBOpenHelper.java的全部代码:
package cn.example.d2_sqlite_book2.db;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import cn.example.d2_sqlite_book2.R;
/*
* 实现将数据库文件从raw目录拷贝到手机里存放数据库的位置
*/
public class DBOpenHelper
{
private final int BUFFER_SIZE = 400000;// 缓冲区大小
public static final String DB_NAME = "idioms14.db"; // 保存的数据库文件名
public static final String PACKAGE_NAME = "cn.example.d2_sqlite_book2";// 应用的包名
public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME
+ "/databases"; // 在手机里存放数据库的位置
private Context context;
public DBOpenHelper(Context context)
{
this.context = context;
}
public SQLiteDatabase openDatabase()
{
try
{
File myDataPath = new File(DB_PATH);
if (!myDataPath.exists())
{
myDataPath.mkdirs();// 如果没有这个目录则创建
}
String dbfile = myDataPath + "/" + DB_NAME;
if (!(new File(dbfile).exists()))
{// 判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
InputStream is = context.getResources().openRawResource(R.raw.idioms14);
FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0)
{
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
return db;
} catch (FileNotFoundException e)
{
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e)
{
Log.e("Database", "IO exception");
e.printStackTrace();
}
return null;
}
}
六:Animal.java的全部代码:
package cn.example.d2_sqlite_book2.entity;
public class Animal
{
private int id;
private String name;// 成语名称
private String pronounce;// 成语发音
private String explain;// 成语解释
private String antonym;// 反义词
private String homoionym;// 同义词
private String derivation;// 源自
private String examples;// 例子
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 getPronounce()
{
return pronounce;
}
public void setPronounce(String pronounce)
{
this.pronounce = pronounce;
}
public String getExplain()
{
return explain;
}
public void setExplain(String explain)
{
this.explain = explain;
}
public String getAntonym()
{
return antonym;
}
public void setAntonym(String antonym)
{
this.antonym = antonym;
}
public String getHomoionym()
{
return homoionym;
}
public void setHomoionym(String homoionym)
{
this.homoionym = homoionym;
}
public String getDerivation()
{
return derivation;
}
public void setDerivation(String derivation)
{
this.derivation = derivation;
}
public String getExamples()
{
return examples;
}
public void setExamples(String examples)
{
this.examples = examples;
}
}
七:DialogUtil.java的全部代码:
package cn.example.d2_sqlite_book2.util;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import cn.example.d2_sqlite_book2.R;
public class DialogUtil
{
public static void showDialog(String result, Context context)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.dialog_info, null);
builder.setView(view);
TextView tvIdiomInfo = (TextView) view.findViewById(R.id.tvIdiomInfo);
tvIdiomInfo.setText(result);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
builder.create().show();
}
}
1::dialog_info.xml的全部代码;
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_ling"
android:orientation="vertical" >
<TextView
android:id="@+id/tvIdiomInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</ScrollView>
2::animal_item.xml的全部代码:
<?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"
android:padding="10dp" >
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="助人为乐"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageButton
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/tvName"
android:background="@null"
android:src="@drawable/btnsave" />
</RelativeLayout>
3::activity_animal.xml的全部代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:background="@drawable/bg_animal" android:orientation="vertical" > <ListView android:id="@+id/lvAnimalList" android:layout_width="match_parent" android:layout_height="match_parent" android:listSelector="#00000000" > <!-- android:layoutAnimation="@anim/layout_anim_listview" --> </ListView> </LinearLayout> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="增" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/button1" android:text="删" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/button1" android:text="改" /> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/button2" android:layout_toRightOf="@id/button3" android:text="查" /> </RelativeLayout> </LinearLayout>