Update method not saving changes Sqlite Database (Android Studio) - java

I'm trying to complete my update method on my database, but I'm not getting the results.
My app doesn't show any error, I can access the object I want to edit, I'm able to change the data, but the changes are not saved.
I've tried this code in another app and worked ok, but now I'm not able to save my changes when I edit the data I want to alter.
Can anyone please give a hand?
My Database:
package com.myapplication.umdocededaisy;
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<>();
private final Context context;
private static final String DATABASE_NAME = "BancoDoceDaisy.db";
private static final int DATABASE_VERSION = 4;
//Estruturas das Tabelas do banco de dados:
//Tabela dos produtos - materia prima:
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";
//------------------------------------------------------
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);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUTO);
onCreate(db);
}
void addMateriaPrima(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();
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_PRODUTO;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query,null);
}
return cursor;
}
public List<MateriaPrima> buscaProduto() {
String columns[] = {COLUMN_CODIGO, COLUMN_PRODUTO, COLUMN_VALOR, COLUMN_QTD, COLUMN_TIPO};
SQLiteDatabase db = getReadableDatabase();
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;
}
void updateData(MateriaPrima materiaPrima) {
SQLiteDatabase db = 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.update(TABLE_PRODUTO, cv, " codigo=?", new String[]{String.valueOf(materiaPrima.getCodigo())});
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 materiaPrima) {
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_PRODUTO, COLUMN_CODIGO + " codigo", new String[]{String.valueOf(materiaPrima)});
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 deleteAllData() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUTO);
db.close();
}
}
My Update Activity
package com.myapplication.umdocededaisy;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateActivity extends AppCompatActivity {
EditText editCodigo2, editProduto2, editValor2, editQuantidade2, editTipo2;
Button btnUpdate, btnDelete;
String codigo, produto, valor, quantidade, tipo;
InputMethodManager inputManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
//Declarações objetos:
editCodigo2 = findViewById(R.id.editCodigo2);
editProduto2 = findViewById(R.id.editProduto2);
editValor2 = findViewById(R.id.editValor2);
editQuantidade2 = findViewById(R.id.editQuantidade2);
editTipo2 = findViewById(R.id.editTipo2);
btnUpdate = findViewById(R.id.btnUpdate);
btnDelete = findViewById(R.id.btnDelete);
inputManager = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
getAndSetIntentData();
ActionBar ab = getSupportActionBar();
if(ab != null){
ab.setTitle(produto);
}
btnUpdate.setOnClickListener(v -> {
MateriaPrima materiaPrima = new MateriaPrima();
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
produto = editProduto2.getText().toString().trim();
valor = editValor2.getText().toString().trim();
quantidade = editQuantidade2.getText().toString().trim();
tipo = editTipo2.getText().toString().trim();
myDB.updateData(materiaPrima);
inputManager.hideSoftInputFromWindow(btnUpdate.getWindowToken(), 0);
recreate();
});
btnDelete.setOnClickListener(v -> confirmDeleteDialog());
}
void getAndSetIntentData() {
if (getIntent().hasExtra("codigo") && getIntent().hasExtra("produto") && getIntent().hasExtra("valor") &&
getIntent().hasExtra("quantidade") && getIntent().hasExtra("tipo")){
//Getting data:
codigo = getIntent().getStringExtra("codigo");
produto = getIntent().getStringExtra("produto");
valor = getIntent().getStringExtra("valor");
quantidade = getIntent().getStringExtra("quantidade");
tipo = getIntent().getStringExtra("tipo");
//Setting data:
editCodigo2.setText(codigo);
editProduto2.setText(produto);
editValor2.setText(valor);
editQuantidade2.setText(quantidade);
editTipo2.setText(tipo);
}else{
Toast.makeText(this, R.string.strData0, Toast.LENGTH_SHORT).show();
}
}
void confirmDeleteDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.strMsgDelete) + " " + produto);
builder.setMessage(getString(R.string.strMsgDelete ) + " " + produto + " ?");
builder.setPositiveButton(getString(R.string.strYes), (dialog, which) -> {
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
myDB.deleteOneRow(codigo);
finish();
});
builder.setNegativeButton(getString(R.string.strNo), (dialog, which) -> {
});
builder.create().show();
}
}

