A Medrano A Medrano - 29 days ago 5
Android Question

How can I call a method of my database helper class in another class in Java - Android

Class database helper



package br.com.mefti.simplefinance.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.util.Log;

import java.util.ArrayList;

import br.com.mefti.simplefinance.sqlite.ContratoSF.*;
import br.com.mefti.simplefinance.modelo.*;
import br.com.mefti.simplefinance.ui.ExtratoDespesasCursorAdapter;


/**
* Created by a_med on 13/10/2016.
* clase que administra a conexao da base de dados e a estrutura
*/

public class BaseDadosSF extends SQLiteOpenHelper {
public static final String NOME_BASE_DADOS = "BDSimpleFinance.db";
private static final int VERSAO_ATUAL = 1;
private final Context contexto;
SQLiteDatabase db;

interface Tabelas{
String USUARIO = "usuario";
String LANCAMENTO = "lancamento";
String CATEGORIA = "categoria";
}

interface Referencias{
String COD_USUARIO = String.format("REFERENCES %s(%s) ON DELETE CASCADE",Tabelas.USUARIO, Usuario.COD_USUARIO);
String COD_LANCAMENTO = String.format("REFERENCES %s(%s)",Tabelas.LANCAMENTO, Lancamento.COD_LANCAMENTO);
String COD_CATEGORIA = String.format("REFERENCES %s(%s)",Tabelas.CATEGORIA, Categoria.COD_CATEGORIA);
}

public BaseDadosSF(Context contexto){
super(contexto, NOME_BASE_DADOS, null, VERSAO_ATUAL);
this.contexto = contexto;
}

@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
db.setForeignKeyConstraintsEnabled(true);
}else {
db.execSQL("PRAGMA foreign_keys=ON");
}
}
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {


sqLiteDatabase.execSQL(String.format("CREATE TABLE %s ( %s INTEGER PRIMARY KEY AUTOINCREMENT," +
"%s TEXT NOT NULL UNIQUE,%s VARCHAR(50) NOT NULL,%s VARCHAR(20) NOT NULL,%s VARCHAR(30) NOT NULL UNIQUE, %s CHAR(1) NOT NULL )",
Tabelas.USUARIO, BaseColumns._ID,
Usuario.COD_USUARIO, Usuario.NOME, Usuario.SENHA, Usuario.EMAIL, Usuario.ESTADO
));

sqLiteDatabase.execSQL(String.format("CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT," +
"%s TEXT UNIQUE NOT NULL, %s TEXT NOT NULL %s, %s TEXT NOT NULL %s, %s CHAR(1) NOT NULL, " +
"%s VARCHAR(100) NOT NULL, %s DOUBLE, %s DATETIME, %s CHAR(1) NOT NULL, %s DATETIME, " +
"%s DOUBLE, %s VARCHAR(400))",
Tabelas.LANCAMENTO, BaseColumns._ID,
Lancamento.COD_LANCAMENTO, Lancamento.COD_USUARIO, Referencias.COD_USUARIO, Lancamento.COD_CATEGORIA, Referencias.COD_CATEGORIA, Lancamento.TP_LANCAMENTO,
Lancamento.DESCRICAO, Lancamento.VALOR, Lancamento.DATA, Lancamento.REPETIR, Lancamento.PREVISAO_DATA,
Lancamento.PREVISAO_VALOR, Lancamento.OBSERVACAO
));

sqLiteDatabase.execSQL(String.format("CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT," +
"%s TEXT UNIQUE NOT NULL, %s TEXT NOT NULL %s, %s VARCHAR(20) NOT NULL, %s CHAR(1) NOT NULL)",
Tabelas.CATEGORIA, BaseColumns._ID,
Categoria.COD_CATEGORIA, Categoria.COD_USUARIO, Referencias.COD_USUARIO, Categoria.NOME, Categoria.TP_LANCAMENTO
));
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Tabelas.USUARIO);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Tabelas.LANCAMENTO);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Tabelas.CATEGORIA);

onCreate(sqLiteDatabase);
}


