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;
Related
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);
}
how to add second column value of same or other table in another spinner from sqlite database using button click in android studio
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
});
Perhaps consider the following working example.
This consists of 2 spinners and 3 buttons. The buttons controlling from which of the 3 tables the data is extracted for the 2nd spinner.
The trick, as such, used is to use AS to utilise a standard column name, irrespective of the actual column name. The one difference is that this rather than using a normal adapter, it utilises a CursorAdapter (SimpleCursorAdapter as it's quite flexible) and thus you can extract the data directly.
First the SQLite side i.e. the class that extends SQLiteOpenHelper :-
class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE1_TABLE = "_table1";
public static final String TABLE1_ID_COL = BaseColumns._ID;
public static final String TABLE1_NAME_COL = "_name";
public static final String TABLE1_DESC_COL = "_desc";
private static final String TABLE1_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE1_TABLE + "(" +
TABLE1_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE1_NAME_COL + " TEXT UNIQUE" +
"," + TABLE1_DESC_COL + " TEXT " +
");";
public static final String TABLE2_TABLE = "_table2";
public static final String TABLE2_ID_COL = BaseColumns._ID;
public static final String TABLE2_TABLE1_ID_MAP_COL = "_table1_id_map";
public static final String TABLE2_NAME_COL = "_name";
private static final String TABLE2_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE2_TABLE + "(" +
TABLE2_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE2_TABLE1_ID_MAP_COL + " INTEGER " +
"," + TABLE2_NAME_COL + " TEXT" +
");";
public static final String TABLE3_TABLE = "_table3";
public static final String TABLE3_ID_COL = BaseColumns._ID;
public static final String TABLE3_TABLE2_ID_MAP_COL = "_table2_id_map";
public static final String TABLE3_NAME_COL = "_name";
private static final String TABLE3_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE3_TABLE +"(" +
TABLE3_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE3_TABLE2_ID_MAP_COL + " INTEGER " +
"," + TABLE3_NAME_COL + " TEXT " +
");";
private static volatile DBHelper INSTANCE;
private SQLiteDatabase db;
public static final String SPINNER_COLUMN1 = "_spc1";
public static final String SPINNER_COLUMN2 = "_spc2";
private DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (INSTANCE==null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE1_CREATE_SQL);
db.execSQL(TABLE2_CREATE_SQL);
db.execSQL(TABLE3_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertTable1Row(String name,String description) {
ContentValues cv = new ContentValues();
cv.put(TABLE1_NAME_COL,name);
cv.put(TABLE1_DESC_COL,description);
return db.insert(TABLE1_TABLE,null,cv);
}
public long insertTable2Row(String name, long table1_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE2_NAME_COL,name);
cv.put(TABLE2_TABLE1_ID_MAP_COL,table1_id);
return db.insert(TABLE2_TABLE,null,cv);
}
public long insertTable3Row(String name, long table2_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE3_NAME_COL,name);
cv.put(TABLE3_TABLE2_ID_MAP_COL,table2_id);
return db.insert(TABLE3_TABLE,null,cv);
}
public Cursor getSpinnerData(String table, long map) {
String[] columns = new String[]{};
String whereClause = "";
String[] whereArgs = new String[]{String.valueOf(map)};
switch (table) {
case TABLE1_TABLE:
columns = new String[]{TABLE1_ID_COL,TABLE1_NAME_COL + " AS " + SPINNER_COLUMN1,TABLE1_DESC_COL + " AS " + SPINNER_COLUMN2};
whereClause = "";
break;
case TABLE2_TABLE:
columns = new String[]{TABLE2_ID_COL ,TABLE2_NAME_COL + " AS " + SPINNER_COLUMN1,"'-' AS " + SPINNER_COLUMN2};
whereClause = TABLE2_TABLE1_ID_MAP_COL + "=?";
break;
case TABLE3_TABLE:
columns = new String[]{TABLE3_ID_COL, TABLE3_NAME_COL + " AS " + SPINNER_COLUMN1,"'~' AS " + SPINNER_COLUMN2};
whereClause = TABLE3_TABLE2_ID_MAP_COL + "=?";
break;
}
if (map < 0) {
whereClause="";
whereArgs = new String[]{};
}
if (columns.length > 0) {
return db.query(table,columns,whereClause,whereArgs,null,null,null);
} else {
return db.query(TABLE1_TABLE,new String[]{"0 AS " + TABLE1_ID_COL + ",'ooops' AS " + SPINNER_COLUMN1,"'ooops' AS " + SPINNER_COLUMN2},null,null,null,null,null,"1");
}
}
}
as said there are three tables
a singleton approach has been utilised for the DBHelper
the most relevant aspect in regards to switching spinner data is the getSpinnerData function, which takes two parameters, the most relevant being the first the tablename which drives the resultant query.
Note the use of BaseColumns._ID ALL Cursor adapters must have a column name _id (which is what BaseColumns._ID resolves to). The column should be an integer value that uniquely identifies the row.
the 2nd parameter caters for the selection of only related data, but a negative is used to ignore this aspect.
The Activity "MainActivity" used to demonstrate is :-
public class MainActivity extends AppCompatActivity {
Button btn1, btn2, btn3;
Spinner sp1,sp2;
String[] spinnerColumns = new String[]{DBHelper.SPINNER_COLUMN1,DBHelper.SPINNER_COLUMN2};
SimpleCursorAdapter sca1,sca2;
String sp1_table_name = DBHelper.TABLE1_TABLE;
String sp2_table_name = DBHelper.TABLE2_TABLE;
Cursor csr1, csr2;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = this.findViewById(R.id.button1);
btn2 = this.findViewById(R.id.button2);
btn3 = this.findViewById(R.id.button3);
sp1 = this.findViewById(R.id.spinner1);
sp2 = this.findViewById(R.id.spinner2);
dbHelper = DBHelper.getInstance(this);
Cursor test4Data = dbHelper.getWritableDatabase().query(DBHelper.TABLE1_TABLE,null,null,null,null,null,null, "1");
if (test4Data.getCount() < 1) {
addSomeData();
}
test4Data.close();
sp1_table_name = DBHelper.TABLE1_TABLE;
sp2_table_name = DBHelper.TABLE2_TABLE;
setUpButtons();
setOrRefreshSpinner1();
setOrRefreshSpinner2();
}
void setUpButtons() {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE1_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE2_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE3_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
}
void setOrRefreshSpinner1() {
csr1 = dbHelper.getSpinnerData(sp1_table_name,-1);
if (sca1==null) {
sca1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr1,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp1.setAdapter(sca1);
} else {
sca1.swapCursor(csr1);
}
}
void setOrRefreshSpinner2() {
csr2 = dbHelper.getSpinnerData(sp2_table_name,-1);
if (sca2==null) {
sca2 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr2,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp2.setAdapter(sca2);
} else {
sca2.swapCursor(csr2);
}
}
private void addSomeData() {
long n1 = dbHelper.insertTable1Row("NAME001","The first name.");
long n2 = dbHelper.insertTable1Row("NAME002","The second name.");
long n3 = dbHelper.insertTable1Row("NAME003","The third name");
long t2n1 = dbHelper.insertTable2Row("CHILDNAME001",n1);
long t2n2 = dbHelper.insertTable2Row("CHILDNAME002",n2);
long t2n3 = dbHelper.insertTable2Row("CHILDNAME003", n3);
dbHelper.insertTable3Row("GRANDCHILDNAME001",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME002",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME003",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME004",t2n2);
dbHelper.insertTable3Row("GRANDCHILDNAME005",t2n3);
}
}
Result
The above when run starts of with :-
With the first spinner dropdown shown :-
With the second spinner dropdown shown :-
If Button1 is clicked then both spinners (i.e. spinner2 has been changed to select data from Table1 rather than Table2) show data from Table1 (useless but for demonstration) :-
If Button3 is clicked then data from Table3 is displayed in the second spinner:-
Clicking Button2 shows data from Table2.
Of course the principle could be applied in many different ways.
My adapters were not set so I made below changes and got expected result.
// RETRIEVE
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, nos);
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
sp1.setAdapter(adapter1);
sp2.setAdapter(adapter2);
});
So its to looks like this:
SCREENSHOT
But when I click add or less button its returning the size of the whole list.
In this case its returns 2(because the otitles.size() returns 2) Like under the item that I clicked appears another item from the list.
PARENT RecyclerView Adapter:
public class recyclercart extends RecyclerView.Adapter<recyclercart.myViewHolder> {
Context context;
ArrayList<String> list;
public static View.OnClickListener onclickup;
public static View.OnClickListener onclickdown;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oid = new ArrayList<>();
Cursor gettitle, getimage, getingridients, getdependencies,getquantities, getprices, getstartprice, getbrand, getid;
ArrayList<Integer> postoremove= new ArrayList<>();
ProgressBar progressBar;
SQLiteDatabase database;
public recyclercart(Context c, ProgressBar progressBar){
context=c;
this.progressBar=progressBar;
SQLHelper helper = new SQLHelper(context);
database = helper.getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM "+SQLHelper.DATABASE_TABLE, null);
list =new ArrayList<>();
cursor.moveToFirst();
do {
String lol = cursor.getString(cursor.getColumnIndex(SQLHelper.BRAND_NAME));
list.add(lol.substring(0,lol.length()-5));
}while (cursor.moveToNext());
if(cursor.moveToLast()) {
postoremove.clear();
Log.d("glavniy", "LIST: " + list.toString());
list = new ArrayList<>(removeDuplicates(list));
}
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.templatecart, parent, false );
return new myViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
otitles.clear();
oimages.clear();
oingridients.clear();
odependencies.clear();
oprices.clear();
oquantities.clear();
ostartprices.clear();
obrand.clear();
oid.clear();
Cursor cur = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "+SQLHelper.BRAND_NAME+" LIKE '%"+
list.get(position)+"%'", null);
SQLHelper helper = new SQLHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
gettitle = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getimage = database.rawQuery("SELECT "+SQLHelper.IMAGESRC_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getingridients = database.rawQuery("SELECT "+SQLHelper.INGRIDIENTS_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getdependencies = database.rawQuery("SELECT "+SQLHelper.DEPENDENCIES_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getprices = database.rawQuery("SELECT "+SQLHelper.PRICE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getquantities = database.rawQuery("SELECT "+SQLHelper.QUANTITY_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getstartprice = database.rawQuery("SELECT "+SQLHelper.START_PRICE+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getbrand = database.rawQuery("SELECT "+SQLHelper.BRAND_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getid = database.rawQuery("SELECT "+SQLHelper.KEY_ID+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
if (gettitle.moveToFirst() && getimage.moveToNext() && getingridients.moveToFirst() && getdependencies.moveToFirst()
&& getprices.moveToFirst() && getquantities.moveToFirst() && getstartprice.moveToFirst() && getbrand.moveToFirst() && getid.moveToFirst()) {
do {
otitles.add(gettitle.getString(gettitle.getColumnIndex(SQLHelper.TITLE_NAME)));
oimages.add(getimage.getString(getimage.getColumnIndex(SQLHelper.IMAGESRC_NAME)));
oingridients.add(getingridients.getString(getingridients.getColumnIndex(SQLHelper.INGRIDIENTS_NAME)));
odependencies.add(getdependencies.getString(getdependencies.getColumnIndex(SQLHelper.DEPENDENCIES_NAME)));
oprices.add(getprices.getString(getprices.getColumnIndex(SQLHelper.PRICE_NAME)));
oquantities.add(getquantities.getString(getquantities.getColumnIndex(SQLHelper.QUANTITY_NAME)));
ostartprices.add(getstartprice.getString(getstartprice.getColumnIndex(SQLHelper.START_PRICE)));
obrand.add(getbrand.getString(getbrand.getColumnIndex(SQLHelper.BRAND_NAME)));
oid.add(getid.getString(getid.getColumnIndex(SQLHelper.KEY_ID)));
Log.d("glavniy", String.valueOf(ostartprices));
} while (gettitle.moveToNext() && getimage.moveToNext() && getingridients.moveToNext() && getdependencies.moveToNext()
&& getprices.moveToNext() && getquantities.moveToNext() && getstartprice.moveToNext() && getbrand.moveToNext() && getid.moveToNext());
}
if(gettitle.moveToLast()) {
Log.d("glavniy", "MOVETOLAST");
holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
holder.recyclerView.setAdapter(new recyclerOrdersAdapter(context, otitles, oimages, oingridients, oquantities, oprices, ostartprices
, obrand, odependencies, oid));
}
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("resources");
reference.child(list.get(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
holder.title.setText(snapshot.child("nameBrand").getValue().toString());
Glide.with(context).load(snapshot.child("imageBrand").getValue().toString()).into(holder.imageView);
try {
if(recyclerSearchRecycler.timeCheck(snapshot.child("times").child("startTime").getValue().toString(),
snapshot.child("times").child("closeTime").getValue().toString())){
holder.open.setText("OPEN");
}else {holder.open.setText("CLOSED");}
} catch (ParseException e) {
e.printStackTrace();
}
reference.child(list.get(position)).child("addresses").addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ArrayList<String> addresses = new ArrayList<>();
addresses.add(dataSnapshot.getValue().toString());
Log.d("glavniy", dataSnapshot.getValue().toString());
if(addresses.size()==snapshot.getChildrenCount()) {
try {
float distance = activityBrandPage.getNearestRest(addresses, context);
Log.d("glavniy", "DIST: " + distance);
if (distance <= 1000) {
progressBar.setVisibility(View.INVISIBLE);
holder.delivery.setText("Delivery: 400 AMD");
} else if (distance > 1000 && distance <= 2000) {
holder.delivery.setText("Delivery: 500 AMD");
progressBar.setVisibility(View.INVISIBLE);
} else if (distance > 2000 && distance <= 3000) {
holder.delivery.setText("Delivery: 600 AMD");
} else if (distance > 3000 && distance <= 4000) {
holder.delivery.setText("Delivery: 700 AMD");
progressBar.setVisibility(View.INVISIBLE);
}
if (search.prog != null) {
search.prog.setVisibility(View.INVISIBLE);
}
} catch (IOException e) {
e.printStackTrace();
progressBar.setVisibility(View.VISIBLE);
Toast.makeText(context, "Failed, please restart", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class myViewHolder extends RecyclerView.ViewHolder {
TextView title, delivery, open;
ImageView imageView;
public static RecyclerView recyclerView;
public myViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.ivBrandCart);
recyclerView=itemView.findViewById(R.id.recyclerMainCart);
title=itemView.findViewById(R.id.tvBrandCart);
delivery=itemView.findViewById(R.id.tvdelivery);
open=itemView.findViewById(R.id.opentv);
}
}
CHILD RecyclerView Adapter:
public class recyclerOrdersAdapter extends RecyclerView.Adapter<recyclerOrdersAdapter.myViewHolder> {
public static Context context;
SQLiteDatabase database;
public static int pos;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oids = new ArrayList<>();
#SuppressLint("Recycle")
public recyclerOrdersAdapter(Context c, ArrayList<String> titles, ArrayList<String> images, ArrayList<String> ingridients,
ArrayList<String> quantities, ArrayList<String> prices, ArrayList<String> startprices, ArrayList<String> brands,
#Nullable ArrayList<String> dependencies, ArrayList<String> ids){
System.out.println("hi");
otitles=new ArrayList<>(titles);
oimages= new ArrayList<>(images);
oingridients=new ArrayList<>(ingridients);
oquantities=new ArrayList<>(quantities);
oprices=new ArrayList<>(prices);
ostartprices=new ArrayList<>(startprices);
obrand=new ArrayList<>(brands);
oids=new ArrayList<>(ids);
assert dependencies != null;
odependencies=new ArrayList<>(dependencies);
context = c;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.templateorders, parent, false );
return new myViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
System.out.println("hello n");
if(obrand.size()!=0) {
String title = otitles.get(position);
String image = oimages.get(position);
String ingridient = oingridients.get(position);
String dependencie = odependencies.get(position);
String priceik = oprices.get(position);
String quanik = oquantities.get(position);
ingridient = ingridient.replaceAll("[^a-zA-Z0-9, ]", "");
if (ingridient.contains("null, ")) {
ingridient = ingridient.replaceAll("null, ", "");
} else if (ingridient.contains("null,")) {
ingridient = ingridient.replaceAll("null,", "");
} else {
ingridient = ingridient.replaceAll("null", "");
}
dependencie = dependencie.replaceAll("[^a-zA-Z0-9, ]", "");
System.out.println("ingridients " + ingridient);
holder.title.setText(title);
Glide.with(context).load(image).placeholder(R.drawable.elipsis).into(holder.imageView);
holder.ingridients.setText(ingridient);
if(odependencies.get(position)!=null) {
holder.dependencies.setText(dependencie);
}
if(!priceik.contains("$")) {
holder.price.setText(priceik + "$");
}else {
holder.price.setText(priceik);
}
holder.quantity.setText(quanik);
holder.startprice.setText(ostartprices.get(position));
holder.id.setText(oids.get(position));
SQLHelper helper = new SQLHelper(context);
database = helper.getWritableDatabase();
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
Log.d("glavniy", "position is" + String.valueOf(position));
SQLHelper helper = new SQLHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.execSQL("DELETE FROM " + SQLHelper.DATABASE_TABLE + " WHERE (" + SQLHelper.KEY_ID +
"='" + holder.id.getText().toString() + "')");
notifyItemRemoved(position);
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
});
holder.up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
int o = Integer.parseInt(holder.quantity.getText().toString())+1;
holder.quantity.setText(String.valueOf(o));
int o1 = Integer.parseInt(holder.startprice.getText().toString()) * Integer.parseInt(holder.quantity.getText().toString());
holder.price.setText(o1 + "$");
Log.d("glavniy", "UPDATED");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
});
holder.down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Integer.parseInt(holder.quantity.getText().toString()) != 1) {
holder.quantity.setText(String.valueOf(Integer.parseInt(holder.quantity.getText().toString())-1));
int o1 = Integer.parseInt(holder.price.getText().toString().replace("$","")) - Integer.parseInt(holder.startprice.getText().toString());
holder.price.setText(o1 + "$");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
}
});
}
}
#Override
public int getItemCount() {
return otitles.size();
}
#SuppressLint("StaticFieldLeak")
public class myViewHolder extends RecyclerView.ViewHolder {
public TextView title, price, ingridients, dependencies, up,down, quantity, startprice, id;
public ImageView imageView;
public ImageView delete;
public myViewHolder(#NonNull View itemView) {
super(itemView);
id=itemView.findViewById(R.id.textView7);
startprice=itemView.findViewById(R.id.textView6);
quantity = itemView.findViewById(R.id.ordersQuanity);
up=itemView.findViewById(R.id.upBtn);
down=itemView.findViewById(R.id.downBtn);
delete=itemView.findViewById(R.id.removeButton);
title = itemView.findViewById(R.id.titleOfOrder);
price = itemView.findViewById(R.id.priceOfOrder);
imageView=itemView.findViewById(R.id.imageOfOrde);
ingridients = itemView.findViewById(R.id.ingridientsOfOrder);
dependencies = itemView.findViewById(R.id.dependenciesOfOrder);
}
}
}
How can I make to return exactly size of list that PARENT RecyclerView sends (of that position)?
Oh... This is really hard to read.
I will try to give you some tips for better architecture. I hope you are fine with it.
Why are you using so many lists? Why you don't make one list of custom madr classes with all the data like title, image, ingredient itp.
Why you name the type of class recyclercart instead of RecyclerCard. In Kotlin and in Java programmers have not written rule that classes should be named from big letter and in camelCase stale.
The other thing is that you melted together using database and uploadung data into the view processes. It is not good. It would be better to have other class like DatabaseManager or something like this, which will make the job of taking data from the database etc. If you will do that your RecyclerViewAdapter will get list of ready items in the constructor and the only responsibility of this class will be to show the data in the views. The code will be simplified and maybe the mistake will be more visible. If you want to upload children data dynamically (during scrolling) you cab, but the code for it should be places in the DatabaseManager or Helper, too. If number of data is not big- it could be better to upload it before adapter is created even and just put Map<Item,List instead.
I would also check the way of using SQLiteHelper. I am not sure, but something tells me that you are creating few databases in one program. It can be damgerous. Please, just check it. Remember to create database once and just connect to it few times. About this one I am not sure. I have to less time to investigate yourt code.
About my tips: checkout SOLID; you will have a lot more clear architecture.
Ok finally I found solution. Thats pretty funny but problem was that ArrayLists were static. So I just removed static field and everything works fine now.
So im trying to get 3 of my columns from my database from sqlite to be put into my arraylist then displayed into a list view but at the moment it is only displaying the quantity. Eg: Name: 1 Quantity: 1 Type: 1
But I want it to display all of the other columns instead of just the quantity so the output would actually be: Name: Milk Quantity: 1 Type: Ingredient
Does anyone know how to do this?
InventoryStatus class:
public class InventoryStatus extends AppCompatActivity {
DatabaseHelper myDB;
int currentPosition = 0;
private ArrayList<String> fullList;
private ArrayList<String> displayedList;
ArrayAdapter<String> listAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_status);
listView = findViewById(R.id.listViewStock);
Button btNext = findViewById(R.id.buttonNext);
Button btPrevious = findViewById(R.id.buttonPrevious);
myDB = new DatabaseHelper(this);
Cursor data = myDB.getAllData();
fullList = new ArrayList<>();
displayedList = new ArrayList<>();
for (int i = 0; i < 5; i++)
{
fullList.add("Name: " + i + "Quantity: " + i + "Type: " + i);
}
if (fullList.size() == 0)
{
Toast.makeText(this, "No data found", Toast.LENGTH_SHORT).show();
}
else // fullList isn't empty show first 5 items in ListView
{
setDisplayListPosition();
listView.setAdapter(listAdapter);
}
btNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) // change current position and refresh ListView
{
currentPosition += 5;
if (currentPosition > fullList.size()) currentPosition -= 5;
else
setDisplayListPosition();
}
});
btPrevious.setOnClickListener(new View.OnClickListener() // change current position and refresh ListView
{
public void onClick(View view) {
currentPosition -= 5;
if (currentPosition < 0) currentPosition = 0;
else
setDisplayListPosition();
}
});
}
private void setDisplayListPosition() // helper function which refresh ListView based on `currentPos`
{
displayedList.clear();
for (int i = 0; i < 5 && i + currentPosition < fullList.size(); i++) {
displayedList.add(fullList.get(currentPosition + i)); // ad 5 items from finalList to displayedList
}
listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
displayedList
);
}
}
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Inventory.db";
public static final String TABLE_NAME = "Inventory_table";
public static final String COL1 = "ID";
public static final String COL2 = "Name";
public static final String COL3 = "Quantity";
public static final String COL4 = "Type";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " Name TEXT, Quantity Text, Type Text)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String Name, String Quantity, String Type){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, Name);
contentValues.put(COL3, Quantity);
contentValues.put(COL4, Type);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
// Gets all data
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("select * from " + TABLE_NAME, null);
return data;
}
// Deletes all data
public String deletedata(){
SQLiteDatabase myDB = this.getWritableDatabase();
myDB.delete(TABLE_NAME, null, null);
myDB.close();
return null;
}
}
Change this :
for (int i = 0; i < 5; i++)
{
fullList.add("Name: " + i + "Quantity: " + i + "Type: " + i);
}
to :
if(cursor.moveToFirst())
for(int i=0; i<5 ;i++){
fullList.add("Name: " + cursor.getString(1) + "Quantity: " + cursor.getString(2) + "Type: " + cursor.getString(3));
if(!cursor.moveToNext())
break;
}
I've been trying to populate an Android Listview from a SQLite database using the code below. I have successfully done this from an array inside the same class. But in this case I'm attempting to populate it from a String array I have returned from another class. I'm new to this so am possibly doing this completely wrong. If anyone could look at the code and advise to what I'm doing wrong that'd be brilliant.
Any help would be really appreciated with this as I'm under serious pressure to get it finished, Thanks!
LoginActivity Class
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUserName = (EditText)findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
try{
if(username.length() > 0 && password.length() >0)
{
DBUserAdapter dbUser = new DBUserAdapter(LoginActivity.this);
dbUser.open();
int UID = dbUser.Login(username, password);
if(UID != -1)
{
// TEST
//int UID = dbUser.getUserID(username, password);
//getSitesByClientname(UID);
// END TEST
// MY TEST CODE TO CHANGE ACTIVITY TO CLIENT SITES
Intent myIntent = new Intent(LoginActivity.this, ClientSites.class);
//Intent myIntent = new Intent(getApplicationContext(), ClientSites.class);
myIntent.putExtra("userID", UID);
startActivity(myIntent);
//finish();
// END MY TEST CODE
//Cursor UserID = dbUser.getUserID();
Toast.makeText(LoginActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(LoginActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e)
{
Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Method from DBHelper Class to return String Array
public String[] getSitesByClientname(String id) {
String[] args={id};
//return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
// loop through all rows and adding to array
int count;
count = myCursor.getCount();
final String[] results = new String[count];
results[0] = new String();
int i = 0;
try{
if (myCursor.moveToFirst()) {
do {
results[i] = myCursor.getString(myCursor.getColumnIndex("client_sitename"));
} while (myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
// return results array
return results;
ClientSites Class
public class ClientSites extends ListActivity {
public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
//private Cursor ourCursor = null;
private ArrayAdapter<String> adapter=null;
//#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
//dbHelper.openDataBase();
dbHelper.open();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
Any help with this would be great, Thanks!
Create own project with few activities. Start working with sqlite database
Create new application. Create login activity and DB helper. Trying to upload dada from DB. Reseach and development
Here is an example how to work with SQLite DB.
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper instance;
private static final String DATABASE_NAME = "UserClientBase";
private static final int DATABASE_VERSION = 1;
public static interface USER extends BaseColumns {
String TABLE_NAME = "userTable";
String NAME = "userName";
String PASSWORD = "userPassword";
}
public static interface CLIENT extends BaseColumns {
String TABLE_NAME = "clientTable";
String NAME = "clientName";
String USER_ID = "userId";
}
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT";
private static final String CREATE_TABLE_USER = CREATE_TABLE + USER.TABLE_NAME + " (" + USER._ID
+ " INTEGER PRIMARY KEY, " + USER.NAME + " TEXT " + UNIQUE + ", " + USER.PASSWORD + " TEXT);";
private static final String CREATE_TABLE_CLIENT = CREATE_TABLE + CLIENT.TABLE_NAME + " (" + CLIENT._ID
+ " INTEGER PRIMARY KEY, " + CLIENT.NAME + " TEXT UNIQUE, " + CLIENT.USER_ID + " INTEGER);";
private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_CLIENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE + USER.TABLE_NAME);
db.execSQL(DROP_TABLE + CLIENT.TABLE_NAME);
onCreate(db);
}
public long createUser(String newUserName, String newUserPassword) {
ContentValues values = new ContentValues();
values.put(USER.NAME, newUserName);
values.put(USER.PASSWORD, newUserPassword);
return getWritableDatabase().insert(USER.TABLE_NAME, null, values);
}
public long createClient(long userId, String newClientName) {
ContentValues values = new ContentValues();
values.put(CLIENT.USER_ID, userId);
values.put(CLIENT.NAME, newClientName);
return getWritableDatabase().insert(CLIENT.TABLE_NAME, null, values);
}
public boolean isCorrectLoginPassword(String login, String password) {
Cursor userListCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER.TABLE_NAME + " WHERE " + USER.NAME + " =? AND " + USER.PASSWORD
+ " =?", new String[] { login, password });
if ((userListCursor != null) && (userListCursor.getCount() > 0)) {
return true;
} else {
return false;
}
}
public Cursor getUserClientList(String userName) {
Cursor userClientList = getReadableDatabase().rawQuery(
"SELECT * FROM " + CLIENT.TABLE_NAME + " INNER JOIN " + USER.TABLE_NAME
+ " ON " + CLIENT.USER_ID + " = " + USER.TABLE_NAME + "." + USER._ID + " WHERE "
+ USER.NAME + " =?", new String[] { userName });
return userClientList;
}
}
Example of login button click listener.
String login = loginEdt.getText().toString();
String password = passwordEdt.getText().toString();
boolean loginSuccess = databaseHelper.isCorrectLoginPassword(login, password);
if(loginSuccess) {
Intent clientListIntent = new Intent(LoginActivity.this, ClientListActivity.class);
clientListIntent.putExtra(ClientListActivity.EXTRAS_LOGIN, login);
startActivity(clientListIntent);
} else {
Toast.makeText(LoginActivity.this, "Incorrect login/password", Toast.LENGTH_SHORT).show();
}
And example of listview with data from sql:
clientLv= (ListView)findViewById(R.id.listClient);
login = getIntent().getExtras().getString(EXTRAS_LOGIN);
dbHelper = DBHelper.getInstance(this);
Cursor clientList = dbHelper.getUserClientList(login);
adapter = new SimpleCursorAdapter(this, R.layout.row_client, clientList, new String[]{DBHelper.CLIENT.NAME}, new int[]{R.id.txtClientName} , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
clientLv.setAdapter(adapter);