2016-11-11 11 views
1

類數據庫輔助我怎麼能說我的數據庫輔助類的方法,在Java中另一個類 - Android電子

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; 
 
    } 
 
}
調用類數據庫的方法的類

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

該錯誤:

E/AndroidRuntime:致命異常:主 工藝:br.com.mefti.simplefinance,PID:30549 顯示java.lang.NullPointerException:嘗試調用虛擬方法「android.database.Cursor br.com.mefti.simplefinance .sqlite.BaseDadosSF.ObterCategoriaPorCodCategoria(java.lang.String中)」上的空對象引用 在br.com.mefti.simplefinance.ui.ExtratoDespesasCursorAdapter.bindView(ExtratoDespesasCursorAdapter.java:56)

感謝您的幫助

回答

0

替換此代碼

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

與此

public class ExtratoDespesasCursorAdapter extends CursorAdapter{ 
    public BaseDadosSF dados; 

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

您需要將您正在使用的情況下,當被拋出的錯誤context沒有準備好。

另一點是this是指ExtratoDespesasCursorAdapter而不是activity其中有context

0

試試這個

舊代碼

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

新代碼

public class ExtratoDespesasCursorAdapter extends CursorAdapter{ 
public BaseDadosSF dados ; 

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); 
     dados = new BaseDadosSF(context); 
    return inflater.inflate(R.layout.list_item_extrato_despesas, viewGroup, false); 
} 
相關問題