Hi to all! I made a class named “Database” I called openOrCreateDatabase in in its constructor but it was giving error.
Then I searched on internet and got a solution that in case of non activity class I should also pass context. Then I passed context but then I am facing an error in run time in LogCat: ”java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory)' on a null object reference."

Above in the double quotes is the error.please guide me
Actually I want that I just call the constructor of this class in another class named “InsertRecord” and the database should be created. Now i am pasting code of both my classes

package com.hatflabs.addressbook;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.support.design.widget.TabLayout;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.xml.parsers.FactoryConfigurationError;

/**
 * Created by applezone on 1/1/01.
 */
public class Database  {

    SQLiteDatabase db;
    Connection con;
    String dbName = "MyDb";

    // constructor
    public Database(Context ctxt,  SQLiteDatabase db) {
        db = ctxt.openOrCreateDatabase(dbName, ctxt.MODE_PRIVATE,null);

    }

}

Now I am code of InsertRecord class

package com.hatflabs.addressbook;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hatflabs.addressbook.Database.*;

import java.sql.PreparedStatement;

public class InsertRecord extends AppCompatActivity {

    Context ctxt;
    SQLiteDatabase db;
    Button b1;

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

        b1 = (Button)findViewById(R.id.button1);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

           //creating object of Database class

           Database dtbs = new Database(ctxt,db );
                Log.w("Saboor","database created");

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_insert_record, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Dani AI

Generated

You are getting the NPE because the Context you pass in is null. In InsertRecord, the field ctxt is never initialized, so new Database(ctxt, db) dereferences a null context. There is also variable shadowing in your Database constructor: the parameter named db hides the class field, so you never actually assign to this.db. Finally, the java.sql.* imports are not used for Android SQLite and can be removed.

Quick, minimal fix:

  • Pass a non-null context from your Activity (e.g., InsertRecord.this or getApplicationContext()).
  • Do not take SQLiteDatabase as a constructor parameter; create and store it inside your class.
  • Assign to the field, not a shadowed parameter.

Example:

public final class Database {
    private static final String DB_NAME = "MyDb.db";
    private final SQLiteDatabase db;

    public Database(Context context) {
        this.db = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
        // TODO: create tables if needed with db.execSQL(...)
    }

    public SQLiteDatabase getDb() { return db; }
}

And from your Activity click handler:

Database dtbs = new Database(InsertRecord.this); // or getApplicationContext()

Better long-term: follow Android’s recommended pattern with SQLiteOpenHelper. Put your schema in onCreate, upgrades in onUpgrade, and call getWritableDatabase() when you need a handle. This avoids lifecycle leaks, handles versioning, and centralizes DB setup.

Debugging tip echoing : set a breakpoint where you construct Database and inspect the Context, or log/Toast context == null. Also log the DB path with db.getPath() after opening so you know it actually opened. Remove java.sql.Connection/PreparedStatement; use SQLiteDatabase and SQLiteStatement on Android.

This is not the answer but to share how I debug such a thing. I hook up my device and run it over the Android studio USB debugger and break at that line of code to examine variables to see what's up. If I can't do that I've been sending up "toasts" with messages so I can see what's going on inside.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.