从数据库检索数据到列表视图失败

Posted

技术标签:

【中文标题】从数据库检索数据到列表视图失败【英文标题】:Retrieving data from database to listview failed 【发布时间】:2013-08-07 09:53:30 【问题描述】:

我的程序包含一个Activityclass 和一个数据库class。我用来将数据库值保存到ListView 的代码有一些问题。 以下是Activity中的inner class

class getclicker extends ListActivity implements Button.OnClickListener 
    public void onClick(View v) 

        String datevalue = date.getText().toString();
        String Userselectvalue = userSelection.getText().toString();
        cursor1 = eventsData.getContact(datevalue, Userselectvalue);
        String[] fromColumns =  classdbOpenHelper.KEY_EVENT ;
        int[] toViews =  R.id.event ;
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.events, cursor1, fromColumns, toViews, 0);
        listView = getListView();
        listView.setAdapter(adapter);

    

    public void onDestroy() 
        eventsData.close();
    

sqlite 类包含

public Cursor getContact(String datevalue, String Userselectvalue) 
    String selection = classdbOpenHelper.KEY_DESC + " = '" + Userselectvalue + "'" + " AND " + classdbOpenHelper.KEY_DATE + " = '" + datevalue + "'";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(classdbOpenHelper.DATABASE_TABLE, new String[]  classdbOpenHelper.KEY_ROWID, classdbOpenHelper.KEY_DESC, classdbOpenHelper.KEY_EVENT, classdbOpenHelper.KEY_DATE ,
            selection, null, null, null, null);
    if (cursor != null) 
        cursor.moveToFirst();
    
    return cursor;

【问题讨论】:

如果只考虑以上信息,我会给能够解决此问题的人 1k 积分。 @gunar 挑战接受 请问有什么错误? 哈哈哈哈哈哈哈哈哈:) 到底是什么问题?什么不工作? 【参考方案1】:

关注我的代码

将以下内容写入layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_
    android:layout_
    >
<TextView  
    android:layout_
    android:layout_
    android:text="@string/hello"
    />
</LinearLayout>

将以下内容写入 DBHelper.java:

package com.example.ListViewFromSQLiteDB;

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

public class DBHelper extends SQLiteOpenHelper

    public SQLiteDatabase DB;
    public String DBPath;
    public static String DBName = "sample";
    public static final int version = '1';
    public static Context currentContext;
    public static String tableName = "Resource";


    public DBHelper(Context context) 
        super(context, DBName, null, version);
        currentContext = context;
        DBPath = "/data/data/" + context.getPackageName() + "/databases";
        createDatabase();

    

    @Override
    public void onCreate(SQLiteDatabase db) 
        // TODO Auto-generated method stub

    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        // TODO Auto-generated method stub

    

    private void createDatabase() 
        boolean dbExists = checkDbExists();

        if (dbExists) 
            // do nothing
         else 
            DB = currentContext.openOrCreateDatabase(DBName, 0, null);
            DB.execSQL("CREATE TABLE IF NOT EXISTS " +
                    tableName +
                    " (LastName VARCHAR, FirstName VARCHAR," +
                    " Country VARCHAR, Age INT(3));");

            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('M','shumi','India',25);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('C','sarah','India',25);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('D','Lavya','USA',20);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('V','Avi','EU',25);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('T','Shenoi','Bangla',25);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('L','Lamha','Australia',20);");
        


    

    private boolean checkDbExists() 
        SQLiteDatabase checkDB = null;

        try 
            String myPath = DBPath + DBName;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);

         catch (SQLiteException e) 

            // database does't exist yet.

        

        if (checkDB != null) 

            checkDB.close();

        

        return checkDB != null ? true : false;
    

将以下内容写入清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.ListViewFromSQLiteDB"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="com.example.ListViewFromSQLiteDB.DataListView"
                  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>

</manifest>

ListViewFromSQLiteDB.java 文件并在其中编写以下代码:

package com.example.ListViewFromSQLiteDB;

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;
import android.widget.TextView;

public class DataListView extends ListActivity 

    private ArrayList<String> results = new ArrayList<String>();
    private String tableName = DBHelper.tableName;
    private SQLiteDatabase newDB;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        openAndQueryDatabase();

        displayResultList();


    
    private void displayResultList() 
        TextView tView = new TextView(this);
        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);

    
    private void openAndQueryDatabase() 
        try 
            DBHelper dbHelper = new DBHelper(this.getApplicationContext());
            newDB = dbHelper.getWritableDatabase();
            Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
                    tableName +
                    " where Age > 10 LIMIT 4", null);

            if (c != null ) 
                if  (c.moveToFirst()) 
                    do 
                        String firstName = c.getString(c.getColumnIndex("FirstName"));
                        int age = c.getInt(c.getColumnIndex("Age"));
                        results.add("Name: " + firstName + ",Age: " + age);
                    while (c.moveToNext());
                 
                       
         catch (SQLiteException se ) 
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
         finally 
            if (newDB != null) 
                newDB.execSQL("DELETE FROM " + tableName);
                newDB.close();
        

    


现在只需运行代码 ....

【讨论】:

【参考方案2】:

您是否在光标中获取数据?

请检查此更改此行并尝试 字符串选择 = classdbOpenHelper.KEY_DESC + "='" + Userselectvalue + "'" + " AND " + classdbOpenHelper.KEY_DATE + "='" + datevalue + "'";

【讨论】:

以上是关于从数据库检索数据到列表视图失败的主要内容,如果未能解决你的问题,请参考以下文章

如何从firebase检索多个数据到android中的列表视图?

我如何从firebase检索数据到android listview顶部[重复]

使用查询从 sql 视图中检索引用表的列表

单击列表视图项时检索的值

从列表视图中检索数据并将其显示在文本视图/图像视图中

无法从数据库中检索数据,以完成列表视图