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

Show graphical element/view when tapping on android
Why is Keyguard not being Re-enabled?
Is there a way to get all location point (lat and lon) around a specific country?
How to set Socket timeout of fail connecting
how can decode json data form api in android?
Disable SQLiteLog in Android
http-link to private Dropbox files
Mvvmcross Loading Indicator not showing
VideoView problems in ScrolView
Android app publishing/ google play store app publication query
Php Post FATAL EXCEPTION — Async and permission included
No resource identifier found for attribute 'isSelected' in package 'auto'
XMPP error using asmack
Android - Graying out/changing the alpha of all items aside from the selected item
How to bring ImageView in front of Button in android 5?
How to set time by location Android

Categories

HOME
phpword
deep-learning
nunit
mjml
yahoo-finance
socket.io
can
xbee
data-visualization
computer-science
fabric.io
enthought
redis-sentinel
emoji
jxl
tput
automatic-ref-counting
3nf
magnetic-cards
event-sourcing
fileserver
android-7.0-nougat
smartclient
pyramid
apache2.4
microsoft-ocr
ag
guzzle
gulp-watch
aggregation
zxing
flask-sqlalchemy
opentk
fat
jackson-modules
bringtofront
testcomplete
instantiation
hibernate-search
modalviewcontroller
parse-tree
openproject
lint
playframework-2.1
jvmti
opensmpp
branching-and-merging
opencmis
lampp
hammer.js
carrot2
git-flow
ngmaterial
otp
check-mk
css-transforms
rmongo
mapinfo
pre-build-event
kiosk
createprocess
nio2
text-search
coda
cgi-bin
mod-proxy
skspritenode
mirror
canvg
kubuntu
nodelist
boost-program-options
structuremap3
formview
live555
functional-java
wxformbuilder
spring-remoting
multiautocompletetextview
xmltodict
ora-06550
windows-phone-8-sdk
printdialog
cmmi
android-icons
cascadingdropdown
boost-msm
iboutlet
boost-signals
jdb
oracle-enterprise-linux
ilasm
luabind
gobject-introspection
ikimagebrowserview
fsevents
drawtobitmap
strsep
collectionviewsource
cac
presentation-layer
squishit
dot-emacs
hbm2java
tabpanel
scrubyt
flvplayback
unmanagedresources

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