如果您想了解android–SQLite数据库“上下文”传递给适配器的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于AndroidSQLite数据库中的表详解、androidSQLite数
如果您想了解android – SQLite数据库“上下文”传递给适配器的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于Android SQLite数据库中的表详解、android SQLite数据库使用实例、Android SQLite数据库升级方案、Android SQLite数据库已损坏的有价值的信息。
本文目录一览:- android – SQLite数据库“上下文”传递给适配器
- Android SQLite数据库中的表详解
- android SQLite数据库使用实例
- Android SQLite数据库升级方案
- Android SQLite数据库已损坏
android – SQLite数据库“上下文”传递给适配器
由于我是一个初学者,我在理解“context”参数时遇到了问题.
我想从不扩展活动的类中调用适配器并插入/更新/删除记录,在此示例中代表上下文.
现在我不知道在适配器中作为上下文传递什么,因为我没有从活动调用适配器.
有人可以解释一下吗
解决方法
Android SQLite数据库中的表详解
Android sqlite数据库
前言
以前写PHP的时候,内置了print_r()和var_dump()两个函数用于打印输出任意类型的数据内部结构,现在做Android的开发,发现并没有这种类似的函数,对于数据库的查看很不方便,于是就写了一下查看数据库表的方法代码。
代码实现
import java.util.Arrays; import android.app.Activity; 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.Button; public class SecondActivity extends Activity { public static final String TAG = "Debug Info"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((Button)findViewById(R.id.btnQue)).setonClickListener(new OnClickListener() { @Override public void onClick(View v) { MyDatabaseHelper dbhelper = new MyDatabaseHelper(SecondActivity.this,"BookStore.db",null,1); sqliteDatabase db = dbhelper.getWritableDatabase(); //核心区 //读取系统表 sqlite_master String sql = "select * from sqlite_master"; Cursor cursor = db.rawQuery(sql,null); //打印表的所有列名 Log.i(TAG,Arrays.toString(cursor.getColumnNames())); //打印当前数据库中的所有表 if (cursor.movetoFirst()) { do { String str = ""; for (String item : cursor.getColumnNames()) { str += item + ": " + cursor.getString(cursor.getColumnIndex(item)) + "\n"; } Log.i(TAG,str); } while (cursor.movetoNext()); } } }); } }
功能扩展
查看表是否存在
public Boolean tableIsExist(sqliteDatabase db,String tableName){ boolean result = false; Cursor cursor = null; if(tableName == null){ return result; } String sql = "select count(*) from sqlite_master where type ='table' and name ='"+tableName.trim()+"'"; cursor = db.rawQuery(sql,null); if(cursor.movetoNext()){ if(cursor.getInt(0) > 0){ result = true; } } return result; }
查看数据库中有哪些表
public ArrayList<String> tablesInDB(sqliteDatabase db){ ArrayList<String> list = new ArrayList<String>(); String sql = "select name from sqlite_master where type='table'"; Cursor cursor = db.rawQuery(sql,null); if (cursor.movetoFirst()) { do { list.add(cursor.getString(0)); } while (cursor.movetoNext()); } return list; }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
android SQLite数据库使用实例
创建数据库帮助类DbHelper.java:
package com.example.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists tb_people"+
"(_id integer primary key autoincrement,"+
"name varchar(20),"+
"phone varchar(12),"+
"mobile varchar(12),"+
"email varchar(30))");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
主布局文件:
ch9_sqlmain.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" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="所有联系人:"
android:textSize="15px"/>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="40px"
android:layout_height="wrap_content"
android:text="编号"/>
<TextView android:layout_width="50px"
android:layout_height="wrap_content"
android:text="姓名"/>
<TextView android:layout_width="80px"
android:layout_height="wrap_content"
android:text="电话"/>
<TextView android:layout_width="80px"
android:layout_height="wrap_content"
android:text="手机"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="电子信箱"/>
</LinearLayout>
<ListView android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/list_people"/>
</LinearLayout>
编写ListView的Item显示布局文件ch9_peoplelist.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="horizontal" >
<TextView android:id="@+id/id"
android:layout_width="40px"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/name"
android:layout_width="50px"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/phone"
android:layout_width="80px"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/mobile"
android:layout_width="80px"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
主活动类SqlMainActivity.java:
package com.example.ch9;
import com.example.baseexample.R;
import com.example.db.DbHelper;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class SqlMainActivity extends Activity {
private ListView list_people;
private DbHelper dbhelper;
private SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.ch9_sqlmain);
list_people = (ListView)findViewById(R.id.list_people);
dbhelper = new DbHelper(this, "Db_People", null, 1);
db = dbhelper.getReadableDatabase();
Cursor c = db.query("tb_people", new String[]{"_id","name","phone","mobile","email"}, null, null, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.ch9_peoplelist, c, new String[]{"_id","name","phone","mobile","email"}, new int[]{R.id.id,R.id.name,R.id.phone,R.id.mobile,R.id.email});
this.list_people.setAdapter(adapter);
this.registerForContextMenu(list_people);
}
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE,Menu.FIRST+1,1,"添加").setIcon(android.R.drawable.ic_menu_add);
menu.add(Menu.NONE,Menu.FIRST+1,2,"退出").setIcon(android.R.drawable.ic_menu_delete);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case Menu.FIRST+1:
Intent intent = new Intent();
intent.setClass(SqlMainActivity.this, AddPeopleActivity.class);
startActivity(intent);
break;
case Menu.FIRST+2:finish();
break;
}
return super.onOptionsItemSelected(item);
}
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.add(0,3,0,"修改");
menu.add(0, 4, 0, "删除");
}
public boolean onContextItemSelected(MenuItem item){
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
switch(item.getItemId()){
case 3:
String name=((TextView)menuInfo.targetView.findViewById(R.id.name)).getText().toString();
String phone=((TextView)menuInfo.targetView.findViewById(R.id.phone)).getText().toString();
String mobile=((TextView)menuInfo.targetView.findViewById(R.id.mobile)).getText().toString();
String email=((TextView)menuInfo.targetView.findViewById(R.id.email)).getText().toString();
Intent intent = new Intent();
intent.setClass(SqlMainActivity.this, AddPeopleActivity.class);
Bundle bundle = new Bundle();
bundle.putLong("id", menuInfo.id);
bundle.putString("name", name);
bundle.putString("phone", phone);
bundle.putString("mobile", mobile);
bundle.putString("email", email);
intent.putExtras(bundle);
startActivity(intent);
break;
case 4:
dbhelper = new DbHelper(this,"Db_People",null,1);
db = dbhelper.getWritableDatabase();
db.delete("tb_people", "_id=?", new String[]{menuInfo.id+""});
break;
}
return true;
}
}
布局文件ch9_addpeople.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="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="用户名"
android:layout_weight="2"/>
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edt_name"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="联系电话"
android:layout_weight="2"/>
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edt_phone"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="手机"
android:layout_weight="2"/>
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edt_mobile"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="电子信箱"
android:layout_weight="2"/>
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edt_email"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/bt_save"
android:text="保存"
android:layout_weight="1"/>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/bt_cancel"
android:text="取消"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
创建活动AddPeopleActivity.java:
package com.example.ch9;
import com.example.baseexample.R;
import com.example.db.DbHelper;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddPeopleActivity extends Activity {
private EditText edt_name;
private EditText edt_phone;
private EditText edt_mobile;
private EditText edt_email;
private Button bt_save;
String name,phone,mobile,email;
DbHelper dbhelper;
SQLiteDatabase db;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.ch9_addpeople);
edt_name=(EditText)findViewById(R.id.edt_name);
edt_phone=(EditText)findViewById(R.id.edt_phone);
edt_mobile=(EditText)findViewById(R.id.edt_mobile);
edt_email=(EditText)findViewById(R.id.edt_email);
bt_save = (Button)findViewById(R.id.bt_save);
bundle = this.getIntent().getExtras();
if(bundle!=null){
edt_name.setText(bundle.getString("name"));
edt_phone.setText(bundle.getString("phone"));
edt_mobile.setText(bundle.getString("mobile"));
edt_email.setText(bundle.getString("email"));
}
bt_save.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
name = edt_name.getText().toString();
phone = edt_phone.getText().toString();
mobile = edt_mobile.getText().toString();
email = edt_email.getText().toString();
ContentValues value = new ContentValues();
value.put("name", name);
value.put("phone", phone);
value.put("mobile", mobile);
value.put("email", email);
DbHelper dbhelper = new DbHelper(AddPeopleActivity.this,"Db_People",null,1);
SQLiteDatabase db = dbhelper.getWritableDatabase();
long status;
if(bundle!=null){
status = db.update("tb_people", value, "_id=?", new String[]{bundle.getLong("id")+""});
}else{
status = db.insert("tb_people", null, value);
}
if(status!=-1){
Toast.makeText(AddPeopleActivity.this, "保存成功", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(AddPeopleActivity.this, "保存失败", Toast.LENGTH_LONG).show();
}
}
});
}
}
Android SQLite数据库升级方案
例如一个数据库表
19版本是2个字段
20版本是3个字段
21版本是4个字段
package com.yzc.atclient.service.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import com.allcam.atclient.app.ClientApplication;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String DB_NAME = "allcam_db";
private static final int VERSION = 1;
private static volatile DatabaseHelper instance;
public DatabaseHelper(Context context)
{
this(context, DB_NAME, null, VERSION);
}
public DatabaseHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
public static DatabaseHelper getInstance()
{
if (null == instance)
{
synchronized (DatabaseHelper.class)
{
if (null == instance)
{
instance = new DatabaseHelper(ClientApplication.getAppContext());
}
}
}
return instance;
}
@Override
public void onCreate(SQLiteDatabase db)
{
CardUserTable.createTable(db);
TaskStatusTable.createTable(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//在这里组合case 判断 升级
}
}
例如:
for (int j = oldVersion; j <= newVersion; j++) {
switch (j) {
case 2:
//创建临时表
db.execSQL(TEMP_SQL_CREATE_TABLE_SUBSCRIBE);
//执行OnCreate方法,这个方法中放的是表的初始化操作工作,比如创建新表之类的
onCreate(db);
//删除之前的表里面的那4条默认的数据
for (int i = 0; i < arrWhereAct.length; i++) {
db.execSQL(DELETE_TEMP_SUBSCRIBE + arrWhereAct[i]);
}
//将临时表中的数据放入表A
Cursor cursor = db.rawQuery(INSERT_SUBSCRIBE, null);
if (cursor.moveToFirst()) {
do {
db.execSQL(cursor.getString(cursor
.getColumnIndex("insertSQL")));
} while (cursor.moveToNext());
}
cursor.close();
//将临时表删除掉
db.execSQL(DROP_TEMP_SUBSCRIBE);
break;
default:
break;
}
}
Android SQLite数据库已损坏
现在大约有300人使用我的Android应用程序,每次使用此堆栈跟踪向服务器发送崩溃报告时:
android.database.sqlite.sqliteDatabaseCorruptException: database disk image is malformed at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2596) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621) at android.app.ActivityThread.access$2200(ActivityThread.java:126) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:123) at android.app.ActivityThread.main(ActivityThread.java:4595) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:521) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.sqlite.sqliteDatabaseCorruptException: database disk image is malformed at android.database.sqlite.sqliteQuery.native_fill_window(Native Method) at android.database.sqlite.sqliteQuery.fillWindow(sqliteQuery.java:75) at android.database.sqlite.sqliteCursor.fillWindow(sqliteCursor.java:295) at android.database.sqlite.sqliteCursor.getCount(sqliteCursor.java:276) at android.database.AbstractCursor.movetoPosition(AbstractCursor.java:171) at android.database.AbstractCursor.movetoFirst(AbstractCursor.java:248)
结果是应用程序崩溃并且数据库中的所有数据都丢失了.
需要注意的一点是,每次我读取或写入数据库时,我都会得到一个新的sqliteDatabase,并在完成后立即将其关闭.我这样做是为了防止这种腐败错误.
我还尝试使用单个静态对象同步所有数据库读取和写入,这似乎没有帮助.
这可能只是一个sqlite错误吗?
我在这里找到了与内置电子邮件应用程序类似的错误:http://code.google.com/p/android/issues/detail?id=5610.
这是我的代码:
public class keyvalueTableAdapter extends BaseTableAdapter { private String tableName; private String keyColumnName; private String valueColumnName; public keyvalueTableAdapter(Context context,String tableName,String keyColumnName,String valueColumnName) { super(context); this.tableName = tableName; this.keyColumnName = keyColumnName; this.valueColumnName = valueColumnName; } protected String getStringValue(int key) { Cursor cursor = null; sqliteDatabase db = null; String value; try { db = dbOpenHelper.getReadableDatabase(); cursor = db.query(true,tableName,new String[] { valueColumnName },keyColumnName + "=" + key,null,null); if ((cursor.getCount() == 0) || !cursor.movetoFirst()) { value = null; } else { value = cursor.getString(0); } } finally { if (cursor != null) cursor.close(); if (db != null) db.close(); dbOpenHelper.close(); } return value; } } public abstract class BaseTableAdapter { protected DbOpenHelper dbOpenHelper; public BaseTableAdapter(Context context) { this.dbOpenHelper = new DbOpenHelper(context,DatabaseSettings.DATABASE_NAME,DatabaseSettings.DATABASE_VERSION); } }
解决方法
“the DB holds session information so
it’s not very feasible to do a backup.
The data changes by the minute”
您应该尝试使用SharedPreferences:它存储键值对(在后台,它使用文件).
存储值:
SharedPreferences sp=MyActivity.getSharedPreferences("Name",Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("key",value); editor.putBoolean("another",true); editor.commit();
检索数据:
sp.getString("key","Not found"); // "Not found" is the default value // if sp does not contain the specified key sp.getBoolean("another",false); // false is the default value // if sp does not contain the specified key
有关更详细的说明,请参见getSharedPreferences和SharedPreferences.
今天的关于android – SQLite数据库“上下文”传递给适配器的分享已经结束,谢谢您的关注,如果想了解更多关于Android SQLite数据库中的表详解、android SQLite数据库使用实例、Android SQLite数据库升级方案、Android SQLite数据库已损坏的相关知识,请在本站进行查询。
本文标签: