anindis
anindis

Reputation: 724

How to open a database from not database class?

My database class is DB.java

package com.example.pocketbooker;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class DB extends SQLiteOpenHelper implements BaseColumns{

    private static final String DATABASE_NAME = "pb_database.db";
    private static final int DATABASE_VERSION = 1;


    public DB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE Members(_id INTEGER PRIMARY KEY AUTOINCREMENT, Mem_Name VARCHAR(50));");
        db.execSQL("CREATE TABLE Incomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "Inc_Name VARCHAR(50), Inc_Sum VARCHAR(10), Inc_Mem VARCHAR (50), Inc_Change_Date DATE, " +
                "Inc_Perbeg_Date DATE, Inc_Period VARCHAR (4));");
        db.execSQL("CREATE TABLE Outcomes(_id INTEGER PRIMARY KEY AUTOINCREMENT,    " +
                "Out_Name VARCHAR(50), Out_Sum VARCHAR(10), Out_Mem VARCHAR (50), Out_Change_Date DATE, " +
                        "Out_Perbeg_Date DATE, Out_Period VARCHAR (4));");
        db.execSQL("CREATE TABLE Goals(_id INTEGER PRIMARY KEY AUTOINCREMENT,   " +
                "Goal_Name VARCHAR(50), Goal_Sum VARCHAR(10), Goal_Mem VARCHAR (50), Goal_Change_Date DATE, " +
                        "Goal_Perbeg_Date DATE, Goal_Period VARCHAR (4));");
    }

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

    }

}

My "other" class is Dialog_mem.java

package com.example.pocketbooker;

import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

@SuppressLint({ "NewApi", "ValidFragment" })
public class Dialog_mem extends DialogFragment implements OnClickListener {
   EditText memname;

   ContentValues cv = new ContentValues();
   private SQLiteDatabase database;
   private DB dbHelper;

   public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    getDialog().setTitle("Добавить Члена Семьи");

    View v = inflater.inflate(R.layout.mem_dialog, null);

    v.findViewById(R.id.mem_btnOK).setOnClickListener(this);
    v.findViewById(R.id.mem_btnCancel).setOnClickListener(this);
    memname=(EditText) v.findViewById(R.id.mem_name);

    return v;

  }


public void onClick(View v) {

      switch(v.getId())
       {  case R.id.mem_btnOK:
           database = dbHelper.getWritableDatabase();
           cv.put("Mem_Name", memname.getText().toString());
           database.insert("Members", "Mem_Name", cv);
           database.close();

             Toast.makeText(getActivity(), "Добавлено", Toast.LENGTH_SHORT).show(); 
       default:
             dismiss();}

  }

  public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);

  }

  public void onCancel(DialogInterface dialog) {
    super.onCancel(dialog);

  }

}

Eclipse shows NullPointerException. I guess it's context error, but I don't know how to point the context needed. getActivity() is the wrong one. "This" too. getApplicationContext() doesn't work at all.

Upvotes: 0

Views: 179

Answers (2)

anindis
anindis

Reputation: 724

Well, I used the akashsr's answer (thank you, man, for the idea). If anyone is interested how I've made it (at last) here's the code.

DB.java

package com.example.pocketbooker;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class DB extends SQLiteOpenHelper implements BaseColumns{

    private static final String DATABASE_NAME = "pb_database.db";
    private static final int DATABASE_VERSION = 1;
    private static DB sInstance;
    ContentValues cv;
     public DB(Context context) {

         super(context, DATABASE_NAME, null, DATABASE_VERSION);}



    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE Members(_id INTEGER PRIMARY KEY AUTOINCREMENT, Mem_Name VARCHAR(50));");
        db.execSQL("CREATE TABLE Incomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "Inc_Name VARCHAR(50), Inc_Sum VARCHAR(10), Inc_Mem VARCHAR (50), Inc_Change_Date DATE, " +
                "Inc_Perbeg_Date DATE, Inc_Period VARCHAR (4));");
        db.execSQL("CREATE TABLE Outcomes(_id INTEGER PRIMARY KEY AUTOINCREMENT,    " +
                "Out_Name VARCHAR(50), Out_Sum VARCHAR(10), Out_Mem VARCHAR (50), Out_Change_Date DATE, " +
                        "Out_Perbeg_Date DATE, Out_Period VARCHAR (4));");
        db.execSQL("CREATE TABLE Goals(_id INTEGER PRIMARY KEY AUTOINCREMENT,   " +
                "Goal_Name VARCHAR(50), Goal_Sum VARCHAR(10), Goal_Mem VARCHAR (50), Goal_Change_Date DATE, " +
                        "Goal_Perbeg_Date DATE, Goal_Period VARCHAR (4));");
    }

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

    }

}

Created DataSource class with insert method. PBDataSource.java

package com.example.pocketbooker;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class PBDataSource {

    DB dbHelper;
    SQLiteDatabase db;
     public PBDataSource(Context context) {
            dbHelper = new DB(context);
          }
    public void open() throws SQLException {
        if (dbHelper != null) {
            db = dbHelper.getWritableDatabase();
        }
    }

    public void close() {
        dbHelper.close();
    }

    public void insertrecord (String a, String b, String c)
    {ContentValues cv= new ContentValues();
        cv.put(b,c);
        db.insert(a, null, cv);
    }
}

And used this method in my DialogFragment class Dialog_mem.java

package com.example.pocketbooker;

import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

@SuppressLint({ "NewApi", "ValidFragment" })
public class Dialog_mem extends DialogFragment implements OnClickListener {
   EditText memname;
   private PBDataSource datasource;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    getDialog().setTitle("Добавить Члена Семьи");

    View v = inflater.inflate(R.layout.mem_dialog, null);

    v.findViewById(R.id.mem_btnOK).setOnClickListener(this);
    v.findViewById(R.id.mem_btnCancel).setOnClickListener(this);
    memname=(EditText) v.findViewById(R.id.mem_name);

    datasource = new PBDataSource(getActivity());
    return v;

  }


public void onClick(View v) {

      switch(v.getId())
       {  case R.id.mem_btnOK:

           datasource.open();
           datasource.insertrecord("Members","Mem_Name", memname.getText().toString());
           datasource.close();
             Toast.makeText(getActivity(), "Добавлено", Toast.LENGTH_SHORT).show(); 
       default:
             dismiss();}

  }

  public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);

  }

  public void onCancel(DialogInterface dialog) {
    super.onCancel(dialog);

  }}

Of course, I'm a noob. I try to study myself as I can. And I hope it will help someone like me.

Upvotes: 1

someengr
someengr

Reputation: 690

You need to initialize the dbHelper instance. What you can do is
1. Create a singleton class for all Database operations.
2. Create a Datasource class. Through which you will access the Database.
3. In Data Source class add open() method

/**
 * Open the Database
 * @throws SQLException
 */
public void open() throws SQLException {
    if (dbHelper != null) {
        db = dbHelper.getWritableDatabase();
    }
}
/**
 * Close
 */
public void close() {
    dbHelper.close();
}


4. Write the method which you need to acces Database in DataSource class and call the database operations on this db instance.

Upvotes: 3

Related Questions