在Android应用程序中使用外部sqlite数据库的问题

时间:2014-04-19 16:31:45

标签: android sqlite

使用外部创建的数据库(一个包含109,000条记录和大小为6.307MB的单词列表)让我头脑发热。我需要帮助找出这里出了什么问题。任何答案都将不胜感激。

这是代码:

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Build;
import android.app.*;
import android.database.Cursor;

public class MainActivity extends Activity 
{
    private DatabaseHelper db;
    private Cursor c;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] a = new String[100];
        int i=0;

       db.openDataBase();
       c = db.getWords("sl");
       db.close();

       while(c.isAfterLast())
       {
           a[i++]=c.getString(c.getColumnIndex("WORD"));
           c.moveToNext();
       }

       ListView l = (ListView)findViewById(R.id.listView1);
       l.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,a));
    }

}

import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.os.Build; import android.app.*; import android.database.Cursor; public class MainActivity extends Activity { private DatabaseHelper db; private Cursor c; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] a = new String[100]; int i=0; db.openDataBase(); c = db.getWords("sl"); db.close(); while(c.isAfterLast()) { a[i++]=c.getString(c.getColumnIndex("WORD")); c.moveToNext(); } ListView l = (ListView)findViewById(R.id.listView1); l.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,a)); } }

这是助手类

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.database.*;
import android.database.sqlite.*;
import android.content.*;

import android.app.*;

public class DatabaseHelper extends SQLiteOpenHelper
{

private static String DB_PATH = "/data/data/com.example.attempt/databases/";

// Data Base Name.
private static final String DATABASE_NAME = "dict.db";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name1 = "WORDS";


public Context context;
static SQLiteDatabase sqliteDataBase;

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

}

@Override
public void onCreate(SQLiteDatabase arg0)
{

}
//check if the database exists
public void createDataBase() throws IOException
{
boolean databaseExist = checkDataBase();

if(databaseExist)
{
// Do Nothing.
}
else
{
this.getWritableDatabase();

copyDataBase();

// TODO Auto-generated catch block

}
}// end if else dbExist
// end createDataBase().
public boolean checkDataBase()
{
File databaseFile = new File(DB_PATH + DATABASE_NAME);
return databaseFile.exists();
}

private void copyDataBase() throws IOException
{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DATABASE_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}

/**
* This method opens the data base connection.
* First it create the path up till data base of the device.
* Then create connection with data base.
*/
public void openDataBase() throws SQLException
{
//Open the database

try {
createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String myPath = DB_PATH + DATABASE_NAME;

sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

/**
* This Method is used to close the data base connection.
*/
@Override
public synchronized void close() 
{
if(sqliteDataBase != null)
sqliteDataBase.close();
super.close();
}
//declare methods to fetch data
public Cursor getWords(String cat)
{

return sqliteDataBase.query("WORDS",new String[]{"WORD"},"CAT="+"'"+cat+"'", null, null,null,null);

}

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

}

}

这是调试后显示的logcat:

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.database.*; import android.database.sqlite.*; import android.content.*; import android.app.*; public class DatabaseHelper extends SQLiteOpenHelper { private static String DB_PATH = "/data/data/com.example.attempt/databases/"; // Data Base Name. private static final String DATABASE_NAME = "dict.db"; // Data Base Version. private static final int DATABASE_VERSION = 1; // Table Names of Data Base. static final String TABLE_Name1 = "WORDS"; public Context context; static SQLiteDatabase sqliteDataBase; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null ,DATABASE_VERSION); this.context = context; } @Override public void onCreate(SQLiteDatabase arg0) { } //check if the database exists public void createDataBase() throws IOException { boolean databaseExist = checkDataBase(); if(databaseExist) { // Do Nothing. } else { this.getWritableDatabase(); copyDataBase(); // TODO Auto-generated catch block } }// end if else dbExist // end createDataBase(). public boolean checkDataBase() { File databaseFile = new File(DB_PATH + DATABASE_NAME); return databaseFile.exists(); } private void copyDataBase() throws IOException { //Open your local db as the input stream InputStream myInput = context.getAssets().open(DATABASE_NAME); // Path to the just created empty db String outFileName = DB_PATH + DATABASE_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the input file to the output file byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } /** * This method opens the data base connection. * First it create the path up till data base of the device. * Then create connection with data base. */ public void openDataBase() throws SQLException { //Open the database try { createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String myPath = DB_PATH + DATABASE_NAME; sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } /** * This Method is used to close the data base connection. */ @Override public synchronized void close() { if(sqliteDataBase != null) sqliteDataBase.close(); super.close(); } //declare methods to fetch data public Cursor getWords(String cat) { return sqliteDataBase.query("WORDS",new String[]{"WORD"},"CAT="+"'"+cat+"'", null, null,null,null); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }

1 个答案:

答案 0 :(得分:1)

我认为您忘记初始化DatabaseHelper db类,如下所示

DatabaseHelper db=new DatabaseHelper(MainActivity.this);

并且未经初始化db您访问了db.openDataBase();方法,因此您获得了NullPointerException