I have a problem:
I implemented a method for call the groups and childs from databases, after put all in a expandablelist, until then, everything was fine all data came out as expected.
But when I call a Toast message with clicked child into onChildClick method, the Toast show me the group instead of the child (the group is wrong too)
Can anyone help me find where I went wrong?
Remembering: the output of the expandable list came out correctly
This my active with expandable list:
public class ShowDeckActivity extends ExpandableListActivity {
/** Called when the activity is first created. */
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carddeck);
try{
SimpleExpandableListAdapter expListAdapter =
new SimpleExpandableListAdapter(
this,
createGroupList(),
R.layout.group_row,
new String[] { "Group Item" },
new int[] { R.id.row_name },
createChildList(),
R.layout.child_row,
new String[] {"Sub Item"},
new int[] { R.id.grp_child}
);
setListAdapter( expListAdapter );
}catch(Exception e){
System.out.println("Errrr +++ " + e.getMessage());
}
}
#SuppressWarnings("rawtypes")
private List createGroupList(){
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
return db.getGroupList();
}
#SuppressWarnings("rawtypes")
private List createChildList(){
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
return db.getChildList();
}
public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
String nameLable = parent.getItemAtPosition(childPosition).toString();
// Debug
// System.out.println("Inside onChildClick at groupPosition = " + (groupPosition + 1) +" Child clicked at position " + (childPosition + 1));
Toast.makeText(getApplicationContext(), nameLable, Toast.LENGTH_SHORT).show();
return true;
}
}
This my DatabaseHandler methods:
public List getGroupList() {
String SQL = "SELECT * FROM assunto";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(SQL, null);
int numeroColunas = cursor.getCount();
ArrayList result = new ArrayList();
if(cursor.moveToFirst()){
do{
HashMap m = new HashMap();
m.put( "Group Item", cursor.getString(2) );
result.add( m );
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return (List)result;
}
//#SuppressWarnings({ "unchecked", "rawtypes" })
public List getChildList(){
String sqlAssunto = "SELECT * FROM assunto";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursorAssunto = db.rawQuery(sqlAssunto, null);
ArrayList result = new ArrayList();
if(cursorAssunto.moveToFirst()){
do { // Loop begin 1
String assuntoID = cursorAssunto.getString(0);
String sqlDeck = "SELECT * FROM deck WHERE table_assuntos_id=" + assuntoID;
Cursor cursorDeck = db.rawQuery(sqlDeck, null);
ArrayList secList = new ArrayList();
if(cursorDeck.moveToFirst()){ // Move-se nos decks
do {
// Loop Begin 2
HashMap child = new HashMap();
child.put( "Sub Item", cursorDeck.getString(2) );
secList.add( child );
} while (cursorDeck.moveToNext()); // Loop end 2
}
result.add( secList );
} while (cursorAssunto.moveToNext()); // Loop end 1
}
cursorAssunto.close();
db.close();
return result;
}
The expandable list output(It's as expected):
GROUP1
- SUB ITEM1_1
- SUB ITEM1_2
- SUB ITEM1_3
GROUP2
- SUB ITEM2_1
- SUB ITEM2_2
GROUP3
- SUB ITEM3_1
GROUP4
[..]
Example:
When I click in (GROUP3 x SUB ITEM3_1)
The wrong Toast message is:
{Group Item= GROUP1}
... instead of the expected:
{Sub Item=SUB ITEM3_1}
Anyone have idea what's happened?
Thanks in advance!
==================[EDITED, I FOUND THE SOLUTION]=========================
To fix the problem you have to instantiate a ExpandableListAdapter, some like this:
ExpandableListAdapter adap = parent.getExpandableListAdapter();
String adaptar = adap.getChild(groupPosition, childPosition).toString(); // This get the correct child name
Thanks for help!
Related
I am trying to create a filter for a ListView of Employees.
I am collecting the spinner value in the MainActivity which works as it is displayed using Toast
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//first, we have to retrieve the item position as a string
// then, we can change string value into integer
String item_position = String.valueOf(position);
positonInt = Integer.valueOf(item_position);
Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Later in the MainActivity I set the adapter by calling the methodgetEmployeeList
List<Employee> employeeList = dataBaseHelper.getEmployeeList(positonInt);
adaptor = new EmployeeAdaptor(MainActivity.this, employeeList);
empListView.setAdapter(adaptor);
I am trying to achieve this by calling the method below, depending the Spinner position value is passed to the method getEmployeeList() which is then used in a switch statement to create the query to populate the ListView
public List<Employee> getEmployeeList(int spinnerPostion) {
switch (spinnerPostion) {
case 1: spinnerPostion = 0;
query = "SELECT * FROM " + EMP_TABLE
+ " ORDER BY " + PROFIT + " DESC ";
break;
}
List<Employee> employeesList = new ArrayList<>();
//Referencing the active database to read infromation
SQLiteDatabase db = this.getReadableDatabase();
//Executing the query
// -Using a Cursor so we can iterate through all readable data in the db
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
//If there are results loop through and create a new Item
//for every item in the db
do {
int employeeID = cursor.getInt(0);
String employeeName = cursor.getString(1);
String employeeSecondName = cursor.getString(2);
int profit = cursor.getInt(3);
Employee menu_emp = new Employee(employeeID, employeeName, employeeSecondName, profit);
employeesList.add(menu_emp);
} while (cursor.moveToNext());
} else {
// Empty List contains no Items
}
//Closing connection to the database and cursor
cursor.close();
db.close();
return employeesList;
}
The method getEmployeeList() works without the switch statement and populates the list when I just set String query but I am getting errors when I try to do this using the switch statement.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dropit/com.example.dropit.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
Are you sure the value you are getting from the Spinner is 1
or you if it's 0 change it to
case 0:
{
spinnerPostion = 0;
query = "SELECT * FROM " + EMP_TABLE
+ " ORDER BY " + PROFIT + " DESC ";
break;
}
I am setting a new activity named Dispatch Report, which has two Spinners: CustomerSpinner and LotSpinner.
LotSpinner shows all Lots in Dispatch Table instead of showing only those Lots which are related to the Customer selected in the first Spinner.
I have fetched CustomerSpinner Value from Dispatch Table. In LotSpinner also fetched Lot numbers from Dispatch Table, but not Filtered according to customer selection.
DispatchReportActivity.Java
// Fetching customer from dispatch table
private void loadCustomerNameDispatch() {
DatabaseHelper db = new DatabaseHelper( getApplicationContext() );
List<String> lables1 = db.getFirmNAmeMoveStock();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables1);
dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinCustomer.setAdapter(dataAdapter);
spinCustomer.setOnItemSelectedListener(this);
}
// Fetching lot from dispatch table
private void loadLotbyCustomerDispatch() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getLotbyCustomer();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinLotbyCustomer.setAdapter(dataAdapter);
}
DATABASEHELPER.Java
//Get firm name in Dispatch Stock Report screen
public List < String > getFirmNAmeMoveStock() {
List < String > labels = new ArrayList < String > ();
// Select all query
String selectQuery = "SELECT * FROM " + Table_Inventory;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(3));
Set < String > set = new HashSet < >(labels);
labels.clear();
labels.addAll(set);
} while ( cursor . moveToNext ());
}
// Closing connection
cursor.close();
db.close();
// Returning lables
return labels;
}
// Method to get Lot No. in Dispatch Stock Report Activity
public List < String > getLotbyCustomer() {
List < String > labels1 = new ArrayList < String > ();
// Select all query
String selectQuery = "SELECT * FROM " + Table_StockDispatch;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels1.add(cursor.getString(4));
Set < String > set = new HashSet < >(labels1);
labels1.clear();
labels1.addAll(set);
} while ( cursor . moveToNext ());
}
// Closing connection
cursor.close();
db.close();
// Returning lables
return labels1;
}
There will be multiple customers, and each customer could have multiple Lots, so I want the second spinner to show only those Lots which are relevant to the customer selected in the first Spinner.
I'd suggest utilising Cursor's and Cursor adapters which can make matter simpler as :-
there is no need for intermediate arrays (one of your issues is that String arrays do not provide sufficient information)
CursorAdapters are designed to handle id (albiet a requirement that these exists in the Cursor with the column name _id (see the use of BaseColumns._ID below)).
The following is a basic example of related spinners based loosely upon your requirements.
First the DatbaseHelper DatabaseHelper.java
Two tables are defined/created Customers and Lots, methods to add data for each exist as do methods to extract a list from each of the tables. The lots extracted are based upon the customer to which they reference/belong to/associate with.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TBL_CUSTOMER = "customer";
public static final String TBL_LOT = "lot";
public static final String COL_CUSTOMER_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
public static final String COL_CUSTOMER_NAME = "customer_name";
public static final String COL_LOT_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
public static final String COL_LOT_NAME = "lot_name";
public static final String COL_LOT_CUSTOMERREFERENCE = "customer_refererence";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase(); //<<<<<<<<<< get the database connection (force create when constructing helper instance)
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_customer_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_CUSTOMER + "(" +
COL_CUSTOMER_ID + " INTEGER PRIMARY KEY, " +
COL_CUSTOMER_NAME + " TEXT UNIQUE " +
")";
String crt_lot_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_LOT + "(" +
COL_LOT_ID + " INTEGER PRIMARY KEY, " +
COL_LOT_NAME + " TEXT, " +
COL_LOT_CUSTOMERREFERENCE + " INTEGER " +
/*?????????? OPTIONAL IF FOREIGN KEYS ARE TURNED ON
"REFERENCES " + TBL_CUSTOMER + "(" +
COL_CUSTOMER_ID +
")" +
*/
")";
db.execSQL(crt_customer_table_sql);
db.execSQL(crt_lot_table_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addCustomer(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_CUSTOMER_NAME,name);
return mDB.insert(TBL_CUSTOMER,null,cv);
}
public long addLot(String name, long customer_reference) {
ContentValues cv = new ContentValues();
cv.put(COL_LOT_NAME,name);
cv.put(COL_LOT_CUSTOMERREFERENCE,customer_reference);
return mDB.insert(TBL_LOT,name,cv);
}
public Cursor getCustomers() {
return mDB.query(TBL_CUSTOMER,null,null,null,null,null,COL_CUSTOMER_NAME);
}
public Cursor getLotsPerCustomer(long customer_id) {
String whereclause = COL_LOT_CUSTOMERREFERENCE + "=?";
String[] whereargs = new String[]{String.valueOf(customer_id)};
return mDB.query(TBL_LOT,null,whereclause,whereargs,null,null,COL_LOT_NAME);
}
}
Note the above is pretty straight-forward. However, it would obviously need to be adapted to suit you App.
The second code is the activity that utilises the above and incorporates the 2 linked/related spinners where the selectable Lots are as per those lots associated with the currently selected customer.
The layout used for the activity is very basic, it just has two spinners. The spiners use the stock Simple_List_Item_2 layout (2 has been used to allow the all important ID's to be viewed (typically the user would not be shown the ID's)).
In short whenever a selection is made in the Customer spinner the Lot spinner is managed (setup or refreshed) based upon the customer id which is used to select the related/reference lots.
public class MainActivity extends AppCompatActivity {
Context mContext;
DatabaseHelper mDBHlpr;
SimpleCursorAdapter mCustomerSCA, mLotSCA;
Spinner mCustomerList, mLotList;
Cursor mCustomers, mLots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mDBHlpr = new DatabaseHelper(this);
mCustomerList = this.findViewById(R.id.customer_list);
mLotList = this.findViewById(R.id.lot_list);
addTestingDataIfNoData(); //Go and add some testing data if there is none
manageCustomerSpinner();
}
private void manageCustomerSpinner() {
mCustomers = mDBHlpr.getCustomers();
if (mCustomerSCA == null) {
mCustomerSCA = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
mCustomers,
new String[]{
DatabaseHelper.COL_CUSTOMER_NAME,
DatabaseHelper.COL_CUSTOMER_ID
},
new int[]{
android.R.id.text1,
android.R.id.text2
},
0
);
mCustomerList.setAdapter(mCustomerSCA);
mCustomerList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageLotSpinner(id); //<<<<<<<<<< WHENEVER CUSTOMER IS SELECTED THE LOT SPINNER IS MANAGED >>>>>>>>>>
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mCustomerSCA.swapCursor(mCustomers);
}
}
private void manageLotSpinner(long id) {
mLots = mDBHlpr.getLotsPerCustomer(id);
if (mLotSCA == null) {
mLotSCA = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
mLots,
new String[]{
DatabaseHelper.COL_LOT_NAME,
DatabaseHelper.COL_LOT_ID
},
new int[]{
android.R.id.text1,
android.R.id.text2
},
0
);
mLotList.setAdapter(mLotSCA);
} else {
mLotSCA.swapCursor(mLots);
}
}
private void addTestingDataIfNoData() {
if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper.TBL_CUSTOMER) < 1) {
mDBHlpr.addCustomer("Fred");
mDBHlpr.addCustomer("Mary");
mDBHlpr.addCustomer("Sue");
mDBHlpr.addCustomer("Alan");
mDBHlpr.addLot("Lot001",2); // Lot for mary
mDBHlpr.addLot("Lot002",1); // Lot for fred
mDBHlpr.addLot("Lot003",4); // Lot for ala
mDBHlpr.addLot("Lot004",3); // Lot for sue
mDBHlpr.addLot("Lot005",3); // Lot for sue
mDBHlpr.addLot("Lot006",3); // Lot for use
mDBHlpr.addLot("Lot007",2); // Lot for mary
mDBHlpr.addLot("Lot008",2); // Lot for mary
mDBHlpr.addLot("Lot009",2); // Lot for mary
mDBHlpr.addLot("Lot0010",2); // Lot for mary
mDBHlpr.addLot("Lot0020",1); // Lot for Fred
mDBHlpr.addLot("Lot00130",4); // Lot for Alan
mDBHlpr.addLot("Lot00130",3); // Lot for Sue
}
}
}
Result Example
Initial
Alan is initial selection due to sort order
After Selecting Mary
Note Lot names, as used, are not really suited to sorting
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 am building an application with database but a problem arises when I am retrieving the values from the database it returns empty (i.e. returned cursor has 0 tuples) and I am sure that database contains some information into it.
I am providing my code please help if you noticed any error.
Fragment where user inputs data to database:
public class FCar extends Fragment implements AdapterView.OnItemSelectedListener {
public FCar() {
}
CarDataBaseAdapter carDataBaseAdapter;
SessionManagement session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflating the view
final View rootView = inflater.inflate(R.layout.fragment_car, container, false);
// declaring stuff, not sure why it has to be final
final Spinner carSpinner;
final EditText editTextDistance, editTextMin;
Button btnSubmitCar;
// create new car database
carDataBaseAdapter = new CarDataBaseAdapter(getActivity());
carDataBaseAdapter = carDataBaseAdapter.open();
SQLiteDatabase x = carDataBaseAdapter.getDatabaseInstance();
session = new SessionManagement(getActivity().getApplicationContext());
// display existing tables
/*
Cursor hi = x.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
hi.moveToFirst();
int f = hi.getCount();
String g = Integer.toString(f);
Toast.makeText(getActivity().getApplicationContext(), g, Toast.LENGTH_LONG).show();
while ( !hi.isAfterLast() ) {
String h = (hi.getString( hi.getColumnIndex("name")) );
hi.moveToNext();
Toast.makeText(getActivity().getApplicationContext(), h, Toast.LENGTH_LONG).show();
}
*/
// Get References of Views
carSpinner = (Spinner) rootView.findViewById(R.id.spinner_car_type);
editTextDistance = (EditText) rootView.findViewById(R.id.editTextcarDistance);
editTextMin = (EditText) rootView.findViewById(R.id.editTextcarMin);
// Spinner click listener
carSpinner.setOnItemSelectedListener(this);
// set default spinner selection
carSpinner.setSelection(0);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Standard");
categories.add("Truck");
categories.add("Electric/Hybrid");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
carSpinner.setAdapter(dataAdapter);
// identifying the button
btnSubmitCar = (Button) rootView.findViewById(R.id.button_car_submit);
btnSubmitCar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// take username entry from login / sign up form via method in FProfile
// String currentUser = getSingleEntry();
String username = session.getUsername();
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy", Locale.CANADA);
String date = formata.format(new Date());
String type = carSpinner.getSelectedItem().toString();
// convert distance to integer
int distance = 0;
try {
distance = Integer.parseInt(editTextDistance.getText().toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse distance " + nfe);
}
// convert minutes to integer
int time = 0;
try {
time = Integer.parseInt(editTextMin.getText().toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse minutes" + nfe);
}
// Save the Data in Database
carDataBaseAdapter.insertEntry(username, date, type, distance, time);
// link back to input menu
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("caller", "Input");
startActivity(intent);
}
}
);
return rootView;
}
This is my query:
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", new String[]{"distance, time"}, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
carCursor.close();
}
carCursor.moveToFirst();
for (int i = 0; i < carCursor.getCount(); i++) {
int distance = carCursor.getInt(carCursor.getColumnIndex("DISTANCE"));
int time = carCursor.getInt(carCursor.getColumnIndex("TIME"));
}
return carCursor;
Then I retrieve it in a fragment
carStandardCursors[i] = carDataBaseAdapter.getCarEntry(currentUsername, searchDate, "Standard");
Then I made a loop to perform math on the cursors
for (int i = 0; i < 7; i++) {
Cursor ccursor = carStandardCursors[i];
carStandardTotal = CalculateCarStandard(ccursor);
carStandard[dex] = carStandardTotal;
And I found that the values in carStandardCursors[i] were all zero.
Use Facebook Stetho Library to check whether the database contains Values or not.Then only you can get an idea.
stetho library
the problem is here,
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", **new String[]{"distance, time"}**, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
carCursor.close();
}
carCursor.moveToFirst();
for (int i = 0; i < carCursor.getCount(); i++) {
int distance = carCursor.getInt(carCursor.getColumnIndex("DISTANCE"));
int time = carCursor.getInt(carCursor.getColumnIndex("TIME"));
}
return carCursor;
change it to
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", new String[]{"DISTANCE", "TIME"}, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
return carCursor;
}else{
if (carCursor!= null) {
carCursor.moveToNext();
}
return carCursor;
}
and then get this cursor at your method call and then at their
Cursor call = classObject.getCarEntry(username, Day, Type);
int distance = call .getInt(carCursor.getColumnIndex("DISTANCE"));
int time = call .getInt(carCursor.getColumnIndex("TIME"));
if more than one data then use while loop and ArrayAdapter
I have a simple question, which will help me to understand a lot ( I hope!)
Well, I have this code:
// Getting contacts Count
public int getContactsCount() {
helper = new DBHelper(CheckTable.this);
SQLiteDatabase db = helper.getReadableDatabase();
String countQuery = "SELECT * FROM " + Market.TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
How may I display this number?!
I thank you in advance...
This method is going to return you an int. Hence you have to declare it in your class. Assuming that you want to display this number in the same class you can simply follow this:
public class Example{
// Getting contacts Count
public int getContactsCount() {
helper = new DBHelper(CheckTable.this);
SQLiteDatabase db = helper.getReadableDatabase();
String countQuery = "SELECT * FROM " + Market.TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public static void main(String[] args) { //main method
int a= getContactsCount(); //calling the method
System.out.println(a); //displaying the integer
}
}
To display the value in a textview:
public class MyActvitiy Extends Activity{
public void onCreate(Bundle b){
super.onCreate(b);
//sets the view to the xml file that contains the textview
setContentView(R.layout.myActvityLayout);
//inflates textview from xml
TextView tv_contactCount = findViewById(R.id.tv_contactCount);
//creates a new example object
Example e = new Example();
//sets the textview to equal the count
tv_contactCount.setText(e.getContactsCount());
}
}
However, you may want to go over Android fundamentals to ensure you get a comprehensive understanding.