//Inicio Operacoes Categoria
public Cursor ObterCategoriaPorCodCategoria(String cod_categoria){
db = this. getReadableDatabase();
String sql = String.format("SELECT * FROM %s WHERE %s=?",
Tabelas.CATEGORIA, Categoria.COD_CATEGORIA);
String[] selectionArgs = {cod_categoria};
Cursor cursor = db.rawQuery(sql, selectionArgs);
Log.d("Categoria", "Categoria");
DatabaseUtils.dumpCursor(cursor);
db.close();
return cursor;
}
}




The class that calls the method of the class Database



package br.com.mefti.simplefinance.ui;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import br.com.mefti.simplefinance.R;
import br.com.mefti.simplefinance.sqlite.BaseDadosSF;
import br.com.mefti.simplefinance.sqlite.ContratoSF;

/**
* Created by a_med on 9/11/2016.
*/

public class ExtratoDespesasCursorAdapter extends CursorAdapter{
public BaseDadosSF dados = new BaseDadosSF(this); ----> the error is here

public ExtratoDespesasCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
LayoutInflater inflater = LayoutInflater.from(cotext);
return inflater.inflate(R.layout.list_item_extrato_despesas, viewGroup, false);
}

@Override
public void bindView(View view, final Context context, Cursor cursor) {

// Referencias UI.
TextView descricaoText = (TextView) view.findViewById(R.id.descricao_despesa);
TextView valorText = (TextView) view.findViewById(R.id.valor_despesa);
TextView categoriaText = (TextView) view.findViewById(R.id.categoria_despesa);
TextView dataText = (TextView) view.findViewById(R.id.data_despesa);
//final ImageView avatarImage = (ImageView) view.findViewById(R.id.iv_avatar);

// Get valores.
String descricao = cursor.getString(cursor.getColumnIndex(ContratoSF.Lancamento.DESCRICAO));
String valor = cursor.getString(cursor.getColumnIndex(ContratoSF.Lancamento.VALOR));
String categoria = cursor.getString(cursor.getColumnIndex(ContratoSF.Lancamento.COD_CATEGORIA));
String data = cursor.getString(cursor.getColumnIndex(ContratoSF.Lancamento.DATA));

//Obtendo nome categorio pelo cod
String nCategoria = "";
Cursor cursor1 = dados.ObterCategoriaPorCodCategoria(categoria);
if (cursor1.moveToFirst()){
nCategoria = cursor.getString(3);
}

//Convertendo data
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
DateFormat targetFormat = new SimpleDateFormat("dd/MMM/yyyy");
String formattedDate = null;
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(data);
formattedDate = targetFormat.format(convertedDate);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(convertedDate);


//String avatarUri = cursor.getString(cursor.getColumnIndex(LawyerEntry.AVATAR_URI));

// Setup.
descricaoText.setText(descricao);
valorText.setText("Valor: R$ " + valor);
categoriaText.setText("Categoria: " + nCategoria);
dataText.setText("Data: " + formattedDate);
}
}





The error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.mefti.simplefinance, PID: 30549
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor br.com.mefti.simplefinance.sqlite.BaseDadosSF.ObterCategoriaPorCodCategoria(java.lang.String)' on a null object reference
at br.com.mefti.simplefinance.ui.ExtratoDespesasCursorAdapter.bindView(ExtratoDespesasCursorAdapter.java:56)

Thanks for the help

Answer

Replace this code

public class ExtratoDespesasCursorAdapter extends CursorAdapter{
  public BaseDadosSF dados = new BaseDadosSF(this); ----> the error is here

  public ExtratoDespesasCursorAdapter(Context context, Cursor c) {
    super(context, c, 0);
  }

with this

public class ExtratoDespesasCursorAdapter extends CursorAdapter{
  public BaseDadosSF dados;

  public ExtratoDespesasCursorAdapter(Context context, Cursor c) {
    super(context, c, 0);
    dados = new BaseDadosSF(context);
  }

You need to pass the context you are using, and the context when the error is thrown is not ready.

Another point is the the this refers to the ExtratoDespesasCursorAdapter and not the activity which has the context.