Picasso is loading URL but no picture is shown - java

I have one of the weirdest problems I've had so far. I am creating an app which sends information about books and authors through different activities. I am sending them with the help of intents. My problem is within the authors section. I am sending name, age and the picture. Name and age are send successfully and to my knowledge with the debugger, the image is sent successfully as well. However, Picasso refuses to load it in ImageView. There are no errors shown and I have no idea what is going on. Here is some code.
This function resets the information in my database:
public void resetAuthor()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_AUTHORS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_AUTHORS + "'");
addBegginingInfoAuthor("J.K.Rowling", 54, "https://www.biographyonline.net/wp-content/uploads/2014/05/jk-rowling4.jpg");
addBegginingInfoAuthor("J.R.R. Tolken", 81, "https://www.biography.com/.image/t_share/MTE5NTU2MzE2Mzg4MzYxNzM5/jrr-tolkien-9508428-1-402.jpg");
addBegginingInfoAuthor("Arthur Conan Doyle", 71, "https://upload.wikimedia.org/wikipedia/commons/b/bd/Arthur_Conan_Doyle_by_Walter_Benington%2C_1914.png");
}
AuthorAdapter class. This is the adapter for my recycler view which displays details about the author. It is also where I start up the intent to move to the other activity:
#Override
public void onBindViewHolder(#NonNull AuthorsViewHolder holder, int position) {
if (!mCursor.moveToPosition(position))
{
return;
}
final int author_id = mCursor.getInt(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_1));
final String name = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_2));
final String age = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_3));
final String image = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_4));
holder.authorIndex.setText(String.valueOf(author_id));
holder.authorName.setText(name);
holder.authorAge.setText(String.valueOf(age));
holder.authorName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), displayBooksFromAuthor.class);
intent.putExtra("Author_id", author_id);
intent.putExtra("Author_name", name);
intent.putExtra("Author_age", age);
intent.putExtra("Author_image", image);
mContext.startActivity(intent);
}
});
}
And finally, my DisplayAuthorDetails class which receives the data from the intent and displays it:
int author_id = intent.getIntExtra("Author_id", 0);
String author_name = intent.getStringExtra("Author_name");
String author_age = intent.getStringExtra("Author_age");
String author_picture = intent.getStringExtra("Author_image");
et_name.setText(author_name);
et_age.setText(author_age);
et_id.setText(String.valueOf(author_id));
Picasso.get().load(author_picture).into(author_image);
I have the library dependency and also the two permissions in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
implementation 'com.squareup.picasso:picasso:2.71828
The weirdest part of this problem is that when I create a brand new project and try to load an image it loads successfully. Any help is appreciated. Thank you for your time
EDIT
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Books and Authors.db";
public static final String TABLE_NAME_AUTHORS = "Authors_table";
public static final String AUTHORS_COL_1 = "Author_ID";
public static final String AUTHORS_COL_2 = "Name";
public static final String AUTHORS_COL_3 = "Age";
public static final String AUTHORS_COL_4 = "Author_picture";
public static final String TABLE_NAME_BOOKS = "Books_table";
public static final String BOOKS_COL_1 = "Book_ID";
public static final String BOOKS_COL_2 = "Author_Foreign";
public static final String BOOKS_COL_3 = "Title";
public static final String BOOKS_COL_4 = "Price";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME_BOOKS + " (Book_ID INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT," + "Author_Foreign INT," + "Price TEXT)");
db.execSQL("create table " + TABLE_NAME_AUTHORS + " (Author_ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT," + "Age INTEGER," + "Author_picture TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_AUTHORS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_BOOKS);
onCreate(db);
}
public boolean insertDataBooks(String title, float price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BOOKS_COL_3, title);
contentValues.put(BOOKS_COL_4, price);
long result = db.insert(TABLE_NAME_BOOKS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean insertDataAuthors(String name, int age) {
SQLiteDatabase mydb = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AUTHORS_COL_2, name);
contentValues.put(AUTHORS_COL_3, age);
long result = mydb.insert(TABLE_NAME_AUTHORS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean addBegginingInfo(int foreign_author_id, String title, double price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BOOKS_COL_2, foreign_author_id);
contentValues.put(BOOKS_COL_3, title);
contentValues.put(BOOKS_COL_4, price);
long result = db.insert(TABLE_NAME_BOOKS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean addBegginingInfoAuthor(String name, int age, String image)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AUTHORS_COL_2, name);
contentValues.put(AUTHORS_COL_3, age);
contentValues.put(AUTHORS_COL_4, image);
long result = db.insert(TABLE_NAME_AUTHORS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public Integer deleteBook(String index) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_BOOKS, "Book_ID = ?", new String[]{index});
}
public Integer deleteAuthor(String authorIndex) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_AUTHORS, "Author_ID = ?", new String[]{authorIndex});
}
public void resetBookTable() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_BOOKS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_BOOKS + "'");
addBegginingInfo(1, "Harry Potter", 9.99);
addBegginingInfo(1, "Fantastic Beasts", 14.99);
addBegginingInfo(2, "Lord of the Rings", 8.99);
addBegginingInfo(2, "The Hobbit", 12.99);
addBegginingInfo(3, "Sherlock Holmes", 6.99);
addBegginingInfo(3, "Valley of Fear", 7.99);
}
public void resetAuthor()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_AUTHORS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_AUTHORS + "'");
addBegginingInfoAuthor("J.K.Rowling", 54, "https://www.biographyonline.net/wp-content/uploads/2014/05/jk-rowling4.jpg");
addBegginingInfoAuthor("J.R.R. Tolken", 81, "https://www.biography.com/.image/t_share/MTE5NTU2MzE2Mzg4MzYxNzM5/jrr-tolkien-9508428-1-402.jpg");
addBegginingInfoAuthor("Arthur Conan Doyle", 71, "https://upload.wikimedia.org/wikipedia/commons/b/bd/Arthur_Conan_Doyle_by_Walter_Benington%2C_1914.png");
}
}

