Creating database in seperate activity/class is giving errors

Please have a look at the following code

Form.java

Form.java is the Main activity, which means the Java file for the first page. Lot of code related to creating “List” and menu are removed.

  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

This is the interface for the code, which perform database actions

package com.example.esoftcallmanager;

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

DataBaseHandler.java

This is the one which perform the database operations

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;
    }

}

However, I am unable to run the code, because I am getting the following error.

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

Whenever I remove the database connection part from the Form.java, this works fine! So the error must be in the following code

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

I do not want to add all the database operations in the Form.java. I need to split the work as I have done. But, how can I do that? Please help!

Answer

if DatabaseHandler is non Activity class then no need to extends Activity to it. you will need to create a parameterized constructor of DatabaseHandler to pass Activity context to it for creating database . change your DatabaseHandler class as:

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();
        }

    }

and pass Activity Context as from Form Activity :

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

Leave a Reply

Your email address will not be published. Required fields are marked *