I'm trying to create a app of baking sell expenses, where I can input the values of the ingredients used on the baking process individually, and then input the values of each product using the values of the ingredients in each recipe, so I can see how much I can sell then to have a good profit.
I have a database and methods working on my first table (Save, Delete, Update, Search...), but I can't make my second table (TABLE_RECEITA) uses the data that already exist from my first table (TABLE_PRODUTO), to complement my recipes.
I want to feed my second table on it's columns with the data from my first table columns, only changing the data of quantity, and value by dividing according to the amount used.
I've tried to used foreign key and spinner but was not successful, but there's a high possibility that I did something wrong.
My Database:
package com.myapplication.umdocededaisy;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MyDatabase extends SQLiteOpenHelper {
List<MateriaPrima> listaProduto = new ArrayList<>();
List<Receita> listaReceita = new ArrayList<>();
private final Context context;
private static final String DATABASE_NAME = "BancoDoceDaisy.db";
private static final int DATABASE_VERSION = 9;
//Estruturas das Tabelas do banco de dados:
//Tabela dos produtos - materia prima **(FIRST TABLE)**:
private static final String TABLE_PRODUTO = "materia_prima";
private static final String COLUMN_CODIGO = "codigo";
private static final String COLUMN_PRODUTO = "produto";
private static final String COLUMN_VALOR = "valor";
private static final String COLUMN_QTD = "quantidade";
private static final String COLUMN_TIPO = "tipo";
//------------------------------------------------------
//Tabela de receitas/massas - **(SECOND TABLE)**:
private static final String TABLE_RECEITA = "receitas";
private static final String COLUMN_TITULO = "titulo";
private static final String COLUMN_ITEM1 = "item1";
private static final String COLUMN_ITEM2 = "item2";
private static final String COLUMN_ITEM3 = "item3";
private static final String COLUMN_ITEM4 = "item4";
private static final String COLUMN_ITEM5 = "item5";
private static final String COLUMN_ITEM6 = "item6";
private static final String COLUMN_ITEM7 = "item7";
private static final String COLUMN_ITEM8 = "item8";
private static final String COLUMN_ITEM9 = "item9";
private static final String COLUMN_ITEM10 = "item10";
private static final String COLUMN_ITEM11 = "item11";
private static final String COLUMN_ITEM12 = "item12";
private static final String COLUMN_ITEM13 = "item13";
private static final String COLUMN_ITEM14 = "item14";
private static final String COLUMN_VALOR1 = "valor1";
private static final String COLUMN_VALOR2 = "valor2";
private static final String COLUMN_VALOR3 = "valor3";
private static final String COLUMN_VALOR4 = "valor4";
private static final String COLUMN_VALOR5 = "valor5";
private static final String COLUMN_VALOR6 = "valor6";
private static final String COLUMN_VALOR7 = "valor7";
private static final String COLUMN_VALOR8 = "valor8";
private static final String COLUMN_VALOR9 = "valor9";
private static final String COLUMN_VALOR10 = "valor10";
private static final String COLUMN_VALOR11 = "valor11";
private static final String COLUMN_VALOR12 = "valor12";
private static final String COLUMN_VALOR13 = "valor13";
private static final String COLUMN_VALOR14 = "valor14";
private static final String COLUMN_QTD1 = "qtd1";
private static final String COLUMN_QTD2 = "qtd2";
private static final String COLUMN_QTD3 = "qtd3";
private static final String COLUMN_QTD4 = "qtd4";
private static final String COLUMN_QTD5 = "qtd5";
private static final String COLUMN_QTD6 = "qtd6";
private static final String COLUMN_QTD7 = "qtd7";
private static final String COLUMN_QTD8 = "qtd8";
private static final String COLUMN_QTD9 = "qtd9";
private static final String COLUMN_QTD10 = "qtd10";
private static final String COLUMN_QTD11 = "qtd11";
private static final String COLUMN_QTD12 = "qtd12";
private static final String COLUMN_QTD13 = "qtd13";
private static final String COLUMN_QTD14 = "qtd14";
MyDatabase(Context context) {
super(context, DATABASE_NAME,null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ TABLE_PRODUTO +
" (" + COLUMN_CODIGO + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUTO + " TEXT, " +
COLUMN_VALOR + " FLOAT, " +
COLUMN_QTD + " FLOAT, " +
COLUMN_TIPO + " TEXT); ";
db.execSQL(query);
String query2 = "CREATE TABLE "+ TABLE_RECEITA +
" (" + COLUMN_TITULO + " TEXT PRIMARY KEY, " + COLUMN_ITEM1 + "TEXT," + COLUMN_ITEM2 + " TEXT, " +
COLUMN_ITEM3 + " TEXT, " + COLUMN_ITEM4 + " TEXT, " + COLUMN_ITEM5 + " TEXT, " + COLUMN_ITEM6 + " TEXT, " +
COLUMN_ITEM7 + " TEXT, " + COLUMN_ITEM8 + " TEXT, " + COLUMN_ITEM9 + " TEXT, " + COLUMN_ITEM10 + " TEXT, " +
COLUMN_ITEM11 + " TEXT, " + COLUMN_ITEM12 + " TEXT, " + COLUMN_ITEM13 + " TEXT, " + COLUMN_ITEM14 + " TEXT, " +
COLUMN_VALOR1 + "FLOAT, " + COLUMN_VALOR2 + "FLOAT, " +COLUMN_VALOR3 + "FLOAT, " + COLUMN_VALOR4 + "FLOAT, " +
COLUMN_VALOR5 + "FLOAT, " + COLUMN_VALOR6 + "FLOAT, " + COLUMN_VALOR7 + "FLOAT, " + COLUMN_VALOR8 + "FLOAT, " +
COLUMN_VALOR9 + "FLOAT, " + COLUMN_VALOR10 + "FLOAT, " + COLUMN_VALOR11 + "FLOAT, " + COLUMN_VALOR12 + "FLOAT, " +
COLUMN_VALOR13 + "FLOAT, " + COLUMN_VALOR14 + "FLOAT, " + COLUMN_QTD1 + "FLOAT, " + COLUMN_QTD1 + "FLOAT, " +
COLUMN_QTD1 + "FLOAT, " + COLUMN_QTD2 + "FLOAT, " + COLUMN_QTD3 + "FLOAT, " + COLUMN_QTD4 + "FLOAT, " +
COLUMN_QTD5 + "FLOAT, " + COLUMN_QTD6 + "FLOAT, " + COLUMN_QTD7 + "FLOAT, " + COLUMN_QTD8 + "FLOAT, " +
COLUMN_QTD9 + "FLOAT, " + COLUMN_QTD10 + "FLOAT, " + COLUMN_QTD11 + "FLOAT, " + COLUMN_QTD12 + "FLOAT, " +
COLUMN_QTD13 + "FLOAT, " + COLUMN_QTD14 + "FLOAT); ";
db.execSQL(query2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUTO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECEITA);
onCreate(db);
}
void addProduto(MateriaPrima materiaPrima) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PRODUTO, materiaPrima.getProduto());
cv.put(COLUMN_VALOR, materiaPrima.getValor());
cv.put(COLUMN_QTD, materiaPrima.getQuantidade());
cv.put(COLUMN_TIPO, materiaPrima.getTipo());
long result = db.insert(TABLE_PRODUTO, null, cv);
if (result == -1) {
Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, R.string.strAddSucess, Toast.LENGTH_SHORT).show();
}
db.close();
}
void addReceita(Receita receita) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITULO, receita.getTitulo());
cv.put(COLUMN_ITEM1, receita.getItem1());
cv.put(COLUMN_ITEM2, receita.getItem2());
cv.put(COLUMN_ITEM3, receita.getItem3());
cv.put(COLUMN_ITEM4, receita.getItem4());
cv.put(COLUMN_ITEM5, receita.getItem5());
cv.put(COLUMN_ITEM6, receita.getItem6());
cv.put(COLUMN_ITEM7, receita.getItem7());
cv.put(COLUMN_ITEM8, receita.getItem8());
cv.put(COLUMN_ITEM9, receita.getItem9());
cv.put(COLUMN_ITEM10, receita.getItem10());
cv.put(COLUMN_ITEM11, receita.getItem11());
cv.put(COLUMN_ITEM12, receita.getItem12());
cv.put(COLUMN_ITEM13, receita.getItem13());
cv.put(COLUMN_ITEM14, receita.getItem14());
cv.put(COLUMN_VALOR1, receita.getValor1());
cv.put(COLUMN_VALOR2, receita.getValor2());
cv.put(COLUMN_VALOR3, receita.getValor3());
cv.put(COLUMN_VALOR4, receita.getValor4());
cv.put(COLUMN_VALOR5, receita.getValor5());
cv.put(COLUMN_VALOR6, receita.getValor6());
cv.put(COLUMN_VALOR7, receita.getValor7());
cv.put(COLUMN_VALOR8, receita.getValor8());
cv.put(COLUMN_VALOR9, receita.getValor9());
cv.put(COLUMN_VALOR10, receita.getValor10());
cv.put(COLUMN_VALOR11, receita.getValor11());
cv.put(COLUMN_VALOR12, receita.getValor12());
cv.put(COLUMN_VALOR13, receita.getValor13());
cv.put(COLUMN_VALOR14, receita.getValor14());
cv.put(COLUMN_QTD1, receita.getQtd1());
cv.put(COLUMN_QTD2, receita.getQtd2());
cv.put(COLUMN_QTD3, receita.getQtd3());
cv.put(COLUMN_QTD4, receita.getQtd4());
cv.put(COLUMN_QTD5, receita.getQtd5());
cv.put(COLUMN_QTD6, receita.getQtd6());
cv.put(COLUMN_QTD7, receita.getQtd7());
cv.put(COLUMN_QTD8, receita.getQtd8());
cv.put(COLUMN_QTD9, receita.getQtd9());
cv.put(COLUMN_QTD10, receita.getQtd10());
cv.put(COLUMN_QTD11, receita.getQtd11());
cv.put(COLUMN_QTD12, receita.getQtd12());
cv.put(COLUMN_QTD13, receita.getQtd13());
cv.put(COLUMN_QTD14, receita.getQtd14());
long result = db. insert(TABLE_RECEITA, null, cv);
if (result == -1) {
Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, R.string.strAddSucess, Toast.LENGTH_SHORT).show();
}
db.close();
}
public List<MateriaPrima> buscaProduto() {
String[] columns = {COLUMN_CODIGO, COLUMN_PRODUTO, COLUMN_VALOR, COLUMN_QTD, COLUMN_TIPO};
SQLiteDatabase db = getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_PRODUTO, columns, null, null, null,null, null);
while (cursor.moveToNext()) {
int index1 = cursor.getColumnIndex(COLUMN_CODIGO);
int codigo = cursor.getInt(index1);
int index2 = cursor.getColumnIndex(COLUMN_PRODUTO);
String produto = cursor.getString(index2);
int index3 = cursor.getColumnIndex(COLUMN_VALOR);
float valor = cursor.getFloat(index3);
int index4 = cursor.getColumnIndex(COLUMN_QTD);
float quantidade = cursor.getFloat(index4);
int index5 = cursor.getColumnIndex(COLUMN_TIPO);
String tipo = cursor.getString(index5);
MateriaPrima produtos = new MateriaPrima(codigo, produto, valor, quantidade, tipo);
listaProduto.add(produtos);
}
return listaProduto;
}
public List<Receita> buscaReceita() {
String[] columns = {COLUMN_TITULO, COLUMN_ITEM1, COLUMN_VALOR, COLUMN_QTD, COLUMN_TIPO};
SQLiteDatabase db = getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_RECEITA, columns, null, null, null,null, null);
while (cursor.moveToNext()) {
int index1 = cursor.getColumnIndex(COLUMN_TITULO);
String titulo = cursor.getString(index1);
int index2 = cursor.getColumnIndex(COLUMN_ITEM1);
String item1 = cursor.getString(index2);
/*int index3 = cursor.getColumnIndex(COLUMN_VALOR);
float valor = cursor.getFloat(index3);
int index4 = cursor.getColumnIndex(COLUMN_QTD);
float quantidade = cursor.getFloat(index4);
int index5 = cursor.getColumnIndex(COLUMN_TIPO);
String tipo = cursor.getString(index5);*/
Receita receitas = new Receita(titulo, item1); //, valor, quantidade, tipo);
listaReceita.add(receitas);
}
return listaReceita;
}
void updateData(String row_id, String produto, String valor, String quantidade, String tipo){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PRODUTO, produto);
cv.put(COLUMN_VALOR, valor);
cv.put(COLUMN_QTD, quantidade);
cv.put(COLUMN_TIPO, tipo);
long result = db.update(TABLE_PRODUTO, cv, "codigo=?", new String[]{row_id});
if(result == -1){
Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
}
db.close();
}
void deleteOneRow(String row_id){
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_PRODUTO, "codigo=?", new String[]{row_id});
if(result== -1){
Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
}
}
void deleteAllData() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUTO);
db.close();
}
}
My Activity to Save My Recipe (Second Table) using the ingredients saved on the first table:
package com.myapplication.umdocededaisy;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddItem extends AppCompatActivity {
EditText et_produto, et_valor, et_qtd, et_sqtd, et_tipo, et_stipo;
Button btnIncluir;
String produto, valor, quantidade, tipo;
List<MateriaPrima> listaProdutos;
Spinner spinner;
MyDatabase myDB = new MyDatabase(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
//Declarações objetos:
et_produto = findViewById(R.id.et_produto);
et_valor = findViewById(R.id.et_valor);
et_qtd = findViewById(R.id.et_qtd);
et_sqtd = findViewById(R.id.et_sqtd);
et_tipo = findViewById(R.id.et_tipo);
et_stipo = findViewById(R.id.et_stipo);
btnIncluir = findViewById(R.id.btnIncluir);
spinner = findViewById(R.id.spinner);
//Chamada de Métodos:
getAndSetIntentData();
loadSpinnerData();
loadSpinner();
//Botões:
//Save Button to Second Table:
btnIncluir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Receita receita = new Receita();
myDB.addReceita(receita);
}
});
}
void getAndSetIntentData() {
if (getIntent().hasExtra("produto") && getIntent().hasExtra("valor") &&
getIntent().hasExtra("quantidade") && getIntent().hasExtra("tipo")){
//Getting data:
produto = getIntent().getStringExtra("produto");
valor = getIntent().getStringExtra("valor");
quantidade = getIntent().getStringExtra("quantidade");
tipo = getIntent().getStringExtra("tipo");
//Setting data:
et_produto.setText(produto);
et_valor.setText(valor);
et_qtd.setText(quantidade);
et_tipo.setText(tipo);
et_stipo.setText(tipo);
}else{
Toast.makeText(this, R.string.strData0, Toast.LENGTH_SHORT).show();
}
}
I don't know how to write the code to save those changes, I don't know if I have to change something on my database insert method or just here, because my insert method is writing just like the one on my first table.
My AddProduto (where I save my ingredients one first table):
package com.myapplication.umdocededaisy;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class AddProduto extends AppCompatActivity {
EditText editProduto, editValor, editQuantidade, editTipo;
FloatingActionButton btnVoltar;
Button btnSalvar;
InputMethodManager inputManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_produto);
//Declarações objetos:
editProduto = findViewById(R.id.editProduto);
editValor = findViewById(R.id.editValor);
editQuantidade = findViewById(R.id.editQuantidade);
editTipo = findViewById(R.id.editTipo);
btnVoltar = findViewById(R.id.btnVoltar);
btnSalvar = findViewById(R.id.btnSalvar);
inputManager = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
btnVoltar.setOnClickListener(v -> {
Intent voltar = new Intent(AddProduto.this, MainActivity.class);
startActivity(voltar);
});
btnSalvar.setOnClickListener(v -> {
if(editProduto.getText().toString().isEmpty() || editValor.getText().toString().isEmpty() ||
editQuantidade.getText().toString().isEmpty() || editTipo.getText().toString().isEmpty())
{
Toast.makeText(AddProduto.this, R.string.strEmpty, Toast.LENGTH_SHORT).show();
}else{
MyDatabase myDB = new MyDatabase(AddProduto.this);
MateriaPrima materiaPrima = new MateriaPrima();
materiaPrima.setProduto(editProduto.getText().toString());
materiaPrima.setValor(Float.parseFloat(editValor.getText().toString()));
materiaPrima.setQuantidade(Float.parseFloat(editQuantidade.getText().toString()));
materiaPrima.setTipo(editTipo.getText().toString());
myDB.addProduto(materiaPrima);
}
reset();
editProduto.requestFocus(); //focar no campo especificado
inputManager.hideSoftInputFromWindow(btnSalvar.getWindowToken(), 0);
});
}
void reset(){
editProduto.setText(" ");
editValor.setText(" ");
editQuantidade.setText(" ");
editTipo.setText(" ");
}
}
Can anyone help me?
I've looked everywhere but didn't found anything that can be applied to my case.
Thanks in advance.
I don't know how to write the code to save those changes,
The design of your database appears to be introducing complexities that would make inserting and retrieving data into/from the second table quite complex.
By the look of it your second table consists of many columns where a relationship could replace the repeated columns (materia/ingredients) and adding such a relationship could perhaps simplify matters.
To look at this you have materia (ingredients) such as Milk Flour Sugar etc. An ingredient can be used in many recipes and a recipe can use many ingredients. As such you likely want a many-many relationship between recipes and ingredients.
So I'd suggest that you consider a mapping table that allows you have to a many to many relationship, so 3 tables instead of 2. Perhaps consider the following:-
CREATE TABLE IF NOT EXISTS materia_prima (codigo INTEGER PRIMARY KEY /* AUTOINCREMENT */,produto TEXT, VALOR FLOAT, QTD FLOAT, TIPO TEXT);
CREATE TABLE IF NOT EXISTS receitas (TITULO TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS receitas_materia (
titulo_map TEXT REFERENCES receitas(titulo) ON DELETE CASCADE ON UPDATE CASCADE,
materia_map INTEGER REFERENCES materia_prima(codigo) ON DELETE CASCADE ON UPDATE CASCADE, receitas_materia_qtd FLOAT,
PRIMARY KEY(titulo_map,materia_map));
The materia_prima table is as it was (except there is no need for the inefficient AUTOINCREMENT so that's been commented out)
The receitas table has been greatly simplified (just 1 column)
The receitas_materia table is the mapping table that is used to signify that an ingredient is used by a recipe.
Foreign Key constraints (the REFERENCES clause) have been added to enforce referential integrity.
The ON DELETE/UPDATE says to propagate changes from the parent to the child.
A third column has been added to denote the quantity used by the recipe.
So taking this further the following data is added :-
First some ingredients including their cost per measure:-
INSERT INTO materia_prima VALUES
(null,'Plain Flour',0.54,1,'Gram'),
(null,'SR Flour',0.55,1,'Gram'),
(null,'Eggs',1.34,1,'Each'),
(null,'Milk',0.2,1,'MilliLitre'),
(null,'Sugar',0.65,1,'Gram');
Second Some recipes :-
INSERT INTO receitas VALUES ('Bread'),('Cake'),('Scone');
Now the ingredients used by recipes (just Bread and Cakes) :-
INSERT INTO receitas_materia VALUES
('Bread',1 /*map to Plain Flour*/,200 /* uses 200 grams */),
('Bread',3,2),
('Bread',4,50),
('Bread',5,10),
('Cake',2,400),
('Cake',3,3),
('Cake',4,100),
('Cake',5,300)
;
So instead of many columns and the complexity of trying to determine what goes into what column. You simply add as many ingredients per recipe as is required (and let the queries do the work).
A Query such as :-
SELECT *, valor * receitas_materia_qtd AS cost
FROM receitas JOIN receitas_materia ON receitas_materia.titulo_map = receitas.titulo JOIN materia_prima ON materia_prima.codigo = receitas_materia.materia_map;
Could be used to list the product and it's ingredients including the cost per ingredient e.g. using the above the results is:-
e.g. Bread uses 200g of sugar which costs 0.54 per gram so therefore the cost of sugar for bread is 108.
You would appear to want the total cost per item so a query something like :-
SELECT titulo, group_concat(produto||' ('||receitas_materia_qtd||' '||tipo||')') AS materias, sum(valor * receitas_materia_qtd) AS total_cost
FROM receitas JOIN receitas_materia ON receitas_materia.titulo_map = receitas.titulo JOIN materia_prima ON materia_prima.codigo = receitas_materia.materia_map
GROUP BY titulo;
Could be used, this results in :-
Android based Example
The following is a basic example that allows ingredients to be added to a recipe via a spinner. The current ingredients are also listed allowing an ingredient to also be removed by long clicking the ingredient.
The example utilises Cursor Adapters which are simpler to work with.
First is MyDatabase which uses the suggested design and includes methods the various methods:-
public class MyDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "BancoDoceDaisy.db";
private static final int DATABASE_VERSION = 9;
SQLiteDatabase db;
public static final String TABLE_PRODUTO = "materia_prima";
public static final String COLUMN_PRODUTO_CODIGO = BaseColumns._ID; /*CHANGED Use the standard Android ID column name */
public static final String COLUMN_PRODUTO = "produto";
public static final String COLUMN_VALOR = "valor";
public static final String COLUMN_QTD = "quantidade";
public static final String COLUMN_TIPO = "tipo";
public static final String TABLE_RECEITA = "receitas";
public static final String COLUMN_RECEITA_CODIGO = BaseColumns._ID;
public static final String COLUMN_TITULO = "titulo";
public static final String TABLE_RECEITA_MATERIA_MAP = TABLE_RECEITA + "_" + TABLE_PRODUTO + "_map";
public static final String COLUMN_RECEITA_MAP = TABLE_RECEITA + "_map";
public static final String COLUMN_PRODUTO_MAP = TABLE_PRODUTO + "_map";
public static final String COLUMN_RECEITA_QTD = TABLE_RECEITA + "_" + COLUMN_QTD;
public static final String DERIVED_COLUMN_COST = "cost";
private static final String cost_calculate = TABLE_PRODUTO + "." + COLUMN_VALOR + " * " + TABLE_RECEITA_MATERIA_MAP + "." + COLUMN_RECEITA_QTD + " AS " + DERIVED_COLUMN_COST;
public static final String DERIVED_COLUMN_TOTAL_COST = "total_cost";
private static final String total_cost_calculate = "SUM(" + TABLE_PRODUTO + "." + COLUMN_VALOR + " * " + TABLE_RECEITA_MATERIA_MAP + "." + COLUMN_QTD + ") AS " + DERIVED_COLUMN_TOTAL_COST;
private final String join_receitamateria_map =
" JOIN " + TABLE_RECEITA_MATERIA_MAP +
" ON " + TABLE_RECEITA + "." + COLUMN_RECEITA_CODIGO +
" = " + TABLE_RECEITA_MATERIA_MAP + "." + COLUMN_RECEITA_MAP;
private final String join_produto =
" JOIN " + TABLE_PRODUTO +
" ON " + TABLE_RECEITA_MATERIA_MAP + "." + COLUMN_PRODUTO_MAP +
" = " + TABLE_PRODUTO + "." + COLUMN_PRODUTO_CODIGO;
private static final String fkey_options = " ON DELETE CASCADE ON UPDATE CASCADE ";
private static volatile MyDatabase instance = null;
private MyDatabase(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = this.getWritableDatabase();
}
public static MyDatabase getDatabaseInstance(Context context) {
if (instance == null) {
instance = new MyDatabase(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ TABLE_PRODUTO +
" (" + COLUMN_PRODUTO_CODIGO + " INTEGER PRIMARY KEY, " +
COLUMN_PRODUTO + " TEXT, " +
COLUMN_VALOR + " FLOAT, " +
COLUMN_QTD + " FLOAT, " +
COLUMN_TIPO + " TEXT); ";
db.execSQL(query);
query = "CREATE TABLE IF NOT EXISTS " + TABLE_RECEITA + "(" +
COLUMN_RECEITA_CODIGO + " INTEGER PRIMARY KEY ," + /* ADDED to make things simpler android wise */
COLUMN_TITULO + " TEXT UNIQUE" +
")";
db.execSQL(query);
query = "CREATE TABLE IF NOT EXISTS " +TABLE_RECEITA_MATERIA_MAP + "(" +
COLUMN_RECEITA_MAP + " INTEGER REFERENCES " + TABLE_RECEITA + "(" + COLUMN_PRODUTO_CODIGO + ")" + fkey_options + "," +
COLUMN_PRODUTO_MAP + " INTEGER REFERENCES " + TABLE_PRODUTO + "(" + COLUMN_RECEITA_CODIGO + ")" + fkey_options + "," +
COLUMN_RECEITA_QTD + " FLOAT, " +
"PRIMARY KEY(" + COLUMN_RECEITA_MAP + "," + COLUMN_PRODUTO_MAP + ")" +
")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertProduto(String produto,Float valor, Float qtd, String tipo) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_PRODUTO,produto);
cv.put(COLUMN_VALOR,valor);
cv.put(COLUMN_QTD,qtd);
cv.put(COLUMN_TIPO,tipo);
return db.insert(TABLE_PRODUTO,null,cv);
}
public long insertReceita(String titulo) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITULO,titulo);
return db.insert(TABLE_RECEITA,null,cv);
}
public long insertReceitaMateria(long receitaMap, long produtoMap, Float qtd) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_RECEITA_MAP,receitaMap);
cv.put(COLUMN_PRODUTO_MAP,produtoMap);
cv.put(COLUMN_RECEITA_QTD,qtd);
return db.insert(TABLE_RECEITA_MATERIA_MAP,null,cv);
}
public int deleteMateriaFromReceita(long receita, long produtoCodigo) {
return db.delete(TABLE_RECEITA_MATERIA_MAP,COLUMN_RECEITA_MAP + " =? AND " + COLUMN_PRODUTO_MAP + "=?",new String[]{String.valueOf(receita), String.valueOf(produtoCodigo)});
}
public Cursor getProduto() {
return db.query(TABLE_PRODUTO,null,null,null,null,null,null);
}
public Cursor getReceita() {
return db.query(TABLE_RECEITA,null,null,null,null,null,null);
}
public Cursor getReceitaProduto(Long receita) {
return db.query(
TABLE_RECEITA + join_receitamateria_map + join_produto,
new String[]{"*",cost_calculate},
TABLE_RECEITA_MATERIA_MAP + "." + COLUMN_RECEITA_MAP + "=?",new String[]{receita.toString()},null,null,null);
}
public String getReceitanameByCodigo(long codigo) {
String rv = "NOT KNOWN";
Cursor csr =db.query(TABLE_RECEITA,new String[]{COLUMN_TITULO},COLUMN_RECEITA_CODIGO + "=?",new String[]{String.valueOf(codigo)},null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COLUMN_TITULO));
}
csr.close();
return rv;
}
}
Next is an initial activity MainActivity (designed to only run once) that adds some materia/produtos (ingredients) and some blank (no ingredients) receitas (recipes). After which the AddProduto activity is invoked passing the Cake recipe to the activity :-
public class MainActivity extends AppCompatActivity {
MyDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = MyDatabase.getDatabaseInstance(this);
db.insertProduto("Plain Flour",0.54F,1F,"Grams");
db.insertProduto("SR Flour",0.55F,1F,"Grams");
db.insertProduto("Eggs",1.34F,1f,"Each");
db.insertProduto("Milk",0.2F,1F,"ml");
db.insertProduto("Sugar",0.65F,1F,"Grams");
db.insertReceita("Bread");
long selectedId = db.insertReceita("Cake");
db.insertReceita("Scone");
Intent intent = new Intent(this,AddProduto.class);
intent.putExtra(MyDatabase.TABLE_RECEITA,selectedId);
startActivity(intent);
}
}
Finally is the AddProduto activity. This has a spinner that allows selection of an ingredient(s). Selecting an ingredient adds the ingredient to the recipe and the recipe's ingredients are then refreshed to show the added ingredient. If an ingredient in the list of ingredients is long clicked it is removed from the recipe.
Note only very basic management is incorporated. e.g. really the ingredients in the spinner should exclude those already in the recipe.
The amount/quantity of the ingredient is set to be 100 for simplicity/brevity of the demo/example:-
public class AddProduto extends AppCompatActivity {
TextView receita;
Spinner materia_add;
ListView materia_in;
SimpleCursorAdapter adapter_list, adapter_spinner;
MyDatabase db;
Cursor csr_add, csr_in;
long current_receita;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_produto);
db = MyDatabase.getDatabaseInstance(this);
receita = this.findViewById(R.id.Receita);
current_receita = this.getIntent().getLongExtra(MyDatabase.TABLE_RECEITA,0);
receita.setText(db.getReceitanameByCodigo(current_receita));
materia_add = this.findViewById(R.id.materia_add);
materia_in = this.findViewById(R.id.materia_in);
setOrRefreshSpinner();
setOrRefreshReceitaList();
}
// Handling the Spinner
private void setOrRefreshSpinner() {
csr_add = db.getProduto();
if (adapter_spinner == null) {
adapter_spinner = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr_add,
new String[]{MyDatabase.COLUMN_PRODUTO, MyDatabase.COLUMN_VALOR},
new int[]{android.R.id.text1, android.R.id.text2},0
);
materia_add.setAdapter(adapter_spinner);
materia_add.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
db.insertReceitaMateria(current_receita,l,100F); // Made up value for demo
setOrRefreshReceitaList(); // Update the List of materia in the receita
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} else {
adapter_spinner.swapCursor(csr_add);
}
}
// Handling the recipe ListView
private void setOrRefreshReceitaList() {
csr_in = db.getReceitaProduto(current_receita);
if (adapter_list == null) {
adapter_list = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr_in,
new String[]{MyDatabase.COLUMN_PRODUTO,MyDatabase.DERIVED_COLUMN_COST},
new int[]{android.R.id.text1,android.R.id.text2},
0
);
materia_in.setAdapter(adapter_list);
materia_in.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
db.deleteMateriaFromReceita(current_receita,l);
setOrRefreshReceitaList();
return true;
}
});
} else {
adapter_list.swapCursor(csr_in);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
csr_in.close();
csr_add.close();
}
}
Result
When first run the AddProduto activity is displayed (after MainActivity starts it) :-
Note that handling the fact that the Spinner automatically selects an Item has not been included so an ingredient is added before any selection is made (see Android Spinner : Avoid onItemSelected calls during initialization in regrad to avoiding this).
Purple is the Spinner
teal is the recipe's list of ingredients (with the total cost of the ingredient i.e. 100 * the ingredient cost).
Select Eggs from the Spinner :-
And then after selection (adding Eggs) :-
LongClick Plain Flour in the List of ingredients :-
Related
How do would you get the MAX value of a column that has been grouped and add together by _id.
So something like this:
I then want to display the MAX value of the four groups, as well as the MIN value of the four groups.
Something like this Scratch High = 702 / Scratch Low = 325
Is this possible with the built in Math functions of SQLite or would I need to write specific code to accomplish this? The actual number of groups will be more than 4, it will depend on how often the bowler actually bowls a series.
I haven't written any code for this as of yet, I am attempting to figure out if this is even possible before attempting to do so. Any suggestions would be welcome.
My attempt to integrate into my Project:
DatabaseHelper.java
public static final String DERIVEDCOL_MAXSCORE = "max_score";
public static final String DERIVEDCOl_MINSCORE = "min_score";
public Cursor getMaxMinScoresAllAndroid() {
SQLiteDatabase db = this.getWritableDatabase();
String tmptbl = "summed_scores";
String tmptblcol = "sum_score";
String crttmptbl = "CREATE TEMP TABLE IF NOT EXISTS " + tmptbl + "(" +
tmptblcol + " INTEGER" +
")";
String empttmptbl = "DELETE FROM " + tmptbl;
db.execSQL(crttmptbl);
db.execSQL(empttmptbl);
String[] columns = new String[]{"sum(score) AS " + tmptblcol};
Cursor csr = db.query(Game.TABLE_NAME,columns,null,null,Game.COLUMN_BOWLER_ID,null,null);
DatabaseUtils.dumpCursor(csr);
while (csr.moveToNext()) {
ContentValues cv = new ContentValues();
cv.put(tmptblcol,csr.getInt(csr.getColumnIndex(tmptblcol)));
db.insert(tmptbl,null,cv);
}
csr.close();
columns = new String[]{"max(" +
tmptblcol +
") AS " + DERIVEDCOL_MAXSCORE,
"min(" +
tmptblcol +
") AS " + DERIVEDCOl_MINSCORE};
return csr = db.query(tmptbl,columns,null,null,null,null,null);
}
public MaxMin getMaxAndminScoresAll() {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScoresAllAndroid();
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
BowlerProfileViewActivity.java
public class BowlerProfileViewActivity extends AppCompatActivity {
Bowler bowler;
private DatabaseHelper db;
private static final String PREFS_NAME = "prefs";
private static final String PREF_BLUE_THEME = "blue_theme";
private static final String PREF_GREEN_THEME = "green_theme";
private static final String PREF_ORANGE_THEME = "purple_theme";
private static final String PREF_RED_THEME = "red_theme";
private static final String PREF_YELLOW_THEME = "yellow_theme";
#Override
protected void onResume() {
super.onResume();
db = new DatabaseHelper(this);
//mAdapter.notifyDatasetChanged(db.getAllLeagues());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//Use Chosen Theme
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean useBlueTheme = preferences.getBoolean(PREF_BLUE_THEME, false);
if (useBlueTheme) {
setTheme(R.style.AppTheme_Blue_NoActionBar);
}
boolean useGreenTheme = preferences.getBoolean(PREF_GREEN_THEME, false);
if (useGreenTheme) {
setTheme(R.style.AppTheme_Green_NoActionBar);
}
boolean useOrangeTheme = preferences.getBoolean(PREF_ORANGE_THEME, false);
if (useOrangeTheme) {
setTheme(R.style.AppTheme_Orange_NoActionBar);
}
boolean useRedTheme = preferences.getBoolean(PREF_RED_THEME, false);
if (useRedTheme) {
setTheme(R.style.AppTheme_Red_NoActionBar);
}
boolean useYellowTheme = preferences.getBoolean(PREF_YELLOW_THEME, false);
if (useYellowTheme) {
setTheme(R.style.AppTheme_Yellow_NoActionBar);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bowler_profile_view);
Intent intent = getIntent();
Boolean shouldUpdate = getIntent().getExtras().getBoolean("shouldUpdate");
String savedLeagueId = intent.getStringExtra("leagueId");
String savedBowlerId = String.valueOf(getIntent().getIntExtra("bowlerId",2));
int bowlerId = Integer.valueOf(savedBowlerId);
getBowlerProfile(savedLeagueId, bowlerId);
// Get The min and max score
MaxMin bowlerMaxMin = db.getMaxAndminScoresAll();
Log.d("SCORES",
"\n\tMaximum Score is " + String.valueOf(bowlerMaxMin.getMax()) +
"\n\tMinimum Score is " + String.valueOf(bowlerMaxMin.getMin()));
}
public void getBowlerProfile(String savedLeagueId, int savedBowlerId) {
String bn, ba, bh;
SQLiteOpenHelper database = new DatabaseHelper(this);
SQLiteDatabase db = database.getReadableDatabase();
Cursor viewBowlerProfile = db.query( Bowler.TABLE_NAME,
new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_BOWLER_AVERAGE, Bowler.COLUMN_BOWLER_HANDICAP, Bowler.COLUMN_TIMESTAMP},
Bowler.COLUMN_ID + "=?",
new String[]{String.valueOf(savedBowlerId)}, null, null, null, null);
if (viewBowlerProfile.moveToFirst()) {
//Prepare League Object
bowler = new Bowler(
viewBowlerProfile.getInt(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_ID)),
viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
bn = viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_NAME)),
ba = viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)),
bh = viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)),
viewBowlerProfile.getString(viewBowlerProfile.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
final TextView bowlerName = (TextView) findViewById(R.id.tvBowlerName);
final TextView bowlerAverage = (TextView) findViewById(R.id.tvBowlerAverageValue);
final TextView bowlerHandicap = (TextView) findViewById(R.id.tvBowlerHandicapValue);
bowlerName.setText(String.valueOf(bn));
bowlerAverage.setText(String.valueOf(ba));
bowlerHandicap.setText(String.valueOf(bh));
//Close Database Connection
viewBowlerProfile.close();
}
//View League Profile Cancel Button
final Button cancel_button = (Button) findViewById(R.id.bCancel);
cancel_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("SAVEDLEAGUEID_VAL", ">>" + String.valueOf(savedLeagueId) + "<<");
Intent intent = new Intent(getApplicationContext(), BowlerActivity.class);
intent.putExtra("leagueId", savedLeagueId);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
/*Intent intent = new Intent(getApplicationContext(), BowlerActivity.class);
intent.putExtra("leagueId", savedLeagueId);
Log.d("LEAGUEID VALUE","value of leagueId = " + String.valueOf(savedLeagueId));
startActivity(intent);
finish();
overridePendingTransition(0, 0);*/
}
});
//Edit League Profile Cancel Button
final Button edit_button = (Button) findViewById(R.id.bEdit);
edit_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int bowlerId = bowler.getId();
Intent intent = new Intent(getApplicationContext(), BowlerProfileEditActivity.class);
intent.putExtra("bowlerId", bowlerId);
intent.putExtra("leagueId", savedLeagueId);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
});
}
}
Logcat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'ca.rvogl.tpbcui.utils.MaxMin ca.rvogl.tpbcui.database.DatabaseHelper.getMaxAndminScoresAll()' on a null object reference
at ca.rvogl.tpbcui.views.BowlerProfileViewActivity.onCreate(BowlerProfileViewActivity.java:79)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
Attempting to group by bowlerId and seriesId
public Cursor getMaxMinScoresAllAndroid(String bowlerId) {
SQLiteDatabase db = this.getWritableDatabase();
String tmptbl = "summed_scores";
String tmptblcol = "sum_score";
String tmpBowlerIdCol = "bowler_id";
String tmpSeriesIdCol = "series_id";
String crttmptbl = "CREATE TEMP TABLE IF NOT EXISTS " + tmptbl + "(" +
tmptblcol + " INTEGER," +
tmpBowlerIdCol + " TEXT," +
tmpSeriesIdCol + " TEXT)";
String empttmptbl = "DELETE FROM " + tmptbl;
db.execSQL(crttmptbl);
db.execSQL(empttmptbl);
String[] columns = new String[]{"sum(score) AS "};
Cursor csr = db.query(Game.TABLE_NAME,columns,null,null,Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'", Game.COLUMN_SERIES_ID,null,null);
DatabaseUtils.dumpCursor(csr);
while (csr.moveToNext()) {
ContentValues cv = new ContentValues();
cv.put(tmptblcol,csr.getInt(csr.getColumnIndex(tmptblcol)));
cv.put(tmpBowlerIdCol,csr.getInt(csr.getColumnIndex(tmpBowlerIdCol)));
cv.put(tmpSeriesIdCol,csr.getInt(csr.getColumnIndex(tmpSeriesIdCol)));
db.insert(tmptbl,null,cv);
}
csr.close();
columns = new String[]{"max(" +
tmptblcol +
") AS " + DERIVEDCOL_MAXSCORE,
"min(" +
tmptblcol +
") AS " + DERIVEDCOl_MINSCORE};
return csr = db.query(tmptbl,columns,null,null,null,null,null);
}
public MaxMin getMaxAndminScoresAll(String bowlerId) {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScoresAllAndroid(bowlerId);
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
You could do this (assuming the table is named myscores and the columns are _id and score) using :-
WITH cte1 AS
(
sum(score) AS sum_score
FROM myscores
GROUP BY _id
)
SELECT max(sum_score) AS min_score, min(sum_score) FROM cte1;
Using this would result in the following :-
Notes
AS is used to rename the output columns
without renaming the columns they would be named max(sum_score) and min(sum_score) respectively.
SQL As Understood By SQLite - Aggregate Functions
This utilises the SQLite aggregate functions max and min and the GROUP BY clause to aggregate the columns according to the _id column.
This also utilises a Common Table Expression (an intermediate/temporary table).
SQL As Understood By SQLite - WITH clause
Incorporating into an Android App (see note at end)
The following is an example App demonstrates how this can be incorporated fro Android :-
First a simple class for the Minimum and maximum vales (as used in the alternative getMaxAndMinScores method)
MaxMin.java (optional)
public class MaxMin {
private int min;
private int max;
public MaxMin(int min, int max) {
this.min = min;
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
}
DBHelper.java
The subclass of SQLiteOpenHelper (just the one table name myscores)
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_SCORE = "myscores";
public static final String COL_SCORE = "score";
public static final String COL_ID = BaseColumns._ID;
public static final String DERIVEDCOL_MAXSCORE = "max_score";
public static final String DERIVEDCOl_MINSCORE = "min_score";
private static final String crt_myscores_sql = "CREATE TABLE IF NOT EXISTS " + TB_SCORE + "(" +
COL_ID + " INTEGER," +
COL_SCORE + " INTEGER" +
")";
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(crt_myscores_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long addScore(long id, int score) {
ContentValues cv = new ContentValues();
cv.put(COL_ID,id);
cv.put(COL_SCORE,score);
return this.getWritableDatabase().insert(TB_SCORE,null,cv);
}
public Cursor getMaxMinScores() {
String sum_score = "sum_score";
String cte1 = "cte1";
String rawqry = " WITH " + cte1 +
" AS " +
"(" +
"SELECT sum(" +
COL_SCORE +
") AS " + sum_score +
" FROM " + TB_SCORE + " GROUP BY " + COL_ID +
") " +
"SELECT " +
" max(" +
sum_score +
") AS " + DERIVEDCOL_MAXSCORE +
"," +
" min(" +
sum_score +
") AS " + DERIVEDCOl_MINSCORE +
" FROM " + cte1 + ";";
return this.getWritableDatabase().rawQuery(rawqry,null);
}
public MaxMin getMaxAndMinScores() {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScores();
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
}
MainActivity.java
The activity that a) adds some rows and then b) gets the maximum and minimum scores (twice using alternative methods) :-
public class MainActivity extends AppCompatActivity {
DBHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DBHelper(this);
// Add Some scores
mDBHlpr.addScore(1,112);
mDBHlpr.addScore(1,123);
mDBHlpr.addScore(1,144);
mDBHlpr.addScore(2,212);
mDBHlpr.addScore(2,190);
mDBHlpr.addScore(2,300);
mDBHlpr.addScore(3,234);
mDBHlpr.addScore(3,134);
mDBHlpr.addScore(3,122);
mDBHlpr.addScore(4,100);
mDBHlpr.addScore(4,111);
mDBHlpr.addScore(4,114);
// Get The min and max scores example 1
Cursor csr = mDBHlpr.getMaxMinScores();
if (csr.moveToFirst()) {
int max_score = csr.getInt(csr.getColumnIndex(DBHelper.DERIVEDCOL_MAXSCORE));
int min_score = csr.getInt(csr.getColumnIndex(DBHelper.DERIVEDCOl_MINSCORE));
Log.d("SCORES",
"\n\tMaximum Score is " + String.valueOf(max_score) +
"\n\tMinimum Score is " + String.valueOf(min_score)
);
}
//Alternative utilising the MaxMin object
MaxMin mymaxmin = mDBHlpr.getMaxAndMinScores();
Log.d("SCORES",
"\n\tMaximum Score is " + String.valueOf(mymaxmin.getMax()) +
"\n\tMinimum Score is " + String.valueOf(mymaxmin.getMin())
);
}
}
IMPORTANT
The WITH clause was introduced in SQL 3.8.3, some older versions of Android (below lollipop (but can be device independent)) will not
support the WITH clause.
The following methods, as equivalents of getMaxMinScores and getMaxAndMinScores could be used for any Android version :-
public Cursor getMaxMinScoresAllAndroid() {
SQLiteDatabase db = this.getWritableDatabase();
String tmptbl = "summed_scores";
String tmptblcol = "sum_score";
String crttmptbl = "CREATE TEMP TABLE IF NOT EXISTS " + tmptbl + "(" +
tmptblcol + " INTEGER" +
")";
String empttmptbl = "DELETE FROM " + tmptbl;
db.execSQL(crttmptbl);
db.execSQL(empttmptbl);
String[] columns = new String[]{"sum(score) AS " + tmptblcol};
Cursor csr = db.query(TB_SCORE,columns,null,null,COL_ID,null,null);
DatabaseUtils.dumpCursor(csr);
while (csr.moveToNext()) {
ContentValues cv = new ContentValues();
cv.put(tmptblcol,csr.getInt(csr.getColumnIndex(tmptblcol)));
db.insert(tmptbl,null,cv);
}
csr.close();
columns = new String[]{"max(" +
tmptblcol +
") AS " + DERIVEDCOL_MAXSCORE,
"min(" +
tmptblcol +
") AS " + DERIVEDCOl_MINSCORE};
return csr = db.query(tmptbl,columns,null,null,null,null,null);
}
public MaxMin getMaxAndminScoresAllAndroid() {
MaxMin rv = new MaxMin(0,0);
Cursor csr = getMaxMinScoresAllAndroid();
if (csr.moveToFirst()) {
rv.setMin(csr.getInt(csr.getColumnIndex(DERIVEDCOl_MINSCORE)));
rv.setMax(csr.getInt(csr.getColumnIndex(DERIVEDCOL_MAXSCORE)));
}
csr.close();
return rv;
}
These utilise an intermediate temporary table so bypass the restriction of using WITH
I am updating a record in Sqlite database through the function given below.Their is only 1 Table and a number of columns.Initially i am updating 3 columns. Problem i am facing :
1) The Problem is that in Logcat initial data is shown but updated data is not showing. Also Logcat not showing any error.
2) When i am displaying in Toast only last value which i added in database statically is showing. Initial two are not present in Toast.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class ContractSqlite extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "thorcontract_Db";
// TABLE NAME
private static final String TABLE_NAME = "contract";
// COLUMN
private static final String PRIMARY_COLUMN = "heading";
private static final String CONTRACT_TITLES_TITLE = "cnttitle";
private static final String CONTRACT_TITLES_SUBTITLE = "cntSUBTITLE";
private static final String CONTRACT_TITLES_BIDID = "cntbidid";
private static final String LOADSUMMARY_HEADER = "lsheader";
private static final String LOADSUMMARY_FOOTER = "lsfooter";
private static final String SECTION1_TITLE = "s1title";
private static final String SECTION1_BODY = "s1body";
private static final String SECTION2_TITLE = "s2title";
private static final String SECTION2_BODY = "s2body";
private static final String SECTION3_TITLE = "s3title";
private static final String SECTION3_BODY = "s3body";
private static final String SECTION4_TITLE = "s4title";
private static final String SECTION4_BODY = "s4body";
private static final String SECTION5_TITLE = "s5title";
private static final String SECTION5_BODY = "s5body";
private static final String SECTION6_TITLE = "s6title";
private static final String SECTION6_BODY = "s6body";
private static final String SECTION7_TITLE = "s7title";
private static final String SECTION7_BODY = "s7body";
private static final String SECTION8_TITLE = "s8title";
private static final String SECTION8_BODY = "s8body";
private static final String SECTION9_TITLE = "s9title";
private static final String SECTION9_BODY = "s9body";
private String title = null, subtitle = null, bidid = null;
public ContractSqlite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTRACT_TABLE = " CREATE TABLE " + TABLE_NAME + "("
+ PRIMARY_COLUMN + " INTEGER PRIMARY KEY,"
+ CONTRACT_TITLES_TITLE + " TEXT ," + CONTRACT_TITLES_SUBTITLE
+ " TEXT ," + CONTRACT_TITLES_BIDID + " TEXT,"
+ LOADSUMMARY_HEADER + " TEXT," + LOADSUMMARY_FOOTER + " TEXT,"
+ SECTION1_TITLE + " TEXT," + SECTION1_BODY + " TEXT,"
+ SECTION2_TITLE + " TEXT," + SECTION2_BODY + " TEXT,"
+ SECTION3_TITLE + " TEXT," + SECTION3_BODY + " TEXT,"
+ SECTION4_TITLE + " TEXT," + SECTION4_BODY + " TEXT,"
+ SECTION5_TITLE + " TEXT," + SECTION5_BODY + " TEXT,"
+ SECTION6_TITLE + " TEXT," + SECTION6_BODY + " TEXT,"
+ SECTION7_TITLE + " TEXT," + SECTION7_BODY + " TEXT,"
+ SECTION8_TITLE + " TEXT," + SECTION8_BODY + " TEXT,"
+ SECTION9_TITLE + " TEXT," + SECTION9_BODY + " TEXT" + ")";
db.execSQL(CREATE_CONTRACT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE" + TABLE_NAME);
onCreate(db);
}
public void addRecord(String title, String subtitle, String bidid) {
SQLiteDatabase db = this.getWritableDatabase();
// String title1 = title;
// String subtitle1 = subtitle;
// String bidid1 = bidid;
ContentValues values = new ContentValues();
try {
values.put(CONTRACT_TITLES_TITLE, title);
values.put(CONTRACT_TITLES_SUBTITLE, subtitle);
values.put(CONTRACT_TITLES_BIDID, bidid);
db.insert(TABLE_NAME, null, values);
Log.i("Initial Data", " " + title + " " + subtitle + " " + bidid);
db.close();
} catch (Exception e) {
db.close();
}
}
public String[] getrecord() {
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()) {
title = cursor.getString(cursor
.getColumnIndex(CONTRACT_TITLES_TITLE));
subtitle = cursor.getString(cursor
.getColumnIndex(CONTRACT_TITLES_SUBTITLE));
bidid = cursor.getString(cursor
.getColumnIndex(CONTRACT_TITLES_BIDID));
// Dumps "Title: Test Title Content: Test Content"
Log.i("CONTRACTTITLES", "Title: " + title + " Content: " + subtitle);
cursor.close();
}
return new String[] { title, subtitle, bidid };
}
public int update(String title, String subtitle, String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CONTRACT_TITLES_TITLE, title);
values.put(CONTRACT_TITLES_SUBTITLE, subtitle);
values.put(CONTRACT_TITLES_SUBTITLE, id);
return db.update(TABLE_NAME, values, PRIMARY_COLUMN + " =?",
new String[] { String.valueOf(1) });
}
}
Method Calling From Main Activity.
csq is database class object
for adding a record
csq.addRecord("abc", "xyz", "1234");
for updating
csq.update(cnttitle_str, cntsubtitle_str, cntbid_str);
for getting a record
String[] str = csq.getrecord();
Toast.makeText(getActivity(),
" " + str[0] + " " + str[1] + "" + str[2], Toast.LENGTH_LONG).show();
Updated data is not showing because you don't have a Log line there (if I understand you correctly).
You only get one line because you need to iterate through the Cursor and return a list or some such.
this sulotion is :
if you want to see all record , do this in your Database class :
public void showAllDBcells() {
String selectQuery = "SELECT * FROM " + TABLE_DB;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Log.d("your tag",cursor.getString(0));
Log.d("your tag",cursor.getString(1));
Log.d("your tag",cursor.getString(2));
// and for another data , just extends code for 3 4 5 ... columns
} while (cursor.moveToNext());
}
//
cursor.close();
db.close();
}
you can call method in your activity , and see your stored data from Database in Logcat .
I want to know how to check for duplicated fields in my database by updating it.
If the day and hour are the same in another row it must give an error.
DBHelper:
package me.wouter.schoolwork;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Schedule {
public static final String KEY_ROWID = "_id"; //Row Id
public static final String KEY_HOUR = "schedule_hour";
public static final String KEY_DAY = "schedule_day";
public static final String KEY_LOCATION = "schedule_location";
public static final String KEY_SUBJECT = "schedule_subject";
public static final String KEY_START = "schedule_start";
public static final String KEY_END = "schedule_end";
private static final String DATABASE_NAME = "PlanYourDay";
private static final String DATABASE_TABLE = "schedule";
private static final int DATABASE_VERSION = 1;
private dBHelper classHelper;
private final Context classContext;
private SQLiteDatabase classDatabase;
public Cursor c;
private static class dBHelper extends SQLiteOpenHelper {
public dBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_HOUR + " TEXT NOT NULL, " +
KEY_DAY + " TEXT NOT NULL, " +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_SUBJECT + " TEXT NOT NULL, " +
KEY_START + " TEXT NOT NULL, " +
KEY_END + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Schedule(Context c){
classContext = c;
}
public Schedule open() throws SQLException{
classHelper = new dBHelper(classContext);
classDatabase = classHelper.getWritableDatabase();
return this;
}
public Schedule close(){
classHelper.close();
return this;
}
public long createEntry(String subject, String day, String hour,
String location, String start, String end) {
ContentValues cv = new ContentValues();
cv.put(KEY_SUBJECT, subject);
cv.put(KEY_DAY, day);
cv.put(KEY_HOUR, hour);
cv.put(KEY_LOCATION, location);
cv.put(KEY_START, start);
cv.put(KEY_END, end);
return classDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_SUBJECT, KEY_HOUR, KEY_DAY, KEY_LOCATION, KEY_START, KEY_END};
c = classDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
final int iSubject = c.getColumnIndex(KEY_SUBJECT);
int iHour = c.getColumnIndex(KEY_HOUR);
int iDay = c.getColumnIndex(KEY_DAY);
int iLocation = c.getColumnIndex(KEY_LOCATION);
int iStart = c.getColumnIndex(KEY_START);
int iEnd = c.getColumnIndex(KEY_END);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iSubject) + " " + c.getString(iHour) + " "
+ c.getString(iDay) + " " + c.getString(iLocation) + " " + c.getString(iStart) + " "
+ c.getString(iEnd) + "\n";
}
return result;
}
}
DB Inserter:
package me.wouter.schoolwork;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ScheduleTest extends Activity implements OnClickListener {
// object variables
Button bLoadSql, bSaveSql;
TextView viewSubject, viewDay, viewHour, viewLocation, viewStart, viewEnd;
EditText editSubject, editDay, editHour, editLocation, editStart, editEnd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sql);
allTheVariables();
bLoadSql.setOnClickListener(this);
bSaveSql.setOnClickListener(this);
}
private void allTheVariables() {
// defines variables in xml file
// buttons
bLoadSql = (Button) findViewById(R.id.bLoadSql);
bSaveSql = (Button) findViewById(R.id.bSaveSql);
// textviews
viewSubject = (TextView) findViewById(R.id.viewSubject);
viewDay = (TextView) findViewById(R.id.viewDay);
viewHour = (TextView) findViewById(R.id.viewHour);
viewLocation = (TextView) findViewById(R.id.viewLocation);
viewStart = (TextView) findViewById(R.id.viewStart);
viewEnd = (TextView) findViewById(R.id.viewEnd);
// edittext
editSubject = (EditText) findViewById(R.id.editSubject);
editDay = (EditText) findViewById(R.id.editDay);
editHour = (EditText) findViewById(R.id.editHour);
editLocation = (EditText) findViewById(R.id.editLocation);
editStart = (EditText) findViewById(R.id.editStart);
editEnd = (EditText) findViewById(R.id.editEnd);
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bLoadSql:
Intent i = new Intent("me.wouter.schoolwork.SCHEDULEVIEW");
startActivity(i);
break;
case R.id.bSaveSql:
boolean didItWork = true;
try{
String subject = editSubject.getText().toString();
String day = editDay.getText().toString();
String hour = editHour.getText().toString();
String location = editLocation.getText().toString();
String start = editStart.getText().toString();
String end = editEnd.getText().toString();
Schedule entry = new Schedule(this);
entry.open();
entry.createEntry(subject, day, hour, location, start, end);
entry.close();
}catch (Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Failed");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(didItWork){
Dialog d = new Dialog(this);
d.setTitle("Inserted");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
}
}
}
And Viewer/Loader:
package me.wouter.schoolwork;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ScheduleView extends Activity {
TextView subject;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
subject = (TextView) findViewById(R.id.subject);
Schedule info = new Schedule(this);
info.open();
String data = info.getData();
subject.setText(data);
info.close();
}
}
Thanks in advance!
It seems to me that what you need is a multi-column uniqueness constraint on your DB schema, with a suitable conflict clause:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_HOUR + " TEXT NOT NULL, " +
KEY_DAY + " TEXT NOT NULL, " +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_SUBJECT + " TEXT NOT NULL, " +
KEY_START + " TEXT NOT NULL, " +
KEY_END + " TEXT NOT NULL, " +
"UNIQUE (" + KEY_DAY + ", " + KEY_HOUR + ") ON CONFLICT ROLLBACK);"
);
This will generate a constraint violation error if the day/hour combination is not unique, without you having to write an explicit check.
My problem is that I don't know how exactly I can display data from the database.
Here is my DatabaseHelper activity ( I've cut not needed code ), which open/close database and create tables.
final static String PN_TABLE = "Tablica_Poniedzialek";
static final String PN_KEY_ID = "_id";
final static String PN_KEY_TYPE_OF_SESSION ="type_of_session";
final static String PN_KEY_START_TIME ="start_time";
final static String PN_KEY_END_TIME ="end_time";
final static String PN_KEY_NAME ="name";
final static String PN_KEY_ROOM ="room";
Creating and adding data to the database works fine. The problem is that I don't know how exactly I should display data inserted into the database. I've tried using Cursors and List Adapter, but it seems that I've messed up something since application is forced to close every time I am launching it in an Emulator.
This is my activity which is responsible for getting data from Database and then displaying it. I have no clue how actually I can display data as a list view. I am not sure which method would be better, the one which creates list ( I believe that it does ) or one that simply fetch data from database. But, let's say that the first one is correct, then the question is how can I actually display all the data ?
package com.projekt;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
public class PoniedzialekActivity extends ListActivity implements OnClickListener{
private Button butPnAdd;
private DatabaseHelper dbhelper;
private SQLiteDatabase db;
Cursor cursor;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_poniedzialek);
butPnAdd = (Button) findViewById(R.id.butPnAdd);
butPnAdd.setOnClickListener(this);
List<Poniedzialek> lista_poniedzialek = getAllPnSession();
this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, lista_poniedzialek));
#Override
public void onClick(View v) {
if(v.getId()==R.id.butPnAdd){
Intent i = new Intent(PoniedzialekActivity.this,dodawaniePoniedzialek.class);
startActivity(i);
}
}
public List<Poniedzialek> getAllPnSession() {
List<Poniedzialek> pnsessionList = new ArrayList<Poniedzialek>();
// Wybierz cale Query
String selectQuery = "SELECT * FROM " + DatabaseHelper.PN_TABLE;
dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// petla po wszystkich rzedach & dodawanie ich do listy
if (cursor.moveToFirst()) {
do {
Poniedzialek pn = new Poniedzialek();
pn.setID(Integer.parseInt(cursor.getString(0)));
pn.setTypeOfSession(cursor.getString(1));
pn.setName(cursor.getString(2));
pn.setStartTime(cursor.getString(3));
pn.setEndTime(cursor.getString(4));
pn.setRoom(cursor.getString(5));
// Dodawanie sesji do listy
pnsessionList.add(pn);
} while (cursor.moveToNext());
}
cursor.close();
// return contact list
return pnsessionList;
}
public Cursor fetchPn() {
SQLiteDatabase db = dbhelper.getWritableDatabase();
return db.query(DatabaseHelper.PN_TABLE, new String[] {DatabaseHelper.PN_KEY_TYPE_OF_SESSION, DatabaseHelper.PN_KEY_START_TIME,
DatabaseHelper.PN_KEY_END_TIME, DatabaseHelper.PN_KEY_NAME, DatabaseHelper.PN_KEY_ROOM}, null, null, null, null, null);
}
} // end PoniedzialekActivity
This is layout_poniedzialek:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/butPnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_pn"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/tab1"
/>
<ListView
android:id="#+id/pnListView"
android:layout_width="304dp"
android:layout_height="380dp"
android:layout_gravity="center_horizontal" >
</ListView>
</LinearLayout>
E D I T
Now I keep getting an error: NullPointerException. This is what I've implemented in poniedzialekActivity ( Please note that DatabaseHelper is the name of class where I keep open/close and static final string attributes - here I am creating 5 tablets )
PoniedzialekActivity class:
public class PoniedzialekActivity extends ListActivity implements OnClickListener{
private Button butPnAdd;
private DatabaseHelper dbhelper;
private SQLiteDatabase db;
Cursor c;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_poniedzialek);
butPnAdd = (Button) findViewById(R.id.butPnAdd);
butPnAdd.setOnClickListener(this);
dbhelper = new DatabaseHelper(this);
dbhelper.open();
c = dbhelper.fetchPn();
String[] columns = new String[] { DatabaseHelper.PN_KEY_TYPE_OF_SESSION, DatabaseHelper.PN_KEY_START_TIME, DatabaseHelper.PN_KEY_END_TIME,
DatabaseHelper.PN_KEY_NAME, DatabaseHelper.PN_KEY_ROOM};
int[] to = new int[] { R.id.textSession, R.id.textStartTime, R.id.textEndTime, R.id.textName, R.id.textRoom };
new SimpleCursorAdapter(PoniedzialekActivity.this, R.layout.entry, c, columns, to);
ListView list = getListView();
list.setAdapter(new SimpleCursorAdapter(PoniedzialekActivity.this, R.layout.entry, c, columns, to));
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.butPnAdd){
Intent i = new Intent(PoniedzialekActivity.this,dodawaniePoniedzialek.class);
startActivity(i);
}
}
}
DatabaseHelper.class
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database.db";
private static final int DATABASE_VERSION = 1;
public static final String TAG = "ProjectDatabase";
static final String PN_TABLE = "Tablica_Poniedzialek";
static final String PN_KEY_ID = "_id";
static final String PN_KEY_TYPE_OF_SESSION ="type_of_session";
static final String PN_KEY_START_TIME ="start_time";
static final String PN_KEY_END_TIME ="end_time";
static final String PN_KEY_NAME ="name";
static final String PN_KEY_ROOM ="room";
static final String WT_TABLE = "Tablica_Wtorek";
static final String WT_KEY_ID = "_id";
static final String WT_KEY_TYPE_OF_SESSION ="type_of_session";
static final String WT_KEY_START_TIME ="start_time";
static final String WT_KEY_END_TIME ="end_time";
static final String WT_KEY_NAME ="name";
static final String WT_KEY_ROOM ="room";
static final String SR_TABLE = "Tablica_Sroda";
static final String SR_KEY_ID = "_id";
static final String SR_KEY_TYPE_OF_SESSION ="type_of_session";
static final String SR_KEY_START_TIME ="start_time";
static final String SR_KEY_END_TIME ="end_time";
static final String SR_KEY_NAME ="name";
static final String SR_KEY_ROOM ="room";
static final String CZ_TABLE = "Tablica_Czwartek";
static final String CZ_KEY_ID = "_id";
static final String CZ_KEY_TYPE_OF_SESSION ="type_of_session";
static final String CZ_KEY_START_TIME ="start_time";
static final String CZ_KEY_END_TIME ="end_time";
static final String CZ_KEY_NAME ="name";
static final String CZ_KEY_ROOM ="room";
static final String PT_TABLE = "Tablica_Piatek";
static final String PT_KEY_ID = "_id";
static final String PT_KEY_TYPE_OF_SESSION ="type_of_session";
static final String PT_KEY_START_TIME ="start_time";
static final String PT_KEY_END_TIME ="end_time";
static final String PT_KEY_NAME ="name";
static final String PT_KEY_ROOM ="room";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private DatabaseHelper dbhelper;
private SQLiteDatabase db;
#Override
public void onCreate(SQLiteDatabase db) {
String pn_sql = "CREATE TABLE " + PN_TABLE +
"(" + PN_KEY_ID + " integer primary key autoincrement, " +
PN_KEY_TYPE_OF_SESSION + " text, " +
PN_KEY_NAME + " text, " +
PN_KEY_START_TIME + " text, " +
PN_KEY_END_TIME + " text, " +
PN_KEY_ROOM + " text);";
String wt_sql = "CREATE TABLE " + WT_TABLE +
"(" + WT_KEY_ID + " integer primary key autoincrement, " +
WT_KEY_TYPE_OF_SESSION + " text, " +
WT_KEY_NAME + " text, " +
WT_KEY_START_TIME + " text, " +
WT_KEY_END_TIME + " text, " +
WT_KEY_ROOM + " text);";
String sr_sql = "CREATE TABLE " + SR_TABLE +
"(" + SR_KEY_ID + " integer primary key autoincrement, " +
SR_KEY_TYPE_OF_SESSION + " text, " +
SR_KEY_NAME + " text, " +
SR_KEY_START_TIME + " text, " +
SR_KEY_END_TIME + " text, " +
SR_KEY_ROOM + " text);";
String cz_sql = "CREATE TABLE " + CZ_TABLE +
"(" + CZ_KEY_ID + " integer primary key autoincrement, " +
CZ_KEY_TYPE_OF_SESSION + " text, " +
CZ_KEY_NAME + " text, " +
CZ_KEY_START_TIME + " text, " +
CZ_KEY_END_TIME + " text, " +
CZ_KEY_ROOM + " text);";
String pt_sql = "CREATE TABLE " + PT_TABLE +
"(" + PT_KEY_ID + " integer primary key autoincrement, " +
PT_KEY_TYPE_OF_SESSION + " text, " +
PT_KEY_NAME + " text, " +
PT_KEY_START_TIME + " text, " +
PT_KEY_END_TIME + " text, " +
PT_KEY_ROOM + " text);";
db.execSQL(pn_sql);
db.execSQL(wt_sql);
db.execSQL(sr_sql);
db.execSQL(cz_sql);
db.execSQL(pt_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Projekt", "aktualizacja z wersji " + oldVersion
+ " do wersji " + newVersion + " ( stare dane ulegna usunieciu ) ");
db.execSQL("DROP TABLE IF EXISTS" + PN_TABLE);
db.execSQL("DROP TABLE IF EXISTS" + WT_TABLE);
db.execSQL("DROP TABLE IF EXISTS" + SR_TABLE);
db.execSQL("DROP TABLE IF EXISTS" + CZ_TABLE);
db.execSQL("DROP TABLE IF EXISTS" + PT_TABLE);
onCreate(db);
}
public void open()
{
dbhelper.open();
}
public void close()
{
dbhelper.close();
}
public Cursor fetchPn() {
return db.query(PN_TABLE, new String[] {PN_KEY_TYPE_OF_SESSION, PN_KEY_START_TIME,
PN_KEY_END_TIME, PN_KEY_NAME, PN_KEY_ROOM}, null, null, null, null, null);
}
}
This is my MainActivity class, which holds TabHost:
public class MainActivity extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//--- TABHOST ---//
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, PoniedzialekActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("Pn").setIndicator("Pn",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, WtorekActivity.class);
spec = tabHost.newTabSpec("Wt").setIndicator("Wt",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SrodaActivity.class);
spec = tabHost.newTabSpec("Sr").setIndicator("Sr",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, CzwartekActivity.class);
spec = tabHost.newTabSpec("Cz").setIndicator("Cz",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, PiatekActivity.class);
spec = tabHost.newTabSpec("Pt").setIndicator("Pt",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(1);
//--- END OF TABHOST ---//
}
}
setListAdapter() isn't defined for Activity... so I'm not sure how your code even compiles.
You need to inflate your layout, find the ListView using findViewById, and then set its adapter.
ListView lv = (ListView) findViewById(R.id.pnListView);
lv.setAdapter(...);
I can create the database just fine, I can Insert and view the values, but whenever I close the android virtual device in eclipse and reopen it, the database values are gone! :O
Please help me!
There are 3 classes : (1 that handles the database and 2 activities)
It would mean the world to me!!! :O
I'd +rep if I coudl
Thank you guys sooo much!#!!!
Here is my code
Database manager :`
package com.jeux;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database2 {
private static final String DATABASE_NAME = "JeuxMotActivity";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_CATEGORIE = "Categorie";
public static final String KEY_CATEGORIE_ID_CATEGORIE = "IDCategorie";
public static final String KEY_CATEGORIE_NOM_CATEGORIE = "NomCategorie";
public static final String TABLE_MOT = "Mot";
public static final String KEY_MOT_ID_MOT = "IDMot";
public static final String KEY_MOT_MOT = "Mot";
public static final String KEY_MOT_EMAIL = "Email";
public static final String KEY_MOT_ID_CATEGORIE = "IDCategorie";
public static final String TABLE_ADMINISTRATEUR = "Administrateur";
public static final String KEY_ADMINISTRATEUR_EMAIL = "Email";
public static final String KEY_ADMINISTRATEUR_PASSWORD = "Password";
public static final String TABLE_SCORE = "Score";
public static final String KEY_SCORE_ID_JEU = "IDJeu";
public static final String KEY_SCORE_USERNAME = "Username";
public static final String KEY_SCORE_SCORE = "Score";
public static final String KEY_SCORE_INITIALES = "Initiales";
public static final String TABLE_UTILISATEUR = "Utilisateur";
public static final String KEY_UTILISATEUR_USERNAME = "Username";
public static final String KEY_UTILISATEUR_PASSWORD = "Password";
public static final String TABLE_JEU = "jeu";
public static final String KEY_JEU_ID_JEU = "IDJeu";
public static final String KEY_JEU_NOM_JEU = "NomJeu";
public static final String KEY_JEU_COMMENTAIRES = "Commentaires";
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(android.database.sqlite.SQLiteDatabase nb) {
//TODO check teh constraints and the relations
nb.execSQL("CREATE TABLE " + TABLE_CATEGORIE + " (" +
KEY_CATEGORIE_ID_CATEGORIE + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CATEGORIE_NOM_CATEGORIE + " TEXT NOT NULL" + ");"
);
nb.execSQL("CREATE TABLE " + TABLE_MOT + " (" +
KEY_MOT_ID_MOT + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_MOT_MOT + " TEXT NOT NULL," +
KEY_MOT_EMAIL + " TEXT NOT NULL," +
KEY_MOT_ID_CATEGORIE + " TEXT NOT NULL," +
"FOREIGN KEY(" + KEY_MOT_ID_CATEGORIE + ") REFERENCES " + TABLE_CATEGORIE + "(" + KEY_CATEGORIE_ID_CATEGORIE + ")," +
"FOREIGN KEY(" + KEY_MOT_EMAIL + ") REFERENCES " + TABLE_ADMINISTRATEUR + "(" + KEY_ADMINISTRATEUR_EMAIL + ")" +
");"
);
nb.execSQL("CREATE TABLE " + TABLE_ADMINISTRATEUR + " (" +
KEY_ADMINISTRATEUR_EMAIL + " TEXT PRIMARY KEY , " +
KEY_ADMINISTRATEUR_PASSWORD + " TEXT NOT NULL" + ");"
);
nb.execSQL("CREATE TABLE " + TABLE_SCORE + " (" +
KEY_SCORE_ID_JEU + " TEXT NOT NULL, " +
KEY_SCORE_USERNAME + " TEXT NOT NULL," +
KEY_SCORE_SCORE + " INTEGER NOT NULL," +
KEY_SCORE_INITIALES + " TEXT NOT NULL," +
"FOREIGN KEY(" + KEY_SCORE_ID_JEU + ") REFERENCES " + TABLE_JEU + "(" + KEY_JEU_ID_JEU + ")," +
"FOREIGN KEY(" + KEY_SCORE_USERNAME + ") REFERENCES " + TABLE_UTILISATEUR + "(" + KEY_UTILISATEUR_USERNAME + ")" +
");"
);
nb.execSQL("CREATE TABLE " + TABLE_UTILISATEUR + " (" +
KEY_UTILISATEUR_USERNAME + " TEXT PRIMARY KEY , " +
KEY_UTILISATEUR_PASSWORD + " TEXT NOT NULL" + ");"
);
nb.execSQL("CREATE TABLE " + TABLE_JEU + " (" +
KEY_JEU_ID_JEU + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_JEU_NOM_JEU + " TEXT NOT NULL UNIQUE," +
KEY_JEU_COMMENTAIRES + " TEXT" +
");"
);
}
#Override
public void onUpgrade(android.database.sqlite.SQLiteDatabase db,
int oldversion, int newversion) {
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIE);
// onCreate(db);
}
}
public Database2(Context c){
ourContext = c;
}
public Database2 open() throws SQLException {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() throws SQLException{
ourHelper.close();
}
public long createCategorie(String name) {
ContentValues cv = new ContentValues();
cv.put(KEY_CATEGORIE_NOM_CATEGORIE, name);
return ourDatabase.insert(TABLE_CATEGORIE, null, cv);
}
public String getCategorieData(){
String result = "";
String[] columns = new String[] {KEY_CATEGORIE_ID_CATEGORIE, KEY_CATEGORIE_NOM_CATEGORIE};
Cursor c = ourDatabase.query(TABLE_CATEGORIE, columns,null, null, null, null, null);
int id = c.getColumnIndex(KEY_CATEGORIE_ID_CATEGORIE);
int name = c.getColumnIndex(KEY_CATEGORIE_NOM_CATEGORIE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result += c.getString(id) + " " + c.getString(name) + "\n";
}
return result;
}
}
`
Event Manager :
package com.jeux;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Jeuxdemots2Activity extends Activity implements OnClickListener {
Button sqlUpdate, sqlView;
EditText nameText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sqlUpdate = (Button) findViewById(R.id.updatebutton);
sqlView = (Button) findViewById(R.id.afficherbutton);
nameText = (EditText) findViewById(R.id.nametext);
sqlUpdate.setOnClickListener(this);
sqlView.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.updatebutton:
try{
String name = nameText.getText().toString();
Database2 entry = new Database2(Jeuxdemots2Activity.this);
entry.open();
entry.createCategorie(name);
entry.close();
}catch (Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
}
break;
case R.id.afficherbutton:
Intent i = new Intent("android.intent.action.SQLVIEW");
startActivity(i);
break;
}
}
}
`
view #3 :
package com.jeux;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLview extends Activity {
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.afficherlayout);
TextView tv = (TextView) findViewById(R.id.affichertextview);
Database2 info = new Database2(this);
info.open();
String data = info.getCategorieData();
info.close();
tv.setText(data);
}
}
When you close/re-open your virtual device, does it look like it's doing a full bootup every time (Shiny Android word, swipe to unlock screen, etc)? If so, it could be re-initializing everything everytime you run your application. If so, you're application and database are no longer on the device, so the data wouldn't persist.
When you create your emulator are you checking the "Snapshot" option? I believe that saves the state of your device into a file so that when you close/re-open your emulator, it's able to resume from the same point.