Maybe you think that the table is not updated because you see the toast with the message that the update failed.
But, the condition that you check in order to show the correct message is not correct.
The method update() returns either the number of the rows affected (updated) or 0 if the update failed.
It never returns -1.
Change your code like this:
if (result == 0) {
Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
}
Also, in the listener of btnUpdate you define a MateriaPrima object which you pass to updateData() without setting its properties.
Where do you get the Codigo property from?
Change to this:
btnUpdate.setOnClickListener(v -> {
MateriaPrima materiaPrima = new MateriaPrima();
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
materiaPrima.setCodigo(?????); // you must set this property
materiaPrima.setProduto(editProduto2.getText().toString().trim());
materiaPrima.setValor(editValor2.getText().toString().trim());
materiaPrima.setQuantidade(editQuantidade2.getText().toString().trim());
materiaPrima.setTipo(editTipo2.getText().toString().trim());
myDB.updateData(materiaPrima);
inputManager.hideSoftInputFromWindow(btnUpdate.getWindowToken(), 0);
recreate();
});

I was able to correct the error by rewriting my update method:
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();
}
Thanks for all the help

Related

Generating a file to store a receipt in android studios

Hello I am new to android studios. I am working on an airline reservation project. One of the requirements of the project is to generate a receipt that is stored on an external file every time a customer makes a payment. I have tried looking around trying to figure out how one might accomplish this with no success. In the app I am using SQLite as a database where every user is assigned a balance once they create an account.
Here is my DBHelper class:
package com.example.shashank.fffffffffffffffffffffffffff;
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 androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "Login.db";
public static final String FLIGHTS = "FLIGHTS";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_DESTINATION = "DESTINATION";
public static final String COLUMN_PRICE = "PRICE";
public static final String COLUMN_DEPARTURE_TIME = "DEPARTURE_TIME";
public static final String COLUMN_ARRIVAL_TIME = "ARRIVAL_TIME";
public static final String COLUMN_DURATION = "DURATION";
public static final String COLUMN_AVAILABLE_SEATS = "AVAILABLE_SEATS";
public static final String USERS = "users";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String BALANCE = "balance";
public static final String BOOKING = "booking";
public DBHelper(Context context) {
super(context, "Login.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase MyDB) {
String createTable1 = ("create Table " + USERS + "(" + USERNAME + " TEXT primary key, " + PASSWORD + " TEXT, " + EMAIL + " TEXT UNIQUE, " + BALANCE + " REAL, " + BOOKING + " INTEGER)");
MyDB.execSQL(createTable1);
MyDB.execSQL("CREATE TABLE " + FLIGHTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_DESTINATION + " TEXT, " + COLUMN_PRICE + " REAL, " + COLUMN_DEPARTURE_TIME + " TEXT, " + COLUMN_ARRIVAL_TIME + " TEXT, " + COLUMN_DURATION + " TEXT, " + COLUMN_AVAILABLE_SEATS + " INTEGER)");
ContentValues insertValues = new ContentValues();
insertValues.put(COLUMN_DESTINATION, "Cape Town");
insertValues.put(COLUMN_PRICE, 2000);
insertValues.put(COLUMN_DEPARTURE_TIME, "1200");
insertValues.put(COLUMN_ARRIVAL_TIME, "1400");
insertValues.put(COLUMN_DURATION, "2");
insertValues.put(COLUMN_AVAILABLE_SEATS, 10);
MyDB.insert(FLIGHTS, null, insertValues);
ContentValues insertValues2 = new ContentValues();
insertValues2.put(COLUMN_DESTINATION, "Johannesburg");
insertValues2.put(COLUMN_PRICE, 1000);
insertValues2.put(COLUMN_DEPARTURE_TIME, "1400");
insertValues2.put(COLUMN_ARRIVAL_TIME, "1600");
insertValues2.put(COLUMN_DURATION, "2");
insertValues2.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues2);
ContentValues insertValues3 = new ContentValues();
insertValues3.put(COLUMN_DESTINATION, "Cape Town");
insertValues3.put(COLUMN_PRICE, 500);
insertValues3.put(COLUMN_DEPARTURE_TIME, "1200");
insertValues3.put(COLUMN_ARRIVAL_TIME, "1400");
insertValues3.put(COLUMN_DURATION, "2");
insertValues3.put(COLUMN_AVAILABLE_SEATS, 0);
MyDB.insert(FLIGHTS, null, insertValues3);
}
#Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
MyDB.execSQL("drop Table if exists " + USERS);
MyDB.execSQL("drop Table if exists " + FLIGHTS);
onCreate(MyDB);
}
public Boolean insertData(String username, String password, String email, Double balance){
SQLiteDatabase MyDB = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(USERNAME, username);
contentValues.put(PASSWORD, password);
contentValues.put(EMAIL, email);
contentValues.put(BALANCE, balance);
long result = MyDB.insert(USERS, null, contentValues);
if(result==-1) return false;
else
return true;
}
public Boolean checkusername(String username) {
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from " + USERS + " where " + USERNAME + " = ?", new String[]{username});
if (cursor.getCount() > 0)
return true;
else
return false;
}
public Boolean checkusernamepassword(String username, String password){
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from " + USERS + " where " + USERNAME + " = ? and " + PASSWORD + " = ?", new String[] {username,password});
if(cursor.getCount()>0)
return true;
else
return false;
}
public List<FlightsModel> getEveryone(){
List<FlightsModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + FLIGHTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
do {
int id = cursor.getInt(0);
String destination = cursor.getString(1);
double price = cursor.getDouble(2);
String departure = cursor.getString(3);
String arrival = cursor.getString(4);
String duration = cursor.getString(5);
int space = cursor.getInt(6);
FlightsModel newFlight = new FlightsModel(id, destination, price, departure, arrival, duration, space);
returnList.add(newFlight);
}while (cursor.moveToNext());
}
else{
}
cursor.close();
db.close();
return returnList;
}
#SuppressLint("Range") // suppress Bug/issue with getColumnIndex
public FlightsModel getFlightById(int id) {
FlightsModel rv;
SQLiteDatabase db = this.getWritableDatabase();
// Uses the query convenience method rather than raw query
Cursor csr = db.query(FLIGHTS,null,COLUMN_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = new FlightsModel(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_DESTINATION)),
csr.getDouble(csr.getColumnIndex(COLUMN_PRICE)),
csr.getString(csr.getColumnIndex(COLUMN_DEPARTURE_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_ARRIVAL_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_DURATION)),
csr.getInt(csr.getColumnIndex(COLUMN_AVAILABLE_SEATS))
);
} else {
rv = new FlightsModel();
}
csr.close();
// No need to close the database (inefficient to keep opening and closing db)
return rv;
}
#SuppressLint("Range")
public UsersModel getPasswordByName(String name){
UsersModel rv;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cr = db.query(USERS, null, USERNAME+"=?", new String[]{name}, null, null, null);
if (cr.moveToFirst()) {
rv = new UsersModel(
cr.getString(cr.getColumnIndex(USERNAME)),
cr.getString(cr.getColumnIndex(PASSWORD)),
cr.getString(cr.getColumnIndex(EMAIL)),
cr.getDouble(cr.getColumnIndex(BALANCE)),
cr.getInt(cr.getColumnIndex(BOOKING))
);
} else rv = new UsersModel();
cr.close();
return rv;
}
public int setBookingByUserName(int bookingAmount, String userName) {
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public double makingPayment(double balance, String userName){
ContentValues cv = new ContentValues();
cv.put(BALANCE,balance);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public int setAvailableSeatsAfterPayment(int seats, int flightID){
ContentValues cv = new ContentValues();
cv.put(COLUMN_AVAILABLE_SEATS,seats);
return this.getWritableDatabase().update(FLIGHTS,cv,COLUMN_ID+"=?",new String[]{String.valueOf(flightID)});
}
public int cancelBooking(int bookingAmount, String userName){
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{String.valueOf(userName)});
}
}
The making payment method is used to update the database with a new balance when a customer books for a flight.
Here is the booking activity:
package com.example.shashank.fffffffffffffffffffffffffff;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class BookingActivity extends AppCompatActivity {
TextView textView;
TextView departure, arrival, duration, price, seats;
DBHelper dbHelper; //<<<<< ADDED
Button book, accountBtn;
FlightsModel flightsModel; //<<<<< ADDED
UsersModel userModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
dbHelper = new DBHelper(this); //<<<<< ADDED
textView = findViewById(R.id.textView);
departure = findViewById(R.id.departure);
arrival = findViewById(R.id.arrival);
duration = findViewById(R.id.duration);
price = findViewById(R.id.price);
seats = findViewById(R.id.seats);
book = findViewById(R.id.button2);
accountBtn = findViewById(R.id.accountBtn);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Intent nameIntent = getIntent();
String name = nameIntent.getStringExtra("userName");
flightsModel = dbHelper.getFlightById(intValue + 1);
intValue = intValue + 1;
textView.setText(flightsModel.getDestination());
departure.setText(flightsModel.getDeparture_time());
arrival.setText(flightsModel.getArrival_time());
duration.setText(flightsModel.getDuration());
price.setText("R" + Double.toString(flightsModel.getPrice()));
seats.setText(Integer.toString(flightsModel.getAvailable_space()));
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int intValue, seats;
Intent mIntent = getIntent();
intValue = mIntent.getIntExtra("intVariableName", 0);
intValue = intValue + 1;
dbHelper = new DBHelper(BookingActivity.this);
flightsModel = dbHelper.getFlightById(intValue);
double price;
price = flightsModel.getPrice();
userModel = dbHelper.getPasswordByName(name);
double balance;
balance = userModel.getBalance();
String name = nameIntent.getStringExtra("userName");
seats = flightsModel.getAvailable_space();
if(seats == 0){
Toast.makeText(BookingActivity.this, "Booking unsuccessful, no available seats", Toast.LENGTH_SHORT).show();
}else{
if(price <= balance){
dbHelper.setBookingByUserName(intValue, name);
Toast.makeText(BookingActivity.this, "Payment successful, booking has been made", Toast.LENGTH_SHORT).show();
double newBalance;
newBalance = balance - price;
dbHelper.makingPayment(newBalance, name);
seats = seats - 1;
dbHelper.setAvailableSeatsAfterPayment(seats, intValue);
}else{
Toast.makeText(BookingActivity.this, "Payment unsuccessful, not enough funds", Toast.LENGTH_SHORT).show();
}
}
}
});
accountBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BookingActivity.this, AccountActivity.class);
intent.putExtra("userName", name);
startActivity(intent);
}
});
}
}
So once a customer makes his booking a receipt file needs to be generated, say for instance with the flight details, time, date and the price of the flight. Any help will be appreciated thank you.
The following is an example that saves a file in the App's Files directory in a sub directory of receipts. The filename being composed of values e.g.
Fred-Cape Town-1200-1400
Stored at /data/user/0/the_package_name/files/receipts/Fred-Cape Town-1200-1400
The file itself, in the example containing :-
Fred
Cape Town
1200
1400
Some supportive methods added to DBHelper :-
public UsersModel getUsersModelByName(String userName) {
UsersModel rv = new UsersModel();
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(USERS,null,USERNAME+"=?", new String[]{userName},null,null,null);
if (csr.moveToFirst()) {
rv = new UsersModel(
csr.getString(csr.getColumnIndex(USERNAME)),
csr.getString(csr.getColumnIndex(PASSWORD)),
csr.getString(csr.getColumnIndex(EMAIL)),
csr.getDouble(csr.getColumnIndex(BALANCE)),
csr.getInt(csr.getColumnIndex(BOOKING))
);
}
csr.close();
return rv;
}
public boolean makeBooking(String userName, int bookingId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingId);
return db.update(USERS,cv,USERNAME + "=?", new String[]{userName}) > 0;
}
Now the makeBookReceiptFile method, also placed in the DBHelper class:-
public String makeBookReceiptFile(String userName, Context context) {
String rcpts_directory = "receipts";
String rv = "";
SQLiteDatabase db = this.getWritableDatabase();
UsersModel currentUser = getUsersModelByName(userName);
FlightsModel currentFlightsModel = new FlightsModel();
if (currentUser.booking > 0) {
currentFlightsModel = getFlightById(currentUser.booking);
if (currentFlightsModel.id < 1) {
rv = "INVALID - unable to extract booking for id " + currentUser.booking;
}
} else {
rv = "INVALID - unable to extract user who's name is " + userName;
}
if (rv.length() > 0) return rv;
String rcpt_filename =
currentUser.username + "-" +
currentFlightsModel.destination + "-" +
currentFlightsModel.departure + "-" +
currentFlightsModel.arrival
;
File rcpt = new File(context.getFilesDir().getPath() + File.separatorChar + rcpts_directory + File.separatorChar + rcpt_filename);
rcpt.getParentFile().mkdirs();
try {
FileWriter fw = new FileWriter(rcpt);
fw.write(userName +
"\n" + currentFlightsModel.destination+
"\n" + currentFlightsModel.departure +
"\n" + currentFlightsModel.arrival
);
fw.flush();
fw.close();
rv = rcpt.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
rv = "IOERROR - " + e.getMessage();
}
return rv;
}
First it retrieves the UsersModel according to the UserName, the it retrieves the FlightsModel according to the booking id.
If either was not obtained then it returns a String starting with INVALID
It then obtains the Files directory via the Context.
Generates the path for the file.
Makes any missing directories.
Write data to the file, flushes and closes the file returning the path or if there was an io error the error message.
The above was tested using :-
db = new DBHelper(this);
db.insertData("Fred","password","fed#email",0.00);
UsersModel fred = db.getUsersModelByName("Fred");
db.makeBooking(fred.username,1);
Log.d("RESULTINFO",db.makeBookReceiptFile("Fred",this));
Resulting in (via Device Explorer) :-
If you have issues with the location of the file then you will have to read https://developer.android.com/training/data-storage/

