android


I am not able to fetch and delete data from Sq-lite


I have created database to perform add to cart functioning.
This is my database helper class.
public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "soulcluster";
// User table name
private static final String TABLE_USER = "user";
private static final String TABLE_PRODUCT = "product";
private static final String TABLE_ADD_TO_CART = "addtocart";
// User Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_PASSWORD = "password";
private static final String KEY_PRODUCT_ID = "id";
private static final String KEY_PRODUCT_IMAGE = "image";
private static final String KEY_PRODUCT_NAME = "productname";
private static final String KEY_PRODUCT_PRICE = "productprice";
private static final String KEY_PRODUCT_DESCRIPTION = "productdescription";
public SQLiteHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USER_TABLE = "CREATE TABLE "
+ TABLE_USER + "("
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_PASSWORD + " TEXT" + ")";
String CREATE_PRODUCT_TABLE = "CREATE TABLE "
+ TABLE_PRODUCT + "("
+ KEY_PRODUCT_ID + " TEXT PRIMARY KEY,"
+ KEY_EMAIL + " TEXT,"
+ KEY_PRODUCT_IMAGE + " BLOB NOT NULL,"
+ KEY_PRODUCT_NAME + " TEXT NOT NULL,"
+ KEY_PRODUCT_PRICE + " TEXT NOT NULL,"
+ KEY_PRODUCT_DESCRIPTION + " TEXT NOT NULL" + ")";
String CREATE_ADD_TO_CART_TABLE = "CREATE TABLE "
+ TABLE_ADD_TO_CART + "("
+ KEY_PRODUCT_ID + " TEXT PRIMARY KEY,"
+ KEY_PRODUCT_IMAGE + " BLOB NOT NULL,"
+ KEY_PRODUCT_NAME + " TEXT NOT NULL,"
+ KEY_PRODUCT_PRICE + " TEXT NOT NULL,"
+ KEY_PRODUCT_DESCRIPTION + " TEXT NOT NULL" + ")";
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_PRODUCT_TABLE);
db.execSQL(CREATE_ADD_TO_CART_TABLE);
Log.d(TAG, "Database tables created" + CREATE_USER_TABLE + " " + CREATE_PRODUCT_TABLE + " " + CREATE_ADD_TO_CART_TABLE);
}
public void addToCart(String product_id, byte [] image, String productName, String productPrice, String productDescription){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_PRODUCT_ID, product_id);
contentValues.put(KEY_PRODUCT_IMAGE, image);
contentValues.put(KEY_PRODUCT_NAME, productName);
contentValues.put(KEY_PRODUCT_PRICE, productPrice);
contentValues.put(KEY_PRODUCT_DESCRIPTION, productDescription);
long id = db.insert(TABLE_ADD_TO_CART, null, contentValues);
db.close();
Log.d(TAG, "New product added into Add to cart " + product_id + " " + image + " " + productName + " " + productPrice + " " + productDescription + " " +id);
}
public void deleteAddToCartItem(String id){
try {
SQLiteDatabase db = this.getWritableDatabase();
String query = "delete from " + TABLE_ADD_TO_CART + " where id=\'" + id + "'";
Log.d("", "Id is here " + id);
db.execSQL(query);
db.close();
}catch (Exception e){
Log.d("", " Something is wrong");
}
}
public ArrayList<AddToCartItems> fetchProduct()
{
ArrayList<AddToCartItems> product = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "select * from " + TABLE_ADD_TO_CART ;
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
AddToCartItems addToCartItems = new AddToCartItems();
addToCartItems.setId(cursor.getString(0));
addToCartItems.setImageArray(cursor.getBlob(1));
addToCartItems.setName(cursor.getString(2));
addToCartItems.setPrice(cursor.getString(3));
addToCartItems.setDescription(cursor.getString(4));
product.add(addToCartItems);
Log.d("", "check -----" + cursor.getString(cursor.getColumnIndex("productname")) + " " + cursor.getString(cursor.getColumnIndex("id")));
cursor.moveToNext();
Log.d("", "Inside fetching method" + " " + cursor.getCount() + " " + product.size() );
System.out.print(cursor.getCount());
}while (cursor.moveToNext());
/* for (int a = 0; a < cursor.getCount(); a++){
}*/
}
Log.d("", "Checkimh product size " + product.size());
db.close();
return product;
}
I have just posted required methods.
In my adapter class on click of add to cart bucket the product will added into database.
holder.add_to_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), items.getItem_Image());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
Date d = new Date();
SimpleDateFormat sm = new SimpleDateFormat("yyyymmddhhmmss");
String productID = sm.format(d);
db.addToCart(productID, bitmapdata, items.getItem_name(), items.getItem_price(), items.getDescription());
//AppController.getInstance().addToCartItemses(items.getItem_Image(), items.getItem_name(), items.getItem_price(), items.getDescription());
Log.d(""," ShopAdapter " + " " + bitmapdata + " " + productID + " " + items.getItem_Image() + " "+ items.getItem_name()+ " "+ items.getItem_price() +" " +items.getDescription());
}
});
here is that method. I have used image as button and on clicking that image insert query fires.
This is the delete method in next activity adapter class
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.deleteAddToCartItem(addToCartItemses.get(position).getId());
addToCartItemses.remove(position);
notifyDataSetChanged();
}
});
Why my queries are not running.
You don't have to specially use anything for user unique id as every logged in user is assigned a unique id and you can retrieve it like this :
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address, and profile photo Url
    String name = user.getDisplayName();
    String email = user.getEmail();
    Uri photoUrl = user.getPhotoUrl();
    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getToken() instead.
    String uid = user.getUid();
}
This code snippet can be found in official firebase docs here
Do let me know if this info helps you.