After many hours of trying I finally found out that to fix this issue I just had to re-install the app on the emulator.

Related

How to populate ListView with SQLite table where int value matches column in table

I am new to android development and can't get this to work. I am trying to populate a listview in my AdminActivity with the int value that I am passing from a previous list view. That int value then needs to be used to populate the ListView with the users that match the int value in the booking column of the users table.
Here is the 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.io.File;
import java.io.FileWriter;
import java.io.IOException;
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, "Johannesburg");
insertValues.put(COLUMN_PRICE, 1200);
insertValues.put(COLUMN_DEPARTURE_TIME, "12:00");
insertValues.put(COLUMN_ARRIVAL_TIME, "14:15");
insertValues.put(COLUMN_DURATION, "2:15");
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, "16:00");
insertValues2.put(COLUMN_ARRIVAL_TIME, "18:15");
insertValues2.put(COLUMN_DURATION, "2:15");
insertValues2.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues2);
ContentValues insertValues3 = new ContentValues();
insertValues3.put(COLUMN_DESTINATION, "Durban");
insertValues3.put(COLUMN_PRICE, 800);
insertValues3.put(COLUMN_DEPARTURE_TIME, "12:00");
insertValues3.put(COLUMN_ARRIVAL_TIME, "14:00");
insertValues3.put(COLUMN_DURATION, "2:00");
insertValues3.put(COLUMN_AVAILABLE_SEATS, 2);
MyDB.insert(FLIGHTS, null, insertValues3);
ContentValues insertValues4 = new ContentValues();
insertValues4.put(COLUMN_DESTINATION, "Port Elizabeth");
insertValues4.put(COLUMN_PRICE, 700);
insertValues4.put(COLUMN_DEPARTURE_TIME, "08:00");
insertValues4.put(COLUMN_ARRIVAL_TIME, "09:10");
insertValues4.put(COLUMN_DURATION, "1:10");
insertValues4.put(COLUMN_AVAILABLE_SEATS, 0);
MyDB.insert(FLIGHTS, null, insertValues4);
ContentValues insertValues5 = new ContentValues();
insertValues5.put(COLUMN_DESTINATION, "Port Elizabeth");
insertValues5.put(COLUMN_PRICE, 700);
insertValues5.put(COLUMN_DEPARTURE_TIME, "12:00");
insertValues5.put(COLUMN_ARRIVAL_TIME, "13:10");
insertValues5.put(COLUMN_DURATION, "1:10");
insertValues5.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues5);
ContentValues insertValues6 = new ContentValues();
insertValues6.put(COLUMN_DESTINATION, "Durban");
insertValues6.put(COLUMN_PRICE, 900);
insertValues6.put(COLUMN_DEPARTURE_TIME, "14:00");
insertValues6.put(COLUMN_ARRIVAL_TIME, "16:00");
insertValues6.put(COLUMN_DURATION, "2:00");
insertValues6.put(COLUMN_AVAILABLE_SEATS, 11);
MyDB.insert(FLIGHTS, null, insertValues6);
}
#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)});
}
#SuppressLint("Range")
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;
}
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.getId() < 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.getName() + "-" +
currentFlightsModel.getDestination() + "-" +
currentFlightsModel.getDeparture_time() + "-" +
currentFlightsModel.getArrival_time()
;
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("Invoice for flight:" + "\n" +
"\n" + "-----------------------------------------------" +
"\n" + "User: " + userName +
"\n" + "Destination: " + currentFlightsModel.getDestination()+
"\n" + "Departure time at: " + currentFlightsModel.getDeparture_time() +
"\n" + "Arrival time at: " + currentFlightsModel.getArrival_time() +
"\n" + "Duration of flight: " + currentFlightsModel.getDuration() +
"\n" + "Amount paid: " + "R" + currentFlightsModel.getPrice()
);
fw.flush();
fw.close();
rv = rcpt.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
rv = "IOERROR - " + e.getMessage();
}
return rv;
}
}
Here is the usersmodel class:
package com.example.shashank.fffffffffffffffffffffffffff;
public class UsersModel {
private String name, password, email;
private double balance;
int booking;
public UsersModel(String name, String password, String email, double balance, int booking) {
this.name = name;
this.password = password;
this.email = email;
this.balance = balance;
this.booking = booking;
}
public UsersModel() {
}
public int getBooking() {
return booking;
}
public void setBooking(int booking) {
this.booking = booking;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "UsersModel{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
Here is the AdminActivity:
package com.example.shashank.fffffffffffffffffffffffffff;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
public class AdminActivity extends AppCompatActivity {
ListView userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
userList = findViewById(R.id.userList);
int intValue;
Intent mIntent = getIntent();
intValue = mIntent.getIntExtra("intVariableName", 0);
intValue = intValue + 1;
Toast.makeText(AdminActivity.this, Integer.toString(intValue), Toast.LENGTH_SHORT).show();
}
}
I want to use the intValue and populate the list with all the users where the intValue matches the int value in their booking column.
Any help will be appreciated thank you
First Add a method to DBHelper to get the list of users as a Cursor by the int (BOOKING) such as :-
public Cursor getUsersByBookingNumber(int bookingNumber) {
SQLiteDatabase MyDB = this.getWritableDatabase();
/* return cursor with ALL columns AND a column called _ID which has the rowid */
return MyDB.query(USERS, new String[]{"*","rowid AS " + BaseColumns._ID},BOOKING+"=?",new String[]{String.valueOf(bookingNumber)},null,null,null);
}
Note that Cursor Adapters MUST have a column name _id (BaseColumns._ID resolves to _id) so this is achieved by getting the rowid column AS _id.
A ListView requires an adapter, Cursor Adapters are designed for use with Cursors so SimpleCursorAdapter is used.
An adapter requires a layout that will be used to display each item in the list (an item can consist of multiple views). In this case the stock layout simple_list_item2 will be used (you would probably want to create your own layout). You setup the adapter and then tell the ListView what adapter to use.
All of the above is done in the respective activity. To demonstrate MainActivity has been used, it is :-
public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
Cursor userListViewCursor; /* The Cursor to be used for the ListView */
SimpleCursorAdapter sca; /* The adapter for the ListView */
ListView userListView; /* The ListView */
int currentBookingNumber; /* the int */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userListView = this.findViewById(R.id.activity_admin);
/* Prepare Database */
dbHelper = new DBHelper(this);
/* Add some test data */
dbHelper.insertData("Fred","password","fred#email",0.00);
dbHelper.insertData("Mary","password","mary#email",0.00);
dbHelper.insertData("Jane","password","jane#email",0.00);
dbHelper.insertData("Tom","password","tom#email",0.00);
dbHelper.insertData("Sue","password","sue#email",0.00);
dbHelper.insertData("Bob","password","bob#email",0.00);
dbHelper.makeBooking("Fred",1);
dbHelper.makeBooking("Mary",2);
dbHelper.makeBooking("Sue",3);
dbHelper.makeBooking("Jane",1);
dbHelper.makeBooking("Tom",2);
dbHelper.makeBooking("Bob",1);
currentBookingNumber = 1; /*(mimic getting the booking number)*/
/* setup the ListView as the adapter will be null */
setupOrRefreshLIstView(currentBookingNumber);
}
private void setupOrRefreshLIstView(int bookingNumber) {
userListViewCursor = dbHelper.getUsersByBookingNumber(bookingNumber);
if (sca == null) {
sca = new SimpleCursorAdapter(
this,
/* The layout for each item in the ListView */
android.R.layout.simple_list_item_2,
userListViewCursor,
/* Columns in the Cursors */
new String[]{DBHelper.USERNAME,DBHelper.EMAIL},
/* id of the View in the ListView's item layout that corresponds with the column in the Cursor*/
/* NOTE 1st column corresponds to first id and so on so :- */
/* USERNAME column value is placed into text1 View, EMAIl column into text2 */
/* simple list item has 2 TextViews with ids text1 and text2 */
new int[]{android.R.id.text1,android.R.id.text2},
0
);
/* Tie the adapter sca to the ListView userListView */
userListView.setAdapter(sca);
/* set listeners here if required e.g. */
userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressLint("Range")
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l /* will be the value of _id column */) {
Toast.makeText(view.getContext(),
"You clicked on the row with _id " + l
+ " the user is " + userListViewCursor.getString(userListViewCursor.getColumnIndex(DBHelper.USERNAME))
+ " the email is " + userListViewCursor.getString(userListViewCursor.getColumnIndex(DBHelper.EMAIL))
/* even though balance etc is not shown as the values are in the cursor they can be retrieved */
+ " the balance is " + userListViewCursor.getDouble(userListViewCursor.getColumnIndex(DBHelper.BALANCE))
,
Toast.LENGTH_SHORT).show();
}
});
} else {
sca.swapCursor(userListViewCursor);
}
}
/* if the activity is resumed then refresh the ListView just in case the data has changed */
#Override
protected void onResume() {
super.onResume();
setupOrRefreshLIstView(currentBookingNumber);
}
#Override
protected void onDestroy() {
super.onDestroy();
userListViewCursor.close(); /*should always close a cursor when done with it */
}
}
Note that some testing data is generated and loaded to demonstrate.
An onItemClickListener has been added, this will toast the details of the clicked item.
Running the above results in :-

