本文介绍了如何从SQLite数据库读取数据并将数据显示在列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从SQLite数据库提取数据,并显示在列表视图。
我做这在我的code,但我得到一个错误:
公共类ShoewDataListActivity扩展ListActivity { @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.grupadd);
按钮btnAdd =(按钮)findViewById(R.id.btnAdd);
按钮来查看=(按钮)findViewById(R.id.btnShowData);
view.setOnClickListener(新OnClickListener(){ 公共无效的onClick(视图v){
displayResultList();
}
});
btnAdd.setOnClickListener(新OnClickListener(){ 公共无效的onClick(视图v){ 布尔didItWork = TRUE; 尝试{
的EditText edtAddName =(EditText上)findViewById(R.id.editNameAdd);
字符串名称= edtAddName.getText()的toString()。
AddData进入=新AddData(ShoewDataListActivity.this);
entry.open();
entry.createEntry(名);
entry.close();
}赶上(例外五){
// e.printStackTrace();
didItWork = FALSE;
字符串错误= e.toString();
对话D =新的对话框(ShoewDataListActivity.this);
d.setTitle(发生了什么......!);
TextView的电视=新的TextView(ShoewDataListActivity.this);
tv.setText(....+误差+......);
d.setContentView(电视);
d.show(); } {最后
如果(didItWork){
//对话框D =新的对话框(GroupActivity.this);
// d.setTitle(这是确定的..........!);
// TextView的电视=新的TextView(GroupActivity.this);
// tv.setText(......全成....);
// d.setContentView(电视);
// d.show();
Toast.makeText(getBaseContext()项目保存,
Toast.LENGTH_LONG).show(); }
}
}
}); } 私人无效displayResultList(){
TextView的tView =新的TextView(本);
AddData信息=新AddData(本);
ArrayList的<串GT;结果=新的ArrayList<串GT;();
结果= info.fatchData();
tView.setText(该数据被从数据库中检索并且只有4
+的结果被显示);
。getListView()addHeaderView(tView);
setListAdapter(新ArrayAdapter<串GT;(这一点,
android.R.layout.simple_list_item_1,结果));
getListView()setTextFilterEnabled(真)。 }
}
和我Dbhelper类是:
公共类AddData { 公共静态最后的字符串标记= DbHelper.class.getSimpleName();
公共静态最后弦乐DB_NAME =Grup.db;
公共静态最终诠释DB_VERSION = 1;
公共静态最后的字符串表=Grups;
公共静态最后弦乐C_ID = BaseColumns._ID;
公共静态最后弦乐C_CREATED_AT =easy_ass_created_At;
公共静态最后弦乐C_NAME =名;
私人DbHelper ourHelper;
私人最终上下文ourContext;
私人SQLiteDatabase ourDatabase; 公共类DbHelper扩展SQLiteOpenHelper { //公共静态最后的字符串标记= DbHelper.class.getSimpleName();
//公共静态最后弦乐DB_NAME =Grup.db;
//公共静态最终诠释DB_VERSION = 1;
//公共静态最终字符串表=Grups;
//公共静态最后弦乐C_ID = BaseColumns._ID;
//公共静态最后弦乐C_CREATED_AT =easy_ass_created_At;
//公共静态最后弦乐C_NAME =名; 公共DbHelper(上下文的背景下){
超(背景下,DB_NAME,空,DB_VERSION); } @覆盖
公共无效的onCreate(SQLiteDatabase DB){ SQL字符串=(CREATE TABLE+ TABLE +(+ C_ID
+整数主键自动增量+ C_NAME
+文字不为空+););
db.execSQL(SQL);
Log.d(TAG的OnCreate SQL+ SQL); } @覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
db.execSQL(+表是否存在删除表);
this.onCreate(DB);
Log.d(TAG,********在Upgrate删除表*****); } } 公共AddData(上下文的背景下){
ourContext =背景; } 公共AddData的open()抛出的SQLException { ourHelper =新DbHelper(ourContext);
ourDatabase = ourHelper.getReadableDatabase();
返回此;
} 公共无效的close(){
ourHelper.close();
} 众长createEntry(字符串名称){
ContentValues CV =新ContentValues();
cv.put(c_name和姓名);
返回ourDatabase.insert(TABLE,空,CV);
} 公共字符串的getData(){ 的String [] =列新的String [] {C_ID,C_NAME};
光标C = ourDatabase.query(表,列,NULL,NULL,NULL,NULL,
空值);
字符串结果=;
// INT iRow = c.getColumnIndex(C_ID);
INT INAME = c.getColumnIndex(C_NAME); //对于(c.moveToFirst();! c.isAfterLast(); c.moveToLast()){
对于(布尔hasItem = c.moveToFirst(); hasItem; hasItem = C
.moveToNext()){
结果=结果++ c.getString(INAME)+\\ n;
c.moveToNext();
}
c.close();
返回结果; } 公众的ArrayList<串GT; fatchData(){ 的String [] =列新的String [] {C_ID,C_NAME};
光标C = ourDatabase.query(表,列,NULL,NULL,NULL,NULL,
空值);
字符串结果=;
ArrayList的<串GT; RESULT1 =新的ArrayList<串GT;();
// INT iRow = c.getColumnIndex(C_ID);
INT INAME = c.getColumnIndex(C_NAME); //对于(c.moveToFirst();! c.isAfterLast(); c.moveToLast()){
对于(布尔hasItem = c.moveToFirst(); hasItem; hasItem = C
.moveToNext()){ 结果=+ c.getString(INAME)+\\ n;
result1.add(结果);
c.moveToNext();
}
c.close();
返回RESULT1;
}
}
解决方案
试试这个,
AndroidManifest.xml中
<?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=http://schemas.android.com/apk/res/android
包=com.collabera.labs.sai.db
安卓版code =1
机器人:=的versionName1.0>
<应用机器人:图标=@绘制/图标机器人:标签=@字符串/ APP_NAME>
<活动机器人:名字=。CRUDonDB
机器人:标签=@字符串/ APP_NAME>
&所述;意图滤光器>
<作用机器人:名字=android.intent.action.MAIN/>
<类机器人:名字=android.intent.category.LAUNCHER/>
&所述; /意图滤光器>
< /活性GT;
< /用途>
<采用-SDK安卓的minSdkVersion =3/>
< /清单>
活动文件
进口的java.util.ArrayList;进口android.app.ListActivity;
进口android.database.Cursor;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteException;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.ArrayAdapter;公共类CRUDonDB扩展ListActivity { 私人最终字符串SAMPLE_DB_NAME =myFriendsDb;
私人最终字符串SAMPLE_TABLE_NAME =朋友; / **当第一次创建活动调用。 * /
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
ArrayList的<串GT;结果=新的ArrayList<串GT;();
SQLiteDatabase SAMPLEDB = NULL; 尝试{
SAMPLEDB = this.openOrCreateDatabase(SAMPLE_DB_NAME,MODE_PRIVATE,NULL); sampleDB.execSQL(CREATE TABLE IF NOT EXISTS+
SAMPLE_TABLE_NAME +
(姓氏VARCHAR,名字VARCHAR,+
国家VARCHAR,年龄INT(3));); sampleDB.execSQL(插入+
SAMPLE_TABLE_NAME +
VALUES('Makam','西Geetha','印度',25););
sampleDB.execSQL(插入+
SAMPLE_TABLE_NAME +
VALUES('Chittur,拉曼,印度,25););
sampleDB.execSQL(插入+
SAMPLE_TABLE_NAME +
VALUES('解决方案','Collabera','印度',20);); 光标C = sampleDB.rawQuery(SELECT名字,年龄+
SAMPLE_TABLE_NAME +
凡年龄大于10 LIMIT 5,NULL); 如果(C!= NULL){
如果(c.moveToFirst()){
做{
字符串的firstName = c.getString(c.getColumnIndex(名字));
INT年龄= c.getInt(c.getColumnIndex(时代));
results.add(+的firstName +,年龄:年龄+);
}而(c.moveToNext());
}
} this.setListAdapter(新ArrayAdapter<串GT;(这一点,android.R.layout.simple_list_item_1,结果)); }赶上(SQLiteException SE){
Log.e(的getClass()getSimpleName(),无法创建或打开数据库);
} {最后
如果(SAMPLEDB!= NULL)
sampleDB.execSQL(DELETE FROM+ SAMPLE_TABLE_NAME);
sampleDB.close();
}
}
}
How to pull Data from SQLite Database and show it on a list view.
I am doing this in my code, but I am getting an error:
public class ShoewDataListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grupadd);
Button btnAdd = (Button) findViewById(R.id.btnAdd);
Button view=(Button) findViewById(R.id.btnShowData);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
displayResultList();
}
});
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
boolean didItWork = true;
try {
EditText edtAddName=(EditText) findViewById(R.id.editNameAdd);
String name = edtAddName.getText().toString();
AddData entry = new AddData(ShoewDataListActivity.this);
entry.open();
entry.createEntry(name);
entry.close();
} catch (Exception e) {
// e.printStackTrace();
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(ShoewDataListActivity.this);
d.setTitle("What happend...!!");
TextView tv = new TextView(ShoewDataListActivity.this);
tv.setText("...." + error + "....");
d.setContentView(tv);
d.show();
} finally {
if (didItWork) {
// Dialog d = new Dialog(GroupActivity.this);
// d.setTitle("This is ok..........!!");
// TextView tv= new TextView(GroupActivity.this);
// tv.setText("....SuccessFull....");
// d.setContentView(tv);
// d.show();
Toast.makeText(getBaseContext(), "Project Saved",
Toast.LENGTH_LONG).show();
}
}
}
});
}
private void displayResultList() {
TextView tView = new TextView(this);
AddData info = new AddData(this);
ArrayList<String> results = new ArrayList<String>();
results = info.fatchData();
tView.setText("This data is retrieved from the database and only 4 "
+ "of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
}
And my Dbhelper class is:
public class AddData {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "Grup.db";
public static final int DB_VERSION = 1;
public static final String TABLE = "Grups";
public static final String C_ID = BaseColumns._ID;
public static final String C_CREATED_AT = "easy_ass_created_At";
public static final String C_NAME = "name";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper {
// public static final String TAG = DbHelper.class.getSimpleName();
// public static final String DB_NAME = "Grup.db";
// public static final int DB_VERSION = 1;
// public static final String TABLE = "Grups";
// public static final String C_ID = BaseColumns._ID;
// public static final String C_CREATED_AT = "easy_ass_created_At";
// public static final String C_NAME = "name";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = ("create table " + TABLE + " ( " + C_ID
+ " integer primary key autoincrement, " + C_NAME
+ " text not null" + ");");
db.execSQL(sql);
Log.d(TAG, "OnCreate sql" + sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE);
this.onCreate(db);
Log.d("TAG", "********On Upgrate Drop Table*****");
}
}
public AddData(Context context) {
ourContext = context;
}
public AddData open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getReadableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name) {
ContentValues cv = new ContentValues();
cv.put(C_NAME, name);
return ourDatabase.insert(TABLE, null, cv);
}
public String getData() {
String[] columns = new String[] { C_ID, C_NAME };
Cursor c = ourDatabase.query(TABLE, columns, null, null, null, null,
null);
String result = "";
// int iRow=c.getColumnIndex(C_ID);
int iName = c.getColumnIndex(C_NAME);
// for(c.moveToFirst();!c.isAfterLast();c.moveToLast()){
for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c
.moveToNext()) {
result = result + " " + c.getString(iName) + "\n";
c.moveToNext();
}
c.close();
return result;
}
public ArrayList<String> fatchData(){
String[] columns = new String[] { C_ID, C_NAME };
Cursor c = ourDatabase.query(TABLE, columns, null, null, null, null,
null);
String result="";
ArrayList<String> result1=new ArrayList<String>();
// int iRow=c.getColumnIndex(C_ID);
int iName = c.getColumnIndex(C_NAME);
// for(c.moveToFirst();!c.isAfterLast();c.moveToLast()){
for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c
.moveToNext()) {
result = " " + c.getString(iName) + "\n";
result1.add(result);
c.moveToNext();
}
c.close();
return result1;
}
}
解决方案
Try this,
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.collabera.labs.sai.db"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".CRUDonDB"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
Activity File
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class CRUDonDB extends ListActivity {
private final String SAMPLE_DB_NAME = "myFriendsDb";
private final String SAMPLE_TABLE_NAME = "friends";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase sampleDB = null;
try {
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
sampleDB.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('Makam','Sai Geetha','India',25);");
sampleDB.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('Chittur','Raman','India',25);");
sampleDB.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('Solutions','Collabera','India',20);");
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
SAMPLE_TABLE_NAME +
" where Age > 10 LIMIT 5", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
sampleDB.close();
}
}
}
这篇关于如何从SQLite数据库读取数据并将数据显示在列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!