Basically what I'm trying to do is to display data using ExpandableListView from my SQLite table, I was able to get data, but I'm getting this error 'java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#cc36823' when I'm trying to reopen my app from onPause state. I tried to search for the solution, and I think the only possible way to solve my problem is to use CursorLoader, but I don't know how can I use it into my code.
My Code >>
//onPause
#Override
protected void onPause() {
super.onPause();
SelectedListView.collapseGroup(lastExpandedPosition);
Cursor currentCursor = ((MyExpandableListAdapter)mAdapter).getCursor();
stopManagingCursor(currentCursor);
stopManagingCursor(childCursor);
}
//onRestart
#Override
protected void onRestart(){
super.onRestart();
Cursor cursor= dataBaseHelper.getSelectedParentMVPDate(reformatMVPDate());
mAdapter.changeCursor(cursor);
}
//ExpandableListView Data
private void fillData(){
String COA = String.format(dataBaseHelper.getCount(VisitDate));
if(COA.equals(0)) {
mGroupsCursor = dataBaseHelper.getSelectedParentMVPDate(reformatMVPDate());
startManagingCursor(mGroupsCursor);
mGroupsCursor.moveToFirst();
ExpandableListView SelectedListView = (ExpandableListView) findViewById(R.id.MVPListitem);
mAdapter = new MyExpandableListAdapter(mGroupsCursor, this,
R.layout.mvp_list_parent,
R.layout.mvp_list_child,
new String[]{DataBaseHelper.MVP_INDUSTRY_TYPE},
new int[]{R.id.txtMVPParent},
new String[]{DataBaseHelper.MVP_BRCH_CODE_NAME, DataBaseHelper.MVP_BRCH_ADDRESS, DataBaseHelper.MVP_ID},
new int[]{R.id.txtviewBrnchCodeName, R.id.txtviewBrchAddr, R.id.txtmvpID});
SelectedListView.setAdapter(mAdapter);
}
else{
mGroupsCursor = dataBaseHelper.getSelectedParentMVPDate(reformatMVPDate());
startManagingCursor(mGroupsCursor);
mGroupsCursor.moveToFirst();
ExpandableListView SelectedListView = (ExpandableListView) findViewById(R.id.MVPListitem);
mAdapter = new MyExpandableListAdapter(mGroupsCursor, this,
R.layout.mvp_list_parent,
R.layout.mvp_list_child,
new String[]{DataBaseHelper.MVP_INDUSTRY_TYPE},
new int[]{R.id.txtMVPParent},
new String[]{DataBaseHelper.MVP_BRCH_CODE_NAME, DataBaseHelper.MVP_BRCH_ADDRESS, DataBaseHelper.MVP_ID},
new int[]{R.id.txtviewBrnchCodeName, R.id.txtviewBrchAddr, R.id.txtmvpID});
SelectedListView.setAdapter(mAdapter);
}
}
public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
public MyExpandableListAdapter(Cursor cursor, Context context,int groupLayout,
int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,
int[] childrenTo) {
super(context, cursor, groupLayout, groupFrom, groupTo,
childLayout, childrenFrom, childrenTo);
}
#SuppressLint("Range")
#Override
protected Cursor getChildrenCursor(Cursor cursor) {
childCursor = (Cursor) dataBaseHelper.getSelectedChildMVPDate(cursor.getString(cursor.getColumnIndex(DataBaseHelper.MVP_INDUSTRY_TYPE)),reformatMVPDate());
startManagingCursor(childCursor);
childCursor.moveToFirst();
return childCursor;
}
public View getChildView(final int groupPosition,
final int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
View rowView = super.getChildView(groupPosition, childPosition,
isLastChild, convertView, parent);
removeMVP = (Button) rowView.findViewById(R.id.btnRemove);
TextView txtBCN = (TextView) rowView.findViewById(R.id.txtviewBrnchCodeName);
TextView txtBA = (TextView) rowView.findViewById(R.id.txtviewBrchAddr);
TextView txtmvpID = (TextView) rowView.findViewById(R.id.txtmvpID);
});
return rowView;
}
}
//Query for Parent/Group
public Cursor getSelectedParentMVPDate(String txtDate){
SQLiteDatabase db = this.getWritableDatabase();
String dropTMPMVPTBL = "DROP TABLE IF EXISTS TMP_MVP_TBL";
db.execSQL(dropTMPMVPTBL);
String q = "CREATE TEMP TABLE IF NOT EXISTS TMP_MVP_tbl AS SELECT a.SCHEDULED_DATE,b.recID,b.BRCH_CODE_NAME,c.BrchAddr,b.INDUSTRY_TYPE,b._id " +
"FROM MVP_a a " +
"LEFT join MVP_tbl b on a.MVP_ID = b.MVP_ID " +
"LEFT JOIN taggedList_tbl c on b.BRCH_CODE_NAME = c.BrchCodeName WHERE b.AppType = 'PLANNED' AND c.areaCode = (SELECT areaCode FROM USER_INFO)";
db.execSQL(q);
String query = "Select DISTINCT INDUSTRY_TYPE, _id from TMP_MVP_tbl WHERE " +SCHEDULED_DATE+ " = '"+txtDate+"' AND recID IS NOT NULL";
return db.rawQuery(query, null);
}
//Query for Child
public Cursor getSelectedChildMVPDate(String Industry, String txtDate){
SQLiteDatabase db = this.getWritableDatabase();
String dropTMPMVPTBL = "DROP TABLE IF EXISTS TMP_MVP_TBL";
db.execSQL(dropTMPMVPTBL);
String query = "CREATE TEMP TABLE IF NOT EXISTS TMP_MVP_tbl AS SELECT a.*,b.recID,b.BRCH_CODE_NAME,c.BrchAddr,b.INDUSTRY_TYPE,b._id " +
"FROM MVP_a a LEFT join MVP_tbl b on a.MVP_ID = b.MVP_ID LEFT JOIN taggedList_tbl c on b.BRCH_CODE_NAME = c.BrchCodeName " +
"WHERE b.AppType = 'PLANNED' AND c.areaCode = (SELECT areaCode FROM USER_INFO) AND " +MVP_INDUSTRY_TYPE+ " = '" + Industry + "' AND " +SCHEDULED_DATE+ " = '"+txtDate+"' ";
db.execSQL(query);
String q = "SELECT * FROM TMP_MVP_tbl";
return db.rawQuery(q, null);
}
Related
In my project there is a list of category and every category has multiple item .I want to store these category with its multiple items.My question is can i store it in sqlite and i want retrieve it in recycle view.
[![In the screenshot every category is given with the selection number.i want to insert it with category with its multiple items and also want to show as given in screenshots][1]][1]
[1]: https://i.stack.imgur.com/9WaKm.png `public class ViewAllAdapter extends RecyclerView.Adapter {
private ArrayList<StringMenuListBean> dataList;
private Context mContext;
private TextView itemText;
private List<String> itemList;
public ViewAllAdapter(Context context, ArrayList<StringMenuListBean> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowitem_viewall, null);
v.setLayoutParams(new RecyclerView.LayoutParams(
RecyclerView.LayoutParams.MATCH_PARENT,
RecyclerView.LayoutParams.WRAP_CONTENT
));
ItemRowHolder mh = new ItemRowHolder(v, mContext);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int position) {
itemList = new ArrayList<>();
final StringMenuListBean model = dataList.get(position);
String str = model.getName();
String category = str.substring(0, str.indexOf("-"));
String item = str.substring(str.indexOf("-") + 1, str.length());
itemList.add(item);
itemRowHolder.linear.removeAllViews();
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
Log.e("category", category);
Log.e("remainder", item);
itemRowHolder.tv_category_item.setText(category + " :");
for (int k = 0; k < itemList.size(); k++) {
itemText = new TextView(mContext);
itemText.setText((position + 1) + " ." + item);
itemText.setTextColor(Color.parseColor("#43A047"));
itemText.setLayoutParams(llp);
itemRowHolder.linear.addView(itemText);
}
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tv_category_item;
protected LinearLayout linear;
public ItemRowHolder(View view, final Context mContextv) {
super(view);
tv_category_item = (TextView) view.findViewById(R.id.tv_category_item);
linear = (LinearLayout) view.findViewById(R.id.linear);
}
}
}
here is my Activitypublic class ViewAllActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView viewall_recycleview;
ViewAllAdapter viewallAdapter;
TextView tv_ID;
TextView tv_PACKID;
TextView tv_PACKAGENAME;
TextView tv_USERID;
TextView tv_USER_NAME;
TextView tv_CATID;
TextView tv_CATNAME;
TextView tv_MENUITEMS;
TextView tv_MEMBER;
TextView tv_DATE;
TextView tv_TIME;
TextView tv_TOTAL_PRICE;
TextView tv_ORDER_TYPE;
TextView tv_DISCOUNT;
TextView tv_CITY;
TextView tv_PROMOCODE;
TextView tv_PAYMENT_STATUS;
TextView tv_PRICE;
TextView tv_MENUID;
TextView tv_SUBPACKAGENAME;
TextView tv_CURRENT_DATE;
Button btn_download;
MenuDetailBean menuDetailBean;
Bundle activitybundle;
String subpackage_id, pack_id;
String menuitem;
ArrayList<StringMenuListBean> stringMenuList;
StringMenuListBean stringMenu;
List<String> menulist;
List<String> arraylist1;
File imagePath;
RecyclerView rcyView_mymenu;
Bitmap bitmap;
View view;
ByteArrayOutputStream bytearrayoutputstream;
File file;
FileOutputStream fileoutputstream;
boolean boolean_save;
LinearLayout ll_linear;
MenuAdapter menuAdapter;
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewall);
init();
setTextAndList();
btn_download.setOnClickListener(this);
}
private void init() {
activitybundle = getIntent().getExtras();
pack_id = activitybundle.getString("pack_id");
subpackage_id = activitybundle.getString("sub_package_id");
// Log.e("subpackage_id",subpackage_id);
bytearrayoutputstream = new ByteArrayOutputStream();
rcyView_mymenu = (RecyclerView) findViewById(R.id.rcyView_mymenu);
rcyView_mymenu.setNestedScrollingEnabled(false);
tv_SUBPACKAGENAME = (TextView) findViewById(R.id.tv_SUBPACKAGENAME);
tv_PRICE = (TextView) findViewById(R.id.tv_PRICE);
tv_TOTAL_PRICE = (TextView) findViewById(R.id.tv_TOTAL_PRICE);
tv_DATE = (TextView) findViewById(R.id.tv_DATE);
tv_TIME = (TextView) findViewById(R.id.tv_TIME);
tv_MEMBER = (TextView) findViewById(R.id.tv_MEMBER);
tv_ORDER_TYPE = (TextView) findViewById(R.id.tv_ORDER_TYPE);
btn_download = (Button) findViewById(R.id.btn_download);
ll_linear = (LinearLayout) findViewById(R.id.ll_linear);
}
private void setTextAndList() {
menuDetailBean = DbUtils.getMenuDetail(getApplicationContext(), pack_id);
tv_SUBPACKAGENAME.setText(menuDetailBean.getSUBPACKAGE_NAME());
tv_PRICE.setText(menuDetailBean.getPRICE() + "/-");
tv_TOTAL_PRICE.setText(menuDetailBean.getTOTAL_PRICE() + "Rs.");
tv_DATE.setText(menuDetailBean.getDATE());
tv_TIME.setText(menuDetailBean.getTIME());
tv_MEMBER.setText(menuDetailBean.getMEMBER());
tv_ORDER_TYPE.setText(menuDetailBean.getORDER_TYPE());
menuitem = menuDetailBean.getMENUITEMS();
menulist = Arrays.asList(menuitem.split(","));
Log.e("meuitem", "" + menulist.size());
stringMenuList = new ArrayList<>();
for (int i = 0; i < menulist.size(); i++) {
StringMenuListBean stringMenu = new StringMenuListBean();
stringMenu.setName(menulist.get(i));
stringMenuList.add(stringMenu);
}
viewallAdapter = new ViewAllAdapter(getApplication(), stringMenuList);
rcyView_mymenu.setHasFixedSize(true);
rcyView_mymenu.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
rcyView_mymenu.setAdapter(viewallAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_download:
Bitmap bitmap1 = loadBitmapFromView(ll_linear, ll_linear.getWidth(), ll_linear.getHeight());
saveBitmap(bitmap1);
break;
}
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File("/sdcard/screenshotdemo.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(), imagePath.getAbsolutePath() + "", Toast.LENGTH_SHORT).show();
boolean_save = true;
btn_download.setText("Check image");
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
}
this is my Activity and below is my Database Utility code in which i saved all cart item . i want every added item is shown in different activity with its whole information.public class DbUtils {
public static void saveCart(Context context, CartItemBean data) {
ContentValues value = new ContentValues();
// for (CartItemBean data : data1) {
value.put(DbConstants.COLUMN_PACKID, data.getCOLUMN_PACKID());
value.put(DbConstants.COLUMN_PACKAGENAME, data.getCOLUMN_PACKAGENAME());
value.put(DbConstants.COLUMN_SUBPACKAGEID, data.getCOLUMN_SUBPACKAGE_ID());
value.put(DbConstants.COLUMN_SUBPACKAGENAME, data.getCOLUMN_SUBPACKAGE_NAME());
value.put(DbConstants.COLUMN_USERID, data.getCOLUMN_USERID());
value.put(DbConstants.COLUMN_USER_NAME, data.getCOLUMN_USER_NAME());
value.put(DbConstants.COLUMN_CATID, data.getCOLUMN_CATID());
value.put(DbConstants.COLUMN_CATNAME, data.getCOLUMN_CATNAME());
value.put(DbConstants.COLUMN_MENUITEMS, data.getCOLUMN_MENUITEMS());
value.put(DbConstants.COLUMN_MENUID, data.getCOLUMN_MENUID());
value.put(DbConstants.COLUMN_MEMBER, data.getCOLUMN_MEMBER());
value.put(DbConstants.COLUMN_DATE, data.getCOLUMN_DATE());
value.put(DbConstants.COLUMN_TIME, data.getCOLUMN_TIME());
value.put(DbConstants.COLUMN_TOTAL_PRICE, data.getCOLUMN_TOTAL_PRICE());
value.put(DbConstants.COLUMN_ORDER_TYPE, data.getCOLUMN_ORDER_TYPE());
value.put(DbConstants.COLUMN_DISCOUNT, data.getCOLUMN_DISCOUNT());
value.put(DbConstants.COLUMN_CITY, data.getCOLUMN_CITY());
value.put(DbConstants.COLUMN_CURRENTDATE, data.getCOLUMN_CURRENT_DATE());
value.put(DbConstants.COLUMN_PRICE, data.getCOLUMN_PRICE());
value.put(DbConstants.COLUMN_PROMOCODE, data.getCOLUMN_PROMOCODE());
value.put(DbConstants.COLUMN_PAYMENT_STATUS, data.getCOLUMN_PAYMENT_STATUS());
DbAccesser.getInstance(context).insertIntoTable(value,
DbConstants.TABLE_CART);
// }
}
// get product list
public static ArrayList<CartItemBean> getCartItems(Context context) {
ArrayList<CartItemBean> offlineDataList = new ArrayList<CartItemBean>();
Cursor cursor = DbAccesser.getInstance(context).query(DbConstants.TABLE_CART, null, null,
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
CartItemBean data = new CartItemBean();
data.setCOLUMN_ID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ID))));
data.setCOLUMN_CATID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATID))));
data.setCOLUMN_PAYMENT_STATUS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PAYMENT_STATUS))));
data.setCOLUMN_USER_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USER_NAME)))));
data.setCOLUMN_USERID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USERID))));
data.setCOLUMN_PACKAGENAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKAGENAME))));
data.setCOLUMN_CATNAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATNAME))));
data.setCOLUMN_CITY((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CITY))));
data.setCOLUMN_CURRENT_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CURRENTDATE))));
data.setCOLUMN_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DATE))));
data.setCOLUMN_DISCOUNT(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DISCOUNT)))));
data.setCOLUMN_MEMBER((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MEMBER))));
data.setCOLUMN_MENUITEMS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUITEMS))));
data.setCOLUMN_ORDER_TYPE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE))));
data.setCOLUMN_PACKID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKID))));
data.setCOLUMN_PROMOCODE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PROMOCODE))));
data.setCOLUMN_TIME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TIME)))));
data.setCOLUMN_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PRICE)))));
data.setCOLUMN_MENUID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUID)))));
data.setCOLUMN_TOTAL_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
data.setCOLUMN_SUBPACKAGE_ID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGEID)))));
data.setCOLUMN_SUBPACKAGE_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));
offlineDataList.add(data);
cursor.moveToNext();
}
}
return offlineDataList;
}
public static MenuDetailBean getMenuDetail(Context context, String packId) {
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + DbConstants.TABLE_CART + " WHERE "
+ DbConstants.COLUMN_PACKID + " = " + packId;
Cursor c = database.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
MenuDetailBean menuDetailBean = new MenuDetailBean();
menuDetailBean.setTIME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TIME)))));
menuDetailBean.setDATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_DATE)))));
menuDetailBean.setSUBPACKAGE_NAME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));
menuDetailBean.setPRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_PRICE)))));
menuDetailBean.setTOTAL_PRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
menuDetailBean.setMEMBER(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MEMBER)))));
menuDetailBean.setORDER_TYPE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE)))));
menuDetailBean.setMENUITEMS(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MENUITEMS)))));
menuDetailBean.setCURRENT_DATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_CURRENTDATE)))));
return menuDetailBean;
}
public static int deteteTableData(Context context, String tableName) {
int status = 0;
status = DbAccesser.getInstance(context).deleteTable(tableName);
return status;
}
public static void deleteOrderAfterTEnDays(Context context) {
Cursor cursor = DbAccesser.getInstance(context).raw_query("delete from new_order where current_datetime < default current_timestamp - INTERVAL 10 DAY", null);
Log.e("CURSOR", "" + cursor);
}
// get bill by particular date and outletId
public static CartItemBean getOrderBillByOutlet(Context context, CartItemBean bean) {
CartItemBean cartItemBean = new CartItemBean();
String[] params = new String[]{bean.getCOLUMN_PACKID(), bean.getCOLUMN_MEMBER(), bean.getCOLUMN_DATE(), bean.getCOLUMN_TIME()};
Cursor cursor = DbAccesser.getInstance(context).raw_query("select column_id,name,SUM(order_billing) from cart where order_date=? AND outlets_id=?", params);
if (cursor != null) {
if (cursor.moveToFirst()) {
}
}
return cartItemBean;
}
public static void updateRetailerList(Context context, CartItemBean cartItemBean) {
ContentValues values = new ContentValues();
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getWritableDatabase();
values.put(DbConstants.COLUMN_MEMBER, cartItemBean.getCOLUMN_MEMBER());
values.put(DbConstants.COLUMN_DATE, cartItemBean.getCOLUMN_DATE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TIME());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
values.put(DbConstants.COLUMN_SUBPACKAGEID, cartItemBean.getCOLUMN_SUBPACKAGE_ID());
values.put(DbConstants.COLUMN_SUBPACKAGENAME, cartItemBean.getCOLUMN_SUBPACKAGE_NAME());
values.put(DbConstants.COLUMN_CURRENTDATE, cartItemBean.getCOLUMN_CURRENT_DATE());
String sql2 = "UPDATE " + DbConstants.TABLE_CART + " SET " +
DbConstants.COLUMN_MEMBER + " = '" + cartItemBean.getCOLUMN_MEMBER() + "', "
+ DbConstants.COLUMN_DATE + " = '" + cartItemBean.getCOLUMN_DATE() + "', "
+ DbConstants.COLUMN_TIME + " = '" + cartItemBean.getCOLUMN_TIME() + "', "
+ DbConstants.COLUMN_SUBPACKAGEID + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_ID() + "', "
+ DbConstants.COLUMN_SUBPACKAGENAME + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_NAME() + "', "
+ DbConstants.COLUMN_CURRENTDATE + " = '" + cartItemBean.getCOLUMN_CURRENT_DATE() + "', "
+ DbConstants.COLUMN_TOTAL_PRICE + " = '" + cartItemBean.getCOLUMN_TOTAL_PRICE() + "' "
+ " WHERE " +
DbConstants.COLUMN_PACKID + " = '" + cartItemBean.getCOLUMN_PACKID() + "' AND "
+ DbConstants.COLUMN_USERID + " = '" + cartItemBean.getCOLUMN_USERID() + "'";
database.execSQL(sql2);
Log.e("UPDATE", sql2);
}
public static void deleteCartItem(Context context, String packId, String userId) {
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getWritableDatabase();
database.delete(DbConstants.TABLE_CART, DbConstants.COLUMN_PACKID + "=? AND "+ DbConstants.COLUMN_USERID + "=?", new String[]{packId, userId});
database.close();
}`
You can associate multiple items to each category, by creating a table with entries which each reflect an association.
For example, assuming you have a toy database like quoted at the end of this answer (see "MCVE foundation").
Create the table and add a few associations:
create table associations (id int, iid int);
insert into associations values (1, 1);
insert into associations values (1, 2);
insert into associations values (1, 3);
insert into associations values (2, 4);
insert into associations values (2, 5);
insert into associations values (3, 6);
insert into associations values (3, 7);
Then you can retrieve items for all categories:
select cat, name from cats inner join associations using(id) inner join items using (iid);
Output:
cat name
----------- ----------
soup tomato
soup sour
soup corn
namkeen katchori
namkeen aloo
stall tikija
stall patties
Or for more compact output:
select cat, group_concat(name, ', ')
from cats inner join
associations using(id) inner join
items using (iid)
group by cat
order by id;
Output:
cat group_concat(name, ', ')
----------- ------------------------
soup tomato, sour, corn
namkeen katchori, aloo
stall tikija, patties
I am not sure what you mean by "recycle view", maybe because I am working within pure SQLite (no other language, like you obviously use).
I hope one of the two representations suits you - or gets you on the way to achieve your goal.
MCVE foundation
(I did a .dump on my test environment, which I roughly cobbled together to demonstrate the idea. Please consider doing something like this for your next question involving SQLite. That makes it easier for the answerer and thereby faster for you. It also probably gets you a tighter fit of solution and often prevents misunderstandings.
Read Why should I provide an MCVE for what seems to me to be a very simple SQL query? if you like.):
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE table_1 (a int, b int, c int);
INSERT INTO table_1(a,b,c) VALUES(1,5,7);
INSERT INTO table_1(a,b,c) VALUES(2,10,14);
CREATE TABLE table_2 (a int, c int);
INSERT INTO table_2(a,c) VALUES(3,11);
INSERT INTO table_2(a,c) VALUES(6,22);
CREATE TABLE cats (id int, cat varchar(20));
INSERT INTO cats(id,cat) VALUES(1,'soup');
INSERT INTO cats(id,cat) VALUES(2,'namkeen');
INSERT INTO cats(id,cat) VALUES(3,'stall');
CREATE TABLE items (iid int, name varchar(20));
INSERT INTO items(iid,name) VALUES(1,'tomato');
INSERT INTO items(iid,name) VALUES(2,'sour');
INSERT INTO items(iid,name) VALUES(3,'corn');
INSERT INTO items(iid,name) VALUES(4,'katchori');
INSERT INTO items(iid,name) VALUES(5,'aloo');
INSERT INTO items(iid,name) VALUES(6,'tikija');
INSERT INTO items(iid,name) VALUES(7,'patties');
COMMIT;
i created a SQL Database and was able to safe data from three EditText Views and display it in a single TextView.
Then i thought it would be way better to display the data in a custom ListView, so i followed the developer guide and tried to display the data by a simpleCursorAdapter. But it did not work...i do not get any errors or anything, the data is just not shown...I guess there must be some missing connection between the Cursor, the Adapter or the DB...
i know that this kind of question is asked quite frequently, but i am unable to find my mistake, any help would be greatly appreciated:
MyDBHandlerFaecher.java:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
//Delete the line in which the COLUMN_NAME is equal to the input
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
FaecherActivity.java
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(), et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
//delete fach from database
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = new String[]{"_faechername", "_faecherraum", "_faecherfarbe"};
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = getContentResolver().query(Uri.parse(MyDBHandlerFaecher.TABLE_FAECHER),null, null, null, null);
SimpleCursorAdapter fachadapter = new SimpleCursorAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
}
}
i found code that works for me: i found out that the cursor in my DBHandler class was not empty, but it was empty in my FaecherActivity...so i created a custom SimpleCursorAdapter, and modified my code this way:
FaecherActivity:
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(),
et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = dbHandlerFaecher.databaseToStringArray();
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = dbHandlerFaecher.getWritableDatabase().rawQuery(" SELECT * FROM " + MyDBHandlerFaecher.TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist2");
}
else {
Log.d("Event", "Records do not exist2");
}
SimpleCursorAdapter fachadapter = new FaecherRowAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
MyDBHandlerFaecher:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
public String[] databaseToStringArray() {
String[] fromColumns = new String[]{COLUMN_NAME, COLUMN_RAUM, COLUMN_COLOR};
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty or not
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist");
}
else {
Log.d("Event", "Records do not exist");
}
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
cursor.moveToNext();
}
db.close();
return fromColumns;
}
}
FaecherRowAdapter:
public class FaecherRowAdapter extends SimpleCursorAdapter {
private int layout;
private Context context;
public FaecherRowAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
this.context = context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.faecher_row, parent, false);
bindView(v, context, c);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
int fachNameColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_NAME);
int fachRaumColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_RAUM);
int fachFarbeColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_COLOR);
String fachName = c.getString(fachNameColumn);
String fachRaum = c.getString(fachRaumColumn);
String fachFarbe = c.getString(fachFarbeColumn);
//set the name of the entry
TextView facheintrag = (TextView) v.findViewById(R.id.facheintrag);
if (facheintrag != null){
facheintrag.setText(fachName);
}
TextView raumeintrag = (TextView) v.findViewById(R.id.raumeintrag);
if (raumeintrag != null){
raumeintrag.setText(fachRaum);
}
TextView farbeintrag = (TextView) v.findViewById(R.id.farbeintrag);
if (farbeintrag != null){
farbeintrag.setText(fachFarbe);
}
}
}
Im struggling with a bit of my code for my database, I have managed to access the id number of the item i click however i cannot access any more of the data? How can i do this?
For example now i have my id number i want to display all of that data on that row in a seperate window but i cant seem to pull the data with the cursor
String itemselect = String.valueOf(spinner.getSelectedItem());
Toast.makeText(Developer.this, itemselect, Toast.LENGTH_LONG).show();
final Cursor cursor = mydb.getAllRows(itemselect);
startManagingCursor(cursor);
String[] fromfieldnames = new String[]{
DatabaseHelper.COL_1, DatabaseHelper.COL_2, DatabaseHelper.COL_3,
DatabaseHelper.COL_4, DatabaseHelper.COL_5, DatabaseHelper.COL_6 };
int[] toviewids = new int[]{R.id.textone, R.id.texttwo, R.id.textthree, R.id.textfour, R.id.textfive, R.id.textsix};
final SimpleCursorAdapter mycursoradapter = new SimpleCursorAdapter(this, R.layout.listtext, cursor, fromfieldnames, toviewids);
listView.setAdapter(mycursoradapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Long string = mycursoradapter.getItemId(position);
Toast.makeText(Developer.this, string.toString(),Toast.LENGTH_LONG).show();
return true;
}
});
There are no errors in this code I just need to try and add this extra functionality
Thanks in advance M.
The data is stored in your Cursor at the row position position in onItemLongClick. Use the moveToPosition() method on cursor, and retrieve the values:
String one, two, three;
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
cursor.moveToPosition(position);
one = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_1));
two = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_2));
// Etc...
}
};
use the cursor in the following way:
public Cursor getRowByID(int ID) {
SQLiteDatabase db = this.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"id, col_1, col_2, col_3"};
String sqlTables = "your_table";
String filter = "id= "+ID;
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, filter,null, null,
null, null, null);
c.moveToFirst();
return c;
}
public Cursor Retrive_SubCategory1(String id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select "
+ "column_Name1 , "+"column_name2 " + " from "
+"table_name " + " where "
+ "column_name " + "='" + id+ "'",
null);
return cursor;
}
I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview.
Now I want to delete values by position (for example, if i click listview's 4th item i would to delete full this items)
This is my code:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
My Adapter Code:
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and my Main Java code:
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
int a;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
a = Integer.parseInt(holder.counter.getText().toString());
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
dbHelper.close();
cAdapter.notifyDataSetChanged();
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
cAdapter.notifyDataSetChanged();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
I found one example about how to delete title but it's not working.
How could I delete user by position in listview 'onclick' listener?
Any help would be great, thanks
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
You'll need to use the table name here, if all else is correct.
What is the better way to store a returned query basing from the table creation below?+
String CREATE_ITEMS = "CREATE TABLE " + TABLE_ITEMS + "(" + KEY_ID
+ " TEXT," + KEY_NAME + " TEXT," + KEY_PRICE + " TEXT," + KEY_ITEM_ID + " TEXT,"
+ KEY_IMAGE_PATH + " NVARCHAR(1000)" +")";
The reason why I need the records from the TABLE_ITEMS because I need to display it in the GridView approach in displaying images using KEY_IMAGE_PATH. But my main problem is how can I store all the records from each columns, so that I can track what is the price and the image_path of each item displayed in the grid view?
public String[] getImagePath(){
List<String> paths = new ArrayList<String>();
String selectQuery = "SELECT "+ KEY_IMAGE_PATH +" FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
paths.add(cursor.getString(0).toString());
Log.d("getPathImage:", cursor.getString(0).toString());
} while (cursor.moveToNext());
}
db.close();
//This should be returned as array string
return paths.toArray(new String[paths.size()]);
}
It should be,
-itemid
-sellingPrice
-keyid
-imagePath[position]
-keyname
LoadMainMenuActivty
paths = db.getImagePath();
intent.putExtra(Extra.IMAGES, paths);
ImageGridActivity
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Extra.IMAGES);
//The images in only displayed but not the other details.
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text1);
holder.image = (ImageView) view.findViewById(R.id.imageView1);
holder.br = (RatingBar) view.findViewById(R.id.rBarHere);
holder.br.setIsIndicator(true);
holder.br.setFocusable(false);
holder.br.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
//Toast.makeText(getBaseContext(), "Rating:"+rating, Toast.LENGTH_SHORT).show();
}});
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("NAAA NA");
holder.br.setStepSize(1);
holder.br.setFocusable(false);
Log.d("Image Path Value in GridView: ", imageUrls[position].toString());
imageLoader.displayImage(imageUrls[position], holder.image, options);
return view;
}
The returned query should be a String array so I figured it out using the code below.
From the database handler I have to return List<Menu> getItemsAsArray(String Table_Name), then
I have to put it in a loop to access the returned list and put it in a mashmap.
Then store it, ArrayList<HashMap<String, ?>> values2.
Then finally I have to access it through: values2.get(position).get(TAG).toString()