0

我是 android 的新手。我正在尝试读取数据库并将结果放入 List 活动中。以下是条目活动。

  package com.sanjay.listdemo;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

    protected EditText searchText;
    protected SQLiteDatabase db;
    protected Cursor cursor;
    protected ListAdapter adapter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        searchText = (EditText) findViewById(R.id.searchText);
        db = (new DatabaseHelper(this)).getWritableDatabase();

    }

//    public void onListItemClick(ListView parent, View view, int position, long id) {
//      Intent intent = new Intent(this, );
//      Cursor cursor = (Cursor) adapter.getItem(position);
//      intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
//      startActivity(intent);
//    }

    public void search(View view) {
        // || is the concatenation operation in SQLite
        cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employees WHERE firstName || ' ' || lastName LIKE ?", 
                        new String[]{"%" + searchText.getText().toString() + "%"});
        adapter = new SimpleCursorAdapter(
                this, 
                R.layout.simple_list_item, 
                cursor, 
                new String[] {"firstName", "lastName", "title"}, 
                new int[] {R.id.firstname, R.id.lastname, R.id.title});
        setListAdapter(adapter);
    }

}

数据库助手.java

package samples.employeedirectory;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "employee_directory2";

    protected Context context;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String s;
        try {
            Toast.makeText(context, "1", 2000).show();
            InputStream in = context.getResources().openRawResource(R.raw.sql);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in, null);
            NodeList statements = doc.getElementsByTagName("statement");
            for (int i=0; i<statements.getLength(); i++) {
                s = statements.item(i).getChildNodes().item(0).getNodeValue();
                db.execSQL(s);
                db.close();
            }
        } catch (Throwable t) {
            Toast.makeText(context, t.toString(), 50000).show();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS employees");
        onCreate(db);
    }

}

sql.xml

<sql>
<statement>
CREATE TABLE IF NOT EXISTS employees (
    _id INTEGER PRIMARY KEY AUTOINCREMENT, 
    firstName VARCHAR(50), 
    lastName VARCHAR(50), 
    title VARCHAR(50), 
    department VARCHAR(50), 
    managerId INTEGER, 
    city VARCHAR(50), 
    officePhone VARCHAR(30), 
    cellPhone VARCHAR(30), 
    email VARCHAR(30), 
    picture VARCHAR(200))
</statement>
<statement>INSERT INTO employees VALUES(1,'Ryan','Howard','Vice President, North East', 'Management', NULL, 'Scranton','570-999-8888','570-999-8887','ryan@dundermifflin.com','howard.jpg')</statement>
<statement>INSERT INTO employees VALUES(2,'Michael','Scott','Regional Manager','Management',1,'Scranton','570-888-9999','570-222-3333','michael@dundermifflin.com','scott.jpg')</statement>
<statement>INSERT INTO employees VALUES(3,'Dwight','Schrute','Assistant Regional Manager','Management',2,'Scranton','570-444-4444','570-333-3333','dwight@dundermifflin.com','schrute.jpg')</statement>
<statement>INSERT INTO employees VALUES(4,'Jim','Halpert','Assistant Regional Manager','Manage',2,'Scranton','570-222-2121','570-999-1212','jim@dundermifflin.com','halpert.jpg')</statement>
<statement>INSERT INTO employees VALUES(5,'Pamela','Beesly','Receptionist','',2,'Scranton','570-999-5555','570-999-7474','pam@dundermifflin.com','beesly.jpg')</statement>
<statement>INSERT INTO employees VALUES(6,'Angela','Martin','Senior Accountant','Accounting',2,'Scranton','570-555-9696','570-999-3232','angela@dundermifflin.com','martin.jpg')</statement>
<statement>INSERT INTO employees VALUES(7,'Kevin','Malone','Accountant','Accounting',6,'Scranton','570-777-9696','570-111-2525','kmalone@dundermifflin.com','malone.jpg')</statement>
<statement>INSERT INTO employees VALUES(8,'Oscar','Martinez','Accountant','Accounting',6,'Scranton','570-321-9999','570-585-3333','oscar@dundermifflin.com','martinez.jpg')</statement>
<statement>INSERT INTO employees VALUES(9,'Creed','Bratton','Quality Assurance','Customer Services',2,'Scranton','570-222-6666','333-8585','creed@dundermifflin.com','bratton.jpg')</statement>
<statement>INSERT INTO employees VALUES(10,'Andy','Bernard','Sales Director','Sales',2,'Scranton','570-555-0000','570-546-9999','andy@dundermifflin.com','bernard.jpg')</statement>
<statement>INSERT INTO employees VALUES(11,'Phyllis','Lapin','Sales Representative','Sales',10,'Scranton','570-141-3333','570-888-6666','phyllis@dundermifflin.com','lapin.jpg')</statement>
<statement>INSERT INTO employees VALUES(12,'Stanley','Hudson','Sales Representative','Sales',10,'Scranton','570-700-6666','570-777-6666','shudson@dundermifflin.com','hudson.jpg')</statement>
<statement>INSERT INTO employees VALUES(13,'Meredith','Palmer','Supplier Relations','Customer Services',2,'Scranton','570-555-8888','570-777-2222','meredith@dundermifflin.com','palmer.jpg')</statement>
<statement>INSERT INTO employees VALUES(14,'Kelly','Kapoor','Customer Service Rep.','Customer Services',2,'Scranton','570-123-9654','570-125-3666','kelly@dundermifflin.com','kapoor.jpg')</statement>
</sql>

我收到“找不到这样的表:emplyees”。请任何人都可以建议我哪里错了。因为 48 小时我正在尝试解决这个问题。

4

1 回答 1

2

创建数据库时,不要在每条语句上关闭数据库:

转这个:

for (int i=0; i<statements.getLength(); i++) {
  s = statements.item(i).getChildNodes().item(0).getNodeValue();
  db.execSQL(s);
  db.close();
}

进入这个:

for (int i=0; i<statements.getLength(); i++) {
  s = statements.item(i).getChildNodes().item(0).getNodeValue();
  db.execSQL(s);
}

在方法中根本不应该关闭数据库onCreate

尝试执行第二条语句时您没有收到错误的事实让我相信您没有正确执行这些语句。

PS:我也强烈建议你把你的rawQuery变成正确的 AndroidSqliteDatabase查询

PS2:你也应该关闭你的in InputStream.

于 2013-04-14T19:37:47.430 回答