gpt4 book ai didi

java - 如何在 Java - Android 的另一个类中调用我的数据库助手类的方法

转载 作者:行者123 更新时间:2023-11-30 00:53:34 26 4
gpt4 key购买 nike

类数据库助手

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;
}
}
调用类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);
}
}

错误:

E/AndroidRuntime: 致命异常: main 进程: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)

感谢帮助

最佳答案

替换这段代码

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,抛出错误时的context还没有准备好。

另一点是 this 指的是 ExtratoDespesasCursorAdapter 而不是具有 contextactivity

关于java - 如何在 Java - Android 的另一个类中调用我的数据库助手类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40549000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com