Related Links

How can I do a test in Android?
How to disable emojis from android keyboard in xamarin forms?
OnMapReadyCallback not triggered when using Fragment
Android: Improve quality for screen recording by the use of API MEDIA_PROJECTION_SERVICE
Peer not authenticated in AndroidStudio, but not on commandline-gradle
White text under buttons in layout
How can I access a component(for example a timepicker) in one activity from another activity in Android?
Google play shows error code 504 for Android N preview
How to load image from writeable folder and assign to ImageView in Android?
EditText updates items on ListView with TextWatcher
FTDriver.java mDevice null error
How to use Android NavigationDrawer to create other fragments?
Android Studio resource not found after duplicate
ListView scroll position jumps to first element after notifydatasetchanged
Finger print lock in Android
Why doesn't my BTLE virtual beacon show in Chrome?

Categories

HOME
notepad++
composite-primary-key
jsf-2.2
socket.io
echo
spring-session
banner
retrofit2
boto3
pattern-matching
resultset
package.json
sse
topology
database-connection
sar
kendo-mobile
pagespeed
qliksense
object-storage
xcode-ui-testing
interbase
paperjs
mql
postback
openwhisk
fossil
python-import
salesforce-communities
playframework-2.1
css-position
demo
urlsession
odoo-website
laravel-elixir
plr
android-checkbox
linter
gitlist
yii2-api
vugen
trojan
aquamacs
reindex
pair-programming
otp
libjpeg
java-websocket
flac
bootstrap-tags-input
change-tracking
avspeechsynthesizer
udpclient
appscale
lua-telegram-bot
turbo-prolog
fuzzywuzzy
exim4
sciruby
atoi
baasbox
graphics2d
mirror
iiop
machine-instruction
universal-image-loader
mdichild
xml-namespaces
angular-carousel
lambda-architecture
ora-00904
reflector
xml-dsig
jjaql
qscrollarea
accesscontrolexception
bin
beaker-testing
cnf
jquery-1.9
http-status-code-410
fb.ui
faye
usertype
relative
saxparseexception
u2netdk
drawtobitmap
creole
cgbitmapcontextcreate
object-database
scrubyt
application-planning
lemmatization

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App