Android Studio SQLite table duplicates everytime I click view button

I have added 2 entries in the database and if I click the view button for the first time, it normally shows the 2 entries. However, if I click the view button again, there will be 4 entries and then 6, 8, 10 etc. Even though there are 4,6,8,10,12 entries if I view it, I used a getCount command and it showed 2 which is correct. So the database is correct so the bug here is somewhere in the viewbtn but I don't know what it is. How do I fix this?
MainActivity.java
viewbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
res = myDb.getAllData();
if(res.getCount()==0){ //when there is no data show message..error message is depend on "showMessage"method
//show message
showMessage("Oops!","No entry, add an entry to see the list.");
return;
}
while(res.moveToNext()) {
// read and collect data in database in column
buffer.append("\n\n");
buffer.append("Date: " + res.getString(0) + "\n");
buffer.append("Time: " + res.getString(1) + "\n");
buffer.append("Name: " + res.getString(2) + "\n");
buffer.append("Surname: " + res.getString(3) + "\n");
buffer.append("ID: " + res.getString(4) + "\n");
buffer.append("--------------------------------------------------------------");
}
//show all data
showMessage("Entries",buffer.toString()); //show all data in list.list is depnd on "showMessage"method
}
});
DatabaseHelper.java
package com.example.AppDraft3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DatabaseHelper extends SQLiteOpenHelper {
private Context context;
public static final String DATABASE_NAME="Attendance.db";
public static final String TABLE_NAME="Attendance_table";
public static final String COL_1="DATE";
public static final String COL_2="TIME";
public static final String COL_3="NAME";
public static final String COL_4="SURNAME";
public static final String COL_5="ID";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (DATE TEXT,TIME TEXT,NAME TEXT,SURNAME TEXT,ID INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
}
public Boolean verifyData(String TABLE_NAME, String id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE id = '" + id + "'";
Cursor res = db.rawQuery(query, null);
if (res.moveToFirst()){
res.close();
return true;
} else {
res.close();
return false;
}
}
public long insertData(String name,String surname,String id){
if (verifyData(TABLE_NAME, id)){
return 0;
}
// set the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
Date time = new Date();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, dateFormat.format(date));
contentValues.put(COL_2, timeFormat.format(time));
contentValues.put(COL_3, name);
contentValues.put(COL_4, surname);
contentValues.put(COL_5, id);
long result=db.insert(TABLE_NAME, null, contentValues);
return result;
}
public boolean verifyExist(String id){
if (verifyData(TABLE_NAME, id)){
return true;
} else {
return false;
}
}
public Cursor getAllData(){
//get all data
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select*from "+TABLE_NAME, null);
return res;
}
public Integer deleteData(){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME,null,null);
}
public Boolean singleDeleteData(String id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res =db.rawQuery("Select * from " +TABLE_NAME+ " where id = ?", new String[] {id});
if (res.getCount() > 0) {
long resultDel = db.delete(TABLE_NAME, "id=?", new String[] {id});
if (resultDel == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
}
The buffer needs to be empties otherwise you are just appending to it. I am assuming this is a StringBuffer
public void onClick(View v) {
res = myDb.getAllData();
buffer = new StringBuffer();
:
:
}

Can't find SQL column in android project

I have two classes:
Database class:
package com.qstra.soamazingtodoapp;
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 DBAdapter {
private static final String TAG = "DBAdapter"; // used for logging database
// version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_TASK = "task";
public static final String KEY_DATE = "date";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_TASK,
KEY_DATE, KEY_HOUR, KEY_MINUTE };
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
public static final int COL_HOUR = 3;
public static final int COL_MINUTE = 4;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 2; // The version number must be
// incremented each time a
// change to DB structure
// occurs.
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT" + KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT" + ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String task, String date, String hour, String minute) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String task, String date, String hour, String minute) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TASK, task);
newValues.put(KEY_DATE, date);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_MINUTE, minute);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity class:
package com.qstra.soamazingtodoapp;
import com.qstratwo.soamazingtodoapp.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
Time today = new Time(Time.getCurrentTimezone());
DBAdapter myDb;
EditText etTasks;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
String string_hour_x, string_minute_x="None";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTasks = (EditText) findViewById(R.id.editText1);
openDB();
listViewItemClick();
listViewItemLongClick();
populateListView();
// setNotification();
}
#Override
protected Dialog onCreateDialog(int idD){
if (idD== DIALOG_ID){
return new TimePickerDialog(MainActivity.this, kTimePickerListener, hour_x,minute_x, false);
}
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x=hourOfDay;
minute_x=minute;
string_hour_x = Integer.toString(hour_x);
string_minute_x = Integer.toString(minute_x);
Toast.makeText(MainActivity.this, hour_x+" : "+ minute_x,Toast.LENGTH_LONG).show();
}
};
public void setNotification(View v) {
showDialog(DIALOG_ID);
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_AddTask (View v) {
today.setToNow();
String timestamp = today.format("%Y-%m-%d %H:%m:%s");
if(!TextUtils.isEmpty(etTasks.getText().toString())) {
myDb.insertRow(etTasks.getText().toString(),timestamp,string_hour_x, string_minute_x);
}
populateListView();
}
private void populateListView() {
Cursor cursor = myDb.getAllRows();
String[] fromFieldNames=new String[] {
DBAdapter.KEY_ROWID, DBAdapter.KEY_TASK };
int[] toViewIDs = new int[] {
R.id.textViewItemNumber, R.id.textViewItemTasks};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setAdapter(myCursorAdapter);
}
private void updateTask(long id){
Cursor cursor = myDb.getRow(id);
if (cursor.moveToFirst()){
String task = etTasks.getText().toString(); // POBIERANIE Z TEXTFIELD
today.setToNow();
String date = today.format("%Y-%m-%d %H:%m");
// String string_minute_x= Integer.toString(minute_x);
// String string_houte_x=Integer.toString(hour_x);
myDb.updateRow(id, task, date, string_hour_x, string_minute_x );
}
cursor.close();
}public void onClick_DeleteTasks(View v) {
myDb.deleteAll();
populateListView();
}
public void onClick_AppClose(View v) {
moveTaskToBack(true);
MainActivity.this.finish();
}
public void listViewItemLongClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
myDb.deleteRow(id);
populateListView();
return false;
}
});
}
private void listViewItemClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
updateTask(id);
populateListView();
displayToast(id);
}
});
}
private void displayToast(long id){
Cursor cursor = myDb.getRow(id);
if(cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String task = cursor.getString(DBAdapter.COL_TASK);
String date = cursor.getString(DBAdapter.COL_DATE);
String message = "ID: " + idDB + "\n" + "Task: " + task + "\n" + "Date: " + date;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
}
(getting id and text from texfield to database works fine but..)
I'm trying to get hour and minutes values from TimePickerDialog and insert in to database but it seems not working.
Screen shot from log cat:
Why can't it see column named 'hour'?
Add commas in your statement to create database
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT," + KEY_HOUR + " TEXT,"
+ KEY_MINUTE + " TEXT" + ")";

ContentResolver.notifyChange not working

I wanted to play with a ContentProvider example but I ran into an issue I can't seem to solve.
This example consists of an Activity:
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity
{
final String LOG_TAG = "myLogs";
final Uri CONTACT_URI = Uri.parse("content://zulfigarov.com.trainingprj.MyContactsProvider/contacts");
final String CONTACT_NAME = "name";
final String CONTACT_EMAIL = "email";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor cursor = getContentResolver().query(CONTACT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {"name", "email"};
int[] to = {android.R.id.text1, android.R.id.text2};
SimpleCursorAdapter adapter
= new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to, 0);
ListView lvContact = (ListView)findViewById(R.id.lvContacts);
lvContact.setAdapter(adapter);
}
public void onClickInsert(View view)
{
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, "name 4");
cv.put(CONTACT_EMAIL, "email 4");
Uri newUri = getContentResolver().insert(CONTACT_URI, cv);
Log.d(LOG_TAG, "insert, result Uri: " + newUri.toString());
}
public void onClickUpdate(View view)
{
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, "name 5");
cv.put(CONTACT_EMAIL, "email 5");
Uri uri = ContentUris.withAppendedId(CONTACT_URI, 2);
int cnt = getContentResolver().update(uri, cv, null, null);
Log.d(LOG_TAG, "update, count = " + cnt);
}
public void onClickDelete(View view)
{
Uri uri = ContentUris.withAppendedId(CONTACT_URI, 3);
int cnt = getContentResolver().delete(uri, null, null);
Log.d(LOG_TAG, "delete, count = " + cnt);
}
public void onClickError(View view)
{
Uri uri = Uri.parse("content://zulfigarov.com.trainingprj.MyContentProvider/phones");
try
{
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
}
catch (Exception ex)
{
Log.d(LOG_TAG, "Error: " + ex.getClass() + ", " + ex.getMessage());
}
}
}
and a ContentProvider:
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class MyContactsProvider extends ContentProvider
{
final String LOG_TAG = "myLogs";
static final String DB_NAME = "mydb";
static final int DB_VERSION = 1;
static final String CONTACT_TABLE = "contacts";
static final String CONTACT_ID = "_id";
static final String CONTACT_NAME = "name";
static final String CONTACT_EMAIL = "email";
static final String DB_CREATE = "CREATE TABLE " + CONTACT_TABLE + "("
+ CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CONTACT_NAME + " TEXT, "
+ CONTACT_EMAIL + " TEXT" + ");";
static final String AUTHORITY = "zulfigarov.com.trainingprj.MyContactsProvider";
static final String CONTACT_PATH = "contacts";
public static final Uri CONTACT_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + CONTACT_PATH);
static final String CONTACT_CONTENT_TYPE = "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + CONTACT_PATH;
static final String CONTACT_CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd." + AUTHORITY + "." + CONTACT_PATH;
static final int URI_CONTACTS = 1;
static final int URI_CONTACTS_ID = 2;
private static final UriMatcher uriMatcher;
static
{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, CONTACT_PATH, URI_CONTACTS);
uriMatcher.addURI(AUTHORITY, CONTACT_PATH + "/#", URI_CONTACTS_ID);
}
DBHelper dbHelper;
SQLiteDatabase db;
#Override
public boolean onCreate()
{
Log.d(LOG_TAG, "onCreate provider");
dbHelper = new DBHelper(getContext());
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
Log.d(LOG_TAG,"query, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
Log.d(LOG_TAG, "URI_CONTACTS");
if(TextUtils.isEmpty(sortOrder))
{
sortOrder = CONTACT_NAME + " ASC";
}
break;
case URI_CONTACTS_ID:
String id = uri.getLastPathSegment();
Log.d(LOG_TAG, "URI_CONTACTS_ID");
if (TextUtils.isEmpty(selection))
selection = CONTACT_ID + " = " + id;
else
selection = selection + " AND " + CONTACT_ID + " = " + id;
break;
default:
throw new IllegalArgumentException("Wrong URI: " + uri);
}
db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(CONTACT_TABLE, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),CONTACT_CONTENT_URI);
return cursor;
}
#Override
public String getType(Uri uri)
{
Log.d(LOG_TAG, "getTYpe, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
return CONTACT_CONTENT_TYPE;
case URI_CONTACTS_ID:
return CONTACT_CONTENT_ITEM_TYPE;
}
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values)
{
Log.d(LOG_TAG,"insert, " + uri.toString());
if(uriMatcher.match(uri) != URI_CONTACTS)
throw new IllegalArgumentException("Wrong URI: " + uri);
db = dbHelper.getWritableDatabase();
long rowID = db.insert(CONTACT_TABLE, null, values);
Uri resultUri = ContentUris.withAppendedId(CONTACT_CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(resultUri, null);
return resultUri;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs)
{
Log.d(LOG_TAG,"delete, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
Log.d(LOG_TAG,"URI_CONTACTS");
break;
case URI_CONTACTS_ID:
String id = uri.getLastPathSegment();
Log.d(LOG_TAG,"URI_CONTACTS_ID, " + id);
if(TextUtils.isEmpty(selection))
{
selection = CONTACT_ID + " = " + id;
}
else
{
selection = selection + " AND " + CONTACT_ID + " = " + id;
}
break;
default:
throw new IllegalArgumentException("Wrong URI: " + uri);
}
db = dbHelper.getWritableDatabase();
int cnt = db.delete(CONTACT_TABLE, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return cnt;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
{
Log.d(LOG_TAG,"update, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
Log.d(LOG_TAG,"URI_CONTACTS");
break;
case URI_CONTACTS_ID:
String id = uri.getLastPathSegment();
Log.d(LOG_TAG, "URI_CONTACTS_ID");
if(TextUtils.isEmpty(selection))
{
selection = CONTACT_ID;
}
else
{
selection = selection + " AND " + CONTACT_ID + " = " + id;
}
break;
default:
throw new IllegalArgumentException("Wrong URI: " + uri);
}
db = dbHelper.getWritableDatabase();
int cnt = db.update(CONTACT_TABLE, values, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri,null);
return cnt;
}
private class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE);
ContentValues cv = new ContentValues();
for (int i = 1; i <= 3; i++)
{
cv.put(CONTACT_NAME, "name " + i);
cv.put(CONTACT_EMAIL, "email " + i);
db.insert(CONTACT_TABLE, null, cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
}
The touble is that when I click on the buttons (firing onClickInsert, onClickUpdate etc. methods in MainActivity) it updates the data in database but doesn't update the ListView on an activity. Looks like
getContext().getContentResolver().notifyChange(resultUri, null);
is not working properly. So I can't find where i'm wrong.
Use CursorLoaders to load the data and populate the ListView.
http://developer.android.com/reference/android/content/CursorLoader.html
Then use getContext().getContentResolver().notifyChange(resultUri, null); when you insert, update or delete!
Without CursorLoaders you will have to use ContentObservers
So, although DB is updated in background and you are using notifyChange() but no one is listening to that!
You should be calling adapter.notifyDataSetChanged() (after the onClickInsert) in order to make your ListView notice about the change.

cursor.moveToFirst seems to be skipped

I'm new to Java and just tried to make a database. I managed to make a DB and all but when I want to read the values it seems to get an error.
This is my code for my settings activity (which asks for setting values and add them in the DB on a specific ID)
public class Settings extends Activity{
Button Save;
static Switch SwitchCalculations;
public static String bool;
public static List<Integer> list_id = new ArrayList<Integer>();
public static List<String> list_idname = new ArrayList<String>();
public static List<String> list_kind = new ArrayList<String>();
public static List<String> list_value = new ArrayList<String>();
static Integer[] arr_id;
static String[] arr_idname;
static String[] arr_kind;
static String[] arr_value;
public static final String TAG = "Settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Save = (Button) findViewById(R.id.btnSave);
SwitchCalculations = (Switch) findViewById(R.id.switchCalcOnOff);
readData();
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
writeData();
//Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT).show();
readData();
Save.setText("Opgeslagen");
}
});
}
public void writeData() {
int id = 1;
String idname = "switchCalcOnOff";
String kind = "switch";
boolean val = SwitchCalculations.isChecked();
String value = new Boolean(val).toString();
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dbh.C_ID, id);
cv.put(dbh.C_IDNAME, idname);
cv.put(dbh.C_KIND, kind);
cv.put(dbh.C_VALUE, value);
if (dbh.C_ID.isEmpty() == true) {
db.insert(dbh.TABLE, null, cv);
Log.d(TAG, "Insert: Data has been saved.");
} else if (dbh.C_ID.isEmpty() == false) {
db.update(dbh.TABLE, cv, "n_id='1'", null);
Log.d(TAG, "Update: Data has been saved.");
} else {
Log.d(TAG, "gefaald");
}
db.close();
}
public void readData() {
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
List<String> list_value = new ArrayList<String>();
String[] arr_value;
list_value.clear();
Cursor cursor = db.rawQuery("SELECT " + dbh.C_VALUE + " FROM " + dbh.TABLE + ";", null);
if (cursor.moveToFirst()) {
do {
list_value.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()){
cursor.close();
}
db.close();
arr_value = new String[list_value.size()];
for (int i = 0; i < list_value.size(); i++){
arr_value[i] = list_value.get(i);
}
}
}
Then I have my dbHelper activity see below:
package com.amd.nutrixilium;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbHelper_Settings extends SQLiteOpenHelper{
private static final String TAG="dbHelper_Settings";
public static final String DB_NAME = "settings.db";
public static final int DB_VERSION = 10;
public final String TABLE = "settings";
public final String C_ID = "n_id"; // Special for id
public final String C_IDNAME = "n_idname";
public final String C_KIND = "n_kind";
public final String C_VALUE = "n_value";
Context context;
public dbHelper_Settings(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
// oncreate wordt maar 1malig uitgevoerd per user voor aanmaken van database
#Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format("create table %s (%s int primary key, %s TEXT, %s TEXT, %s TEXT)", TABLE, C_ID, C_IDNAME, C_KIND, C_VALUE);
Log.d(TAG, "onCreate sql: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE); // wist een oudere database versie
Log.d(TAG, "onUpgrate dropped table " + TABLE);
this.onCreate(db);
}
}
And the weird thing is I don't get any error messages here.
But I used Log.d(TAG, text) to check where the script is being skipped and that is at cursor.moveToFirst().
So can anyone help me with this problem?
Here, contrary to what you seem to expect, you actually check that a text constant is not empty:
if (dbh.C_ID.isEmpty() == true) {
It isn't : it always contains "n_id"
I think your intent was to find a record with that id and, depending on the result, either insert or update.
You should do just that: attempt a select via the helper, then insert or update as in the code above.
Edit:
Add to your helper something like this:
public boolean someRowsExist(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("select EXISTS ( select 1 from " + TABLE + " )", new String[] {});
cursor.moveToFirst();
boolean exists = (cursor.getInt(0) == 1);
cursor.close();
return exists;
}
And use it to check if you have any rows in the DB:
if (dbh.someRowsExist(db)) { // instead of (dbh.C_ID.isEmpty() == true) {
Looks like you're having trouble debugging your query. Android provides a handy method DatabaseUtils.dumpCursorToString() that formats the entire Cursor into a String. You can then output the dump to LogCat and see if any rows were actually skipped.

Categories

Resources