multiple tables in android

I want to use two tables in my SQLite database but when I try to read the second table my app crashes.
I have a table for the items in a storage and another table for the employees of the storage.
Here is my database class:
public class Database extends SQLiteOpenHelper {
protected static final String DATABASE_NAME = "Storage";
protected static final String KEY_ID = "id";
protected static final String KEY_DESCRIPTION = "description";
protected static final String KEY_CATEGORY = "category";
protected static final String KEY_ORIGIN = "origin";
protected static final String KEY_DATE = "date";
protected static final String KEY_BRAND = "brand";
protected static final String TAB_NAME = "items";
protected static final String KEY_ID2 = "id2";
protected static final String KEY_SURNAME = "surname";
protected static final String KEY_NAME = "name";
protected static final String KEY_USERNAME = "username";
protected static final String KEY_PASSWORD = "password";
protected static final String TAB_NAME2 = "employees";
protected static final int VERSION = 1;
public Database(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TAB_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_DESCRIPTION + " TEXT, "
+ KEY_CATEGORY + " TEXT, "
+ KEY_ORIGIN + " TEXT, "
+ KEY_DATE + " TEXT, "
+ KEY_BRAND + " TEXT)";
String CREATE_DIPENDENTI_TABLE = "CREATE TABLE " + TAB_NAME2 + " ("
+ KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SURNAME + " TEXT, "
+ KEY_NAME + " TEXT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT)";
db.execSQL(CREATE_ITEMS_TABLE);
db.execSQL(CREATE_DIPENDENTI_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME2);
this.onCreate(db);
}
public void Add(String des, String cat, String pro, String data, String brand) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DESCRIPTION, des);
contentValues.put(KEY_CATEGORY, cat);
contentValues.put(KEY_ORIGIN, pro);
contentValues.put(KEY_DATE, data);
contentValues.put(KEY_BRAND, brand);
sqLiteDatabase.insert(TAB_NAME,null, contentValues);
sqLiteDatabase.close();
}
public void Add(String cog, String nom, String user, String pass) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURNAME, cog);
contentValues.put(KEY_NAME, nom);
contentValues.put(KEY_USERNAME, user);
contentValues.put(KEY_PASSWORD, pass);
sqLiteDatabase.insert(TAB_NAME2,null, contentValues);
sqLiteDatabase.close();
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + ";";
return sqLiteDatabase.rawQuery(query, null);
}
public ArrayList getInfoDip() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
ArrayList<String> al=new ArrayList<>();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM " +TAB_NAME2, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
al.add(cursor.getString(cursor.getColumnIndex("surname")));
al.add(cursor.getString(cursor.getColumnIndex("name")));
al.add(cursor.getString(cursor.getColumnIndex("username")));
al.add(cursor.getString(cursor.getColumnIndex("password")));
cursor.moveToNext();
}
return al;
}
public void Modify(int cod,String des, String cat, String pro, String dat, String bran){
SQLiteDatabase db = this.getWritableDatabase();
if(!des.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET description = "+"'"+des+"' "+ "WHERE id = "+"'"+cod+"'");
if(!cat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET categoria = "+"'"+cat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!pro.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET origin = "+"'"+pro+"' "+ "WHERE id = "+"'"+cod+"'");
if(!dat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET date = "+"'"+dat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!bran.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET brand = "+"'"+bran+"' "+ "WHERE id = "+"'"+cod+"'");
}
public void Modify(int cod, String cog, String nom, String user, String pass){
SQLiteDatabase db = this.getWritableDatabase();
if(!cog.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET surname = "+"'"+cog+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!nom.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET name = "+"'"+nom+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!user.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET username = "+"'"+user+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!pass.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET password = "+"'"+pass+"' "+ "WHERE id2 = "+"'"+cod+"'");
}
public void Delete(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME+" WHERE id= "+"'"+cod+"'");
}
public void DeleteDip(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME2+" WHERE id2= "+"'"+cod+"'");
}
public Cursor Search(int cod){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE id = "+"'"+cod+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public Cursor Search(String des){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE description = "+"'"+des+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public void DeleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from " + TAB_NAME);
}
}
and here is the activity where I try to get the ArrayList with the data:
private Database db= new Database(this);
private ArrayList<String> al=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
db.Add("admin","admin","admin","admin");
al.addAll(db.getInfoDip());
But when I try to put the data in the ArrayList the app crashes. Can anyone help me out?
Well so far, how I learned that the best practice for formating queries is to use String.format function. Here your example:
String query = "SELECT * FROM " + TAB_NAME + ";";
Best practice:
String query = String.format("SELECT * FROM %s", TAB_NAME);
So let's get to the getInfoDip method, you should try this:
public List<ContentValues> getInfoDip() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", TAB_NAME2);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContentValues> list = new ArrayList<>(res.getCount());
while (!res.isAfterLast()){
String surname = res.getString(res.getColumnIndex(KEY_SURNAME));
String name = res.getString(res.getColumnIndex(KEY_NAME));
String username = res.getString(res.getColumnIndex(KEY_USERNAME));
String password = res.getString(res.getColumnIndex(KEY_PASSWORD));
list.add(new ContentValues(surname, name, username, password));
res.moveToNext();
}
return list;
}
Here is my whole SQLite test program, check out maybe it helps you:
package com.example.vezba09;
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 Database extends SQLiteOpenHelper {
private static final String DATABASE_FILE_NAME = "contact_database";
public Database(#Nullable Context context) {
super(context, DATABASE_FILE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format(
"CREATE TABLE IF NOT EXISTS %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT)",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID,
ContactModel.COLUMN_CONTACT_NAME,
ContactModel.COLUMN_CONTACT_EMAIL,
ContactModel.COLUMN_CONTACT_PHONE
);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String query = String.format("DROP TABLE IF EXISTS %s", ContactModel.TABLE_NAME);
db.execSQL(query);
onCreate(db);
}
//Dodavanje kontakta
public void addContact(String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.insert(ContactModel.TABLE_NAME, null, cv);
}
//Izmena
public void editContact(int contactId, String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.update(ContactModel.TABLE_NAME,
cv,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public int deleteContact(int contactId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public ContactModel getContactById(int contactId) {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s WHERE %s = ?",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID);
Cursor res = db.rawQuery(query, new String[] {String.valueOf(contactId)});
if(res.moveToFirst()) {
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
return new ContactModel(contactId, name, email, phone);
}
else {
return null;
}
}
public List<ContactModel> getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", ContactModel.TABLE_NAME);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContactModel> list = new ArrayList<>(res.getCount());
while(!res.isAfterLast()) {
int contactId = res.getInt(res.getColumnIndex(ContactModel.COLUMN_CONTACT_ID));
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
list.add(new ContactModel(contactId, name, email, phone));
res.moveToNext();
}
return list;
}
}
Try this and feel free to ask more questions :)
Best regards, Sanady

How to check that a string being entered isn't a unique string. Java (SQLite database)

Hi I am new to android development and I am attempting to make an app which stores appointments. My fragments and activities are all fine however I am trying to work out how to check my sqlite database that the string I am trying to enter isn't already stored as a unique string already, any help is much appreciated.
Here is my code for the database so far.
public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "appointments.db";
public static final String TABLE_APPOINTMENTS = "appointments";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_MONTH = "month";
public static final String COLUMN_YEAR = "year";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_DESCRIPTION = "details";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_APPOINTMENTS
+ "(" + COLUMN_DAY + " INTEGER, " + COLUMN_MONTH + " INTEGER, " + COLUMN_YEAR + " INTEGER, "
+ COLUMN_TITLE + " TEXT NOT NULL UNIQUE, " + COLUMN_TIME + " TEXT, " + COLUMN_DESCRIPTION + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_APPOINTMENTS);
onCreate(db);
}
public void addAppointment(Appointment app){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
Call this method and check return true mean its exist otherwise not.
public boolean checkAppointmentExist(String name){
booolean isExist = false;
String selection = COLUMN_TITLE + " = ? ";
String[] selectionArgs = new String[]{name};
Cursor cursor = database.query(TABLE_APPOINTMENTS, null, selection, selectionArgs, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isExist = true;
}
}
return isExist;
}
public void addAppointment(Appointment app){
if(!checkAppointmentExist(app.get_title())){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}

SQLite database table updating all but one field

So I'm working on an Android app where I have data saved in Android's SQLite database. For some reason, streakCategory and daysKept will update fine, but streakName will not update. Does anybody have any idea why? My code is the same as it is for streakCategory and daysKept.
Snippet of EditStreak.java:
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putString("currButtonActivityName", streakIcon.getText().toString()).commit();
editor.putString("currButtonActivityCategory", categoryIcon.getText().toString()).commit();
editor.putInt("currButtonDaysKept", Integer.parseInt(streakDaysKept.getText().toString().trim())).commit();
String updateName = prefs.getString("currButtonActivityName", "").trim();
String updateCategory = prefs.getString("currButtonActivityCategory", "").trim();
int updateDaysKept = prefs.getInt("currButtonDaysKept", 0);
boolean isUpdated = db.updateData(updateName, updateCategory, updateDaysKept);
Log.d("Name: ", prefs.getString("currButtonActivityName", ""));
if (isUpdated == true){
Log.d("carter.streakly", "AFTER SUCCESS: ID: " + prefs.getInt("currButtonID", 0) + " Name: " + prefs.getString("currButtonActivityName", "") + " Category: " +
prefs.getString("currButtonActivityCategory", "") + " Days Kept: " + prefs.getInt("currButtonDaysKept", 9));
Intent intent = new Intent(EditStreak.this, EnlargedActivity.class);
startActivity(intent);
finish();
}
else{
Toast.makeText(EditStreak.this, "Data not Updated", Toast.LENGTH_LONG);
}
}
});
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "streaks.db"; // Name of DB
public static final String TABLE_NAME = "streak_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "STREAKNAME";
public static final String COL_3 = "STREAKCATEGORY";
public static final String COL_4 = "DATESTARTED";
public static final String COL_5 = "DAYSKEPT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,STREAKNAME TEXT,STREAKCATEGORY TEXT,DATESTARTED TEXT,DAYSKEPT INTEGER);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String STREAKNAME, String STREAKCATEGORY, String DATESTARTED, int DAYSKEPT){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, STREAKNAME);
contentValues.put(COL_3, STREAKCATEGORY);
contentValues.put(COL_4, DATESTARTED);
contentValues.put(COL_5, DAYSKEPT);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
} else {
db.close();
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM "+TABLE_NAME,null);
return res;
}
public boolean updateData(String streakName, String streakCategory, int daysKept){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, streakName);
contentValues.put(COL_3, streakCategory);
contentValues.put(COL_5, daysKept);
db.update(TABLE_NAME, contentValues, "STREAKNAME = ?", new String[] {streakName});
return true;
}
public Integer deleteData(String streakName){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "STREAKNAME = ?", new String[] {streakName});
}
public boolean vacuum(){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("VACUUM");
return true;
}
}
You can try something like this :
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
SQLiteStatement upd=db.compileStatement("UPDATE "+TABLE_NAME+" SET "+COLUMN_NAME+"=VALUE WHERE "+STREAKNAME +"=?");
upd.bindString(1, streakNameValue);
upd.execute();
db.setTransactionSuccessful();
db.endTransaction();
Log.e("update", "done");
Would that ever change according to logic ??
you are querying the record based on streakName and updating the same name.
......
contentValues.put(COL_2, streakName); // streakName = "abcd"
......
db.update(TABLE_NAME, contentValues, "STREAKNAME = ?", new String[] {streakName});
return true;
// here you are querying records which have streakName as "abcd" already, so it wont change
Eithe you need to change it to query it by id of record or pass old streakname which has to be replaced by this new streakName.
db.update(TABLE_NAME, contentValues, "STREAKID = ?", new String[] {streakID});
return true;
or
contentValues.put(COL_2, NEWstreakName);
db.update(TABLE_NAME, contentValues, "STREAKNAME = ?", new String[] {OLDStreakName});
return true;

Delete an Item on Listview but this doesnt deleted from SQLite

I use this method to delete an Item on my SQLite database:
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
And this to my ListView:
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
The problem is that when i delete an item on my listview the item disappears but when I re-open it the item is still there, because this doesn't remove from the database.
I 'll try to explain this with images :
This means that there is some problem with the deleting from the db. Just replace 2nd line in your deleteItem() with
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item}
Log.d("deletedItem", x);
Here x would be the number of rows deleted. Check the value of x after deleting, it should be greater than 0 if the deletion was successful. If it is not then that means the query is wrong and we would need the database schema for correcting it. From your ListView implementation code, its clear that your nameString itself is wrong. You are adding the whole Item in the arraylist and passing to the adapter. And when you fetch the item in the onItemClick dialog, you are using this code
String nameString = (arg0
.getItemAtPosition(arg2))
.toString();
Here arg0.getItemAtPosition(arg2) would return an Item object. You will have to do something like this.
Item tempItem=(Item)items.get(arg2);
String nameString=tempItem.getName();
where getName() would return the name of the item.
The change that I did:
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
to
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
String nameStringData = nameString.substring(6,
nameString.indexOf("Priority Level:") - 1);
Log.d("itemtodelete", nameStringData);
db.deleteItem(nameStringData);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
If you have a better suggestion please post an answer.
Yes this is the problem.
deletedItem = 0 on logCat so that's my database:
public class DatabaseHolder extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ItemsList";
private static final String TABLE_NAME = "Items";
private static final String ITEMS_COLUMN = "items_name";
private static final String PRIORITY_COLUMN = "Priority";
private static final String ID_COLUMN = "Items";
private static int DATABASE_VERSION = 1;
private static String QUERY = "CREATE TABLE " + TABLE_NAME + "("
+ ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEMS_COLUMN
+ " TEXT NOT NULL, " + PRIORITY_COLUMN + " TEXT NOT NULL);";
public DatabaseHolder(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
// Sharer!
public void addItem(String item_name, String priority) {
if (!duplicate(item_name)) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ITEMS_COLUMN, item_name);
values.put(PRIORITY_COLUMN, priority);
db.beginTransaction();
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
public boolean duplicate(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, ITEMS_COLUMN + " =?",
new String[] { name }, null, null, null);
int temp = c.getCount();
c.close();
db.close();
if (temp > 0)
return true;
else
return false;
}
public ArrayList<Item> getAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Item> item = new ArrayList<Item>();
db.beginTransaction();
Cursor cursor = db.query(TABLE_NAME, new String[] { this.ITEMS_COLUMN,
this.PRIORITY_COLUMN }, null, null, null, null, PRIORITY_COLUMN
+ " DESC");
while (cursor.moveToNext()) {
Item itemTemp = new Item(cursor.getString(cursor
.getColumnIndexOrThrow(ITEMS_COLUMN)), new Level(
Integer.parseInt(cursor.getString(cursor
.getColumnIndexOrThrow(PRIORITY_COLUMN)))));
item.add(itemTemp);
}
cursor.close();
db.endTransaction();
db.close();
return item;
}
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
Log.d("deletedItem", String.valueOf(x) );
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}

Categories