在单独的活动/类中创建数据库会产生错误

时间:2013-02-11 15:21:59

标签: java android sqlite nullpointerexception

请查看以下代码

Form.java

Form.java是Main活动,表示第一页的Java文件。许多与创建“列表”和菜单相关的代码都将被删除。

  package com.example.esoftcallmanager;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Form extends Activity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form);

        DatabaseConnector databaseConnector = new DatabaseHandler(); 
        databaseConnector.createConnection();

        ListView lv = (ListView)findViewById(android.R.id.list);
        String arr[] = getResources().getStringArray(R.array.branch_list);

        //lv.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_1,R.id.listText,arr));

        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
            // TODO Auto-generated method stub


            }
            });
    }
}

DataBaseConnector.java

这是代码的接口,用于执行数据库操作

package com.example.esoftcallmanager;

public interface DatabaseConnector 
{
    public void createConnection();
    public void closeConnection();
    public String getPhoneNumber();
}

DataBaseHandler.java

这是执行数据库操作的

package com.example.esoftcallmanager;

import android.app.Activity;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

public class DatabaseHandler extends Activity implements DatabaseConnector
{
    private SQLiteDatabase database;
    private String dbPath = "data//data//com.example.esoftcallmanager.sqllite//esoftDatabase";

    @Override
    public void createConnection() 
    {

        try
        {
            database = this.openOrCreateDatabase("esoftDatabase", MODE_PRIVATE, null);

        database.execSQL("create table BranchNetwork(" +
                "brID integer primary key autoincrement,"
                +"city text,"
                +"steetAddress text"
                +"phoneNumber1 text"
                +"phoneNumber2 text"
                +"email text"
                +");");
        }
        catch(SQLException sql)
        {
            Toast.makeText(this, sql.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void closeConnection() {
        // TODO Auto-generated method stub

    }

    @Override
    public String getPhoneNumber() {
        // TODO Auto-generated method stub
        return null;
    }

}

但是,我无法运行代码,因为我收到以下错误。

02-11 20:35:59.350: D/dalvikvm(434): GC_EXTERNAL_ALLOC freed 52K, 53% free 2552K/5379K, external 1949K/2137K, paused 80ms
02-11 20:40:34.021: D/dalvikvm(1131): GC_EXTERNAL_ALLOC freed 42K, 53% free 2552K/5379K, external 1949K/2137K, paused 122ms
02-11 20:40:34.361: D/AndroidRuntime(1131): Shutting down VM
02-11 20:40:34.361: W/dalvikvm(1131): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:40:34.401: E/AndroidRuntime(1131): FATAL EXCEPTION: main
02-11 20:40:34.401: E/AndroidRuntime(1131): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.esoftcallmanager/com.example.esoftcallmanager.Form}: java.lang.NullPointerException
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.os.Looper.loop(Looper.java:123)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at dalvik.system.NativeStart.main(Native Method)
02-11 20:40:34.401: E/AndroidRuntime(1131): Caused by: java.lang.NullPointerException
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at com.example.esoftcallmanager.DatabaseHandler.createConnection(DatabaseHandler.java:19)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at com.example.esoftcallmanager.Form.onCreate(Form.java:30)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-11 20:40:34.401: E/AndroidRuntime(1131):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-11 20:40:34.401: E/AndroidRuntime(1131):     ... 11 more
02-11 20:40:37.381: I/Process(1131): Sending signal. PID: 1131 SIG: 9

每当我从Form.java中删除数据库连接部分时,这都可以正常工作!所以错误必须在以下代码中

DatabaseConnector databaseConnector = new DatabaseHandler();
        databaseConnector.createConnection();

我不想在Form.java中添加所有数据库操作。我需要像我一样分开工作。但是,我该怎么做?请帮忙!

2 个答案:

答案 0 :(得分:2)

我看到的一件事是:

    database.execSQL("create table BranchNetwork(" +
            "brID integer primary key autoincrement,"
            +"city text,"
            +"steetAddress text"
            +"phoneNumber1 text"
            +"phoneNumber2 text"
            +"email text"
            +");");

你必须写:

    database.execSQL("create table BranchNetwork(" +
            "brID integer primary key autoincrement,"
            +"city text,"
            +"steetAddress text," //forgot comma
            +"phoneNumber1 text," //forgot comma
            +"phoneNumber2 text," // forgot commas
            +"email text"
            +");");

我不知道这是不是错,但试试吧......

答案 1 :(得分:2)

如果DatabaseHandler不是Activity类,则无需将Activity扩展到它。您需要创建DatabaseHandler的参数化构造函数,以将Activity上下文传递给它以创建数据库。将您的DatabaseHandler类更改为:

public class DatabaseHandler implements DatabaseConnector
{
    private SQLiteDatabase database;
     ....
    Context context;

   public DatabaseHandler(Context context){

       this.context=context;
   }

    @Override
    public void createConnection() 
    {

        try
        {
            database = context.openOrCreateDatabase("esoftDatabase", 
                           MODE_PRIVATE, null);
            // your code here....
        }
        catch(SQLException sql)
        {
            Toast.makeText(context, sql.getMessage(), 
                    Toast.LENGTH_LONG).show();
        }

    }

并从表单活动传递活动上下文:

DatabaseConnector databaseConnector = 
                    new DatabaseHandler(Form.this);
databaseConnector.createConnection();