android


Delete Method in sqlite only deleting 1 row in listview


I am making a simple app using sqlite. I asked so many question related to this but hadn't got much replies.
I am having a Problem with my delete function which i want to use in another activity. But its not working, As i am using Custom Listview so I have 2 buttons on row of dynamically created list, one for Update the content and second for deleting the row of the list.
Actually the problem which I am getting is when i delete a row by using button on each row. it only delete the first Item of the List View. totally messed up. Please help me out with this
See:
Database Handler class:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "tt";
// Table names
private static final String TABLE_INCOME = "income";
//private static final String TABLE_INCOME = "income";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_PRICE = "price";
private static final String KEY_TYPE = "type";
private static final String KEY_DATE = "date";
private static final String KEY_DESCRIPTION = "description";
private static final String KEY_PAY_MODE = "pay_mode";
Context c;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_INCOME_TABLE = "CREATE TABLE if not exists " + TABLE_INCOME + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_PRICE + " REAL,"
+ KEY_TYPE + " TEXT,"
+ KEY_DATE + " TEXT,"
+ KEY_DESCRIPTION + " TEXT,"
+ KEY_PAY_MODE + " TEXT"
+")";
db.execSQL(CREATE_INCOME_TABLE);
Log.d(TABLE_INCOME, "table created with "+ KEY_PRICE +" "+ KEY_TYPE +" "
+ KEY_DATE +" " + KEY_DESCRIPTION +" " + KEY_PAY_MODE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_INCOME);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new income
void addContact(Income income) {
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PRICE, income.getPrice());
values.put(KEY_TYPE, income.getType());
values.put(KEY_DATE, income.getDate());
values.put(KEY_DESCRIPTION, income.getDescription());
values.put(KEY_PAY_MODE, income.getPaymode());
// Inserting Row
db.insert(TABLE_INCOME, null, values);
db.close(); // Closing database connection
}
catch(Exception e){
e.printStackTrace();
}
}
// Getting single income
Income getContact(int id) {
Income income = null;
try{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_INCOME, new String[] { KEY_ID, KEY_PRICE,
KEY_TYPE, KEY_DATE , KEY_DESCRIPTION, KEY_PAY_MODE}, null, null, null, null, null);
if (cursor.moveToFirst()) {
income = new Income(Integer.parseInt(cursor.getString(0)),Long.parseLong(cursor.getString(1)),
cursor.getString(2), cursor.getString(3),cursor.getString(4),cursor.getString(5));
Log.d("Genrated..", "Sending data");
}
}
catch(Exception e){
e.printStackTrace();
}
// return income
return income;
}
// Getting All Income
public List<Income> getAllContacts() {
List<Income> contactList = new ArrayList<Income>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_INCOME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Income income = new Income();
income.setPrice(Long.parseLong(cursor.getString(1)));
income.setType(cursor.getString(2));
income.setDate(cursor.getString(3));
income.setDescription(cursor.getString(4));
income.setPaymode(cursor.getString(5));
// Adding income to list
contactList.add(income);
} while (cursor.moveToNext());
}
// return income list
return contactList;
}
// Updating single income
public int updateContact(Income income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PRICE, income.getPrice());
values.put(KEY_TYPE, income.getType());
values.put(KEY_DATE, income.getDate());
values.put(KEY_DESCRIPTION, income.getDescription());
values.put(KEY_PAY_MODE, income.getPaymode());
// updating row
return db.update(TABLE_INCOME, values, null, null);
}
//Deleting single income
public void deleteContact(Income income) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_INCOME, KEY_ID + " = ?",new String[] { String.valueOf(income.getID()) });
db.close();
}
// Getting income Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_INCOME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Implementing in another activity :
String b = Long.toString(_incomelist.get(position).getPrice());
Typeface tf = Typeface.createFromAsset(getAssets(), "font/Rupee_Foradian.ttf");
viewHolder.txt_price.setTypeface(tf);
viewHolder.txt_id.setText(Integer.toString(_incomelist.get(position).getID()).trim());
viewHolder.txt_price.setText("` "+b.trim());
viewHolder.txt_type.setText(_incomelist.get(position).getType().trim());
viewHolder.txt_date.setText(_incomelist.get(position).getDate().trim());
viewHolder.txt_desc.setText(_incomelist.get(position).getDescription().trim());
viewHolder.txt_pmode.setText(_incomelist.get(position).getPaymode().trim());
final int temp = position;
(convertView.findViewById(R.id.imageButton2))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
ViewContact.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
try{
Income income = db.getContact(temp);
db.deleteContact(income); //here using my delete function
ViewContact.this.onResume();
Toast.makeText(getApplicationContext(),"Deleted..",Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
alertbox.show();
}
});
In your function getContact(int id) id is the id of the contact .But you arr not using this id in your query. Means you are not using any where clause in your query.Therefore it always returns first row of your db.

Related Links

Android : SensorEventListener in Fragment not calling onSensorChanged
Android Camera api using Webrtc affect record video button not working
Android Analyze APK
Layout glitch: Nesting RelativeLayout inside a LinearLayout
http requests failing after ionic build android
NotificationCompat.Builder with expand notification is not working
ProgressDialog displays incorrect
Could not install the app on the device on react-native run-android
Android: Type MenuPopup is inaccessible in this context due to: MenuPopup
Understanding Android SQLite [duplicate]
How do I create apk file for a Xamarin.Android application
Android touch Listener move
how to download a tablet emulator for Android lollipop 5.0 API 21
Kivy Buildozer Apk - Import Custom Modules
Trouble with Fragment TextWatcher to Activity communication
Opening Address links on google map app from a webview app

Categories

HOME
url-redirection
phantom-dsl
httparty
eclipse
microsoftgraph
api
prism
time-complexity
3d
spring-data-mongodb
carousel
mips
cakephp-3.4
onclick
banner
modal-dialog
ibeacon-android
datastage
openbugs
stellar.js
pybossa
dynatrace
magnetic-cards
qsqlquery
sse
charles
apache2.4
asciidoctor-pdf
question2answer
ember-cli
interpreter
dapper-extensions
interbase
rpgle
errbot
bioinformatics
event-flow
record
android-gridview
arduino-ide
browser-extension
mnist
playframework-2.1
filesystemwatcher
setup.py
resolution
odoo-website
print-css
apollostack
photos
servermanager
globalize
launchctl
carrot2
static-cast
pdf-conversion
oozie-coordinator
javafx-css
restore
testrail
pacemaker
lrs
ng-grid
simevents
pre-build-event
swizzling
shopping
http-status-code-401
mediametadataretriever
boost-serialization
uiactionsheet
upx
yajsw
grass
asyncdisplaykit
relativelayout
dynamics-nav-2016
morton-number
phonertc
haskell-warp
branch-and-bound
apache-commons-daemon
xmltype
apache-spark-1.3
iiop
strawberry-perl
gii
ignite-ui
personalization
fpdi
getopt
gwt-openlayers
script#
unit-of-work
tlf
dolby-audio-api
booksleeve
panda3d
database-create
apache-commons-dbutils
update-statement
google-ajax-api
dataform
mtu
cuda.net
scrubyt
wysiwym
entitykey
information-management
lemmatization
cardspace

Resources

Encrypt Message