I have three tables in mySQL namely user, restaurants, cartlist.
here user table is for saving the user details.
restaurant table is for saving the meal details, price and quantity.
cartlist is to add the restaurant details.
Now when the specific user login to the app, I want the cartlist items of specific user added to the list. but Im getting the details of whole users who added items to the cart.
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String selectQuery = "SELECT * FROM restaurants";
SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
ProductModel productModel = new ProductModel();
productModel.setID(Integer.parseInt(cursor.getString(0)));
productModel.setName(cursor.getString(1));
productModel.setMealname(cursor.getString(2));
productModel.setMealprice(cursor.getString(3));
productModel.setMealqty(cursor.getString(4));
products.add(productModel);
} while (cursor.moveToNext());
}
cursor.close();
DatabaseManager.getInstance().closeDatabase();
adapter = new ProductAdapter(ProductList.this, R.layout.activity_cartlistview, products);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
Carttable:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
lv_checkout = findViewById(R.id.lv_checkout);
tv_totalamount = findViewById(R.id.tv_totalamount);
btn_checkouttopayment = findViewById(R.id.btn_checkouttopayment);
String selectQuery = "SELECT * FROM carttable";
SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
ProductModel productModel = new ProductModel();
productModel.setID(Integer.parseInt(cursor.getString(0)));
productModel.setName(cursor.getString(1));
productModel.setMealname(cursor.getString(2));
productModel.setMealprice(cursor.getString(3));
productModel.setMealqty(cursor.getString(4));
productModel.setMealtotal((Double.parseDouble(cursor.getString(3)) * Double.parseDouble(cursor.getString(4)) + ""));
products.add(productModel);
} while (cursor.moveToNext());
}
double totalPrices = 0;
for (int i = 0; i < products.size(); i++) {
totalPrices += Double.parseDouble(products.get(i).getMealtotal());
}
tv_totalamount.setText("Total Amount to be Paid : " + totalPrices + "");
cursor.close();
DatabaseManager.getInstance().closeDatabase();
adapter = new ProductAdapter(this, R.layout.activity_cartlistview, products);
lv_checkout.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
what are the changed to be done to the query? Let me knw guys.TIA!
It's because The query you are running is going to the Restaurant table and getting all the Records from It. From what I can understand, Cartlist the name of table in which a user will input the details of a particular restaurant. So Right now, you are calling all the records from Restaurant table which will give you the list regardless of who added it.
You might want to change the query to something like
SELECT restaurant_name FROM cartlist WHERE userName = selected_User;
Now you have the restaurant name. Save these and use it on query.
SELECT * FROM restaurants WHERE restaurantsName = selected_restaurant_name;
do {
ProductModel productModel = new ProductModel();
productModel.setID(Integer.parseInt(cursor.getString(0)));
productModel.setName(cursor.getString(1));
productModel.setMealname(cursor.getString(2));
productModel.setMealprice(cursor.getString(3));
productModel.setMealqty(cursor.getString(4));
productModel.setMealtotal((Double.parseDouble(cursor.getString(3)) * Double.parseDouble(cursor.getString(4)) + ""));
products.add(productModel);
}
Add a constructor to your model class and inject in. Saves a few lines of code/readability.
do {
products.add( new ProductModel(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
}
The line: productModel.setMealtotal((Double.parseDouble(cursor.getString(3)) * Double.parseDouble(cursor.getString(4)) + ""));
seems to contain a simple relationship where the "Meal total = mean quantity * meal price" which could be done in the constructor as well...it is a constant algorithm and part of the model.
Here is the model (I have added #Data using lombok which makes all the getters and setters when being compiled)
import lombok.Data;
#Data
public class ProductModel {
private int id;
private String name;
private String mealName;
private int mealPrice;
private int mealQuantity;
private int mealTotal;
//Constructor...i.e. "new ProductModel(field1,field2...)"
public ProductModel(int id, String name, String mealName, int mealPrice, int mealQuantity) {
this.id = id;
this.name = name;
this.mealName = mealName;
this.mealPrice = mealPrice;
this.mealQuantity = mealQuantity;
this.mealTotal = mealPrice * mealQuantity;
}
}
Related
I want to Show all database contents in a List View in Android Studio, I expect to see 3 rows that each row contains "name, family and ID" , but I see a comlex of package name and some other characters as follws:
com.google.www.hmdbtest01.Person#529e71b4
com.google.www.hmdbtest01.Person#529e7238
com.google.www.hmdbtest01.Person#529e7298
if I have more rows in my database, I will see more lines like above in the output.
my codes are as follow:
public class ListOfData extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_data);
ListView list = findViewById(R.id.list1);
HmDbManager01 db= new HmDbManager01(this);
ArrayList personList = db.getAll();
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, personList);
list.setAdapter(arrayList);
}
}
db.getAll() is as follows:
public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Person p1 = new Person();
p1.pID=cursor.getString(0);
p1.pName=cursor.getString(1);
p1.pFamily=cursor.getString(2);
allData.add(p1);
cursor.moveToNext();
}
}
cursor.close();
sqLiteDatabase.close();
return allData;
}
and, this is Person:
package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}
Let me know your comments on this problem.
arrayListAdapter will convert your personList to list of string
change like it:
ArrayList<String> persons = new ArrayList<String>();
personList.forEach(personModel -> {
persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
});
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, persons);
hi i have this spinner dropdown that displays data from my database. In my database, i have this table named area and it has this fields, aid its primary key and location which is a varchar. so far i am successful in displaying the data im my spinner. in my DBHelper this is the code that gets the data from DB
public Set<String> getAllData()
{
Set<String> set = new HashSet<String>();
String selectQuery = "SELECT * FROM " + TABLE_AREA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
db.close();
return set;
}
then in my addLocation.java here is how i use it to display the data on my spinner
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addplace);
Spinner spn = (Spinner)findViewById(R.id.areas);
Set<String> aset = db.getAllData();
List<String> aData = new ArrayList<>(aset);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
aData);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(spinnerAdapter);
spn.setOnItemSelectedListener(new SpinnerInfo());
}
private class SpinnerInfo implements AdapterView.OnItemSelectedListener {
private boolean isFirst = true;
String selected;
#Override
public void onItemSelected(AdapterView<?> spinner, View selectedView, int selectedIndex, long id)
{
if (isFirst)
{
isFirst = false;
}
else
{
String selection = spinner.getItemAtPosition(selectedIndex).toString();
selected = selection;
}
Toast tempMessage =
Toast.makeText(addLocation.this,
selected,
Toast.LENGTH_SHORT);
tempMessage.show();
}
#Override
public void onNothingSelected(AdapterView<?> spinner) {
// Won’t be invoked unless you programmatically remove entries
}
}
the thing is i needed to get the id of the selected location not the index in the spinner but it's database id. any idea on how i can do this? thanks so much in advance!
i needed to get the id of the selected location not the index in the
spinner but it's database id. any idea on how i can do this?
Do it as using HashMap:
1. Use HashMap instead of Set with location as a key and location id as value. change getAllData() :
public Map<String, Integer> getAllData()
{
Map<String, Integer> hashMap = new HashMap<String, Integer>();
...
if (cursor.moveToFirst()) {
do {
hashMap.put(cursor.getString(1),cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return hashMap;
}
2. Pass all keys to Spinner :
Map<String, Integer> hashMap = db.getAllData();
List<String> allLocations = new ArrayList<String>(hashMap.keySet());
3. Now In onItemSelected use selected String to get id of Selected item:
int location_id=hashMap.get(selected);
Main Activity
Code for fetching data from Sqlite & adding it inside Expandable list view.
public void getExpandableListData() {
// Group data//
Cursor cursor = databaseHelper.getGroupData();
cursor.moveToFirst();
do {
String categoryDescription = cursor.getString(cursor .getColumnIndex("categorydesc"));
int categoryId = cursor.getInt(cursor.getColumnIndex("CategoryId"));
listDataHeader.add(categoryDescription);
// Child data//
Cursor cursorChild = databaseHelper.getChildData(categoryId);
List<ChildInfo> childList = new ArrayList<ChildInfo>();
cursorChild.moveToFirst();
while (cursorChild.moveToNext()) {
String businessName = cursorChild.getString(cursorChild.getColumnIndex("BusinessName"));
phoneNumber = cursorChild.getString(cursorChild.getColumnIndex("ph_Phone"));
String landMark = cursorChild.getString(cursorChild.getColumnIndex("LandMark"));
ChildInfo childInfo = new ChildInfo(businessName, phoneNumber, landMark);
childList.add(childInfo);
}
childDataHashMap.put(categoryDescription, childList);
} while (cursor.moveToNext());
cursor.close();
}
DataBaseHelper class
public Cursor getGroupData() {
String query = "SELECT * FROM Category GROUP BY categorydesc";
return db.rawQuery(query, null);
}
public Cursor getChildData(int CategoryId) {
String query = "SELECT * from Category WHERE CategoryId = '" + CategoryId + "' LIMIT 3" ;
return db.rawQuery(query, null);
}
On load more tab click I have to fetch data from Sqlite db and set it to Expandable list view.Can anyone please suggest me how to avoid repetition of data fetching from Sqlite and maintain count of data fetched.
I am trying to display the contents of my mysqlite database into a listview,
I am able to get the contents and display them in a textview, but for some
reason I can't add the details to an arraylist ? I am not too sure what am doing
wrong. I have looked for multiple solutions but none of them seem to work, am getting an error
Android.database.CursorIndexOutOfBoundsExecption: Index requested -1
Here is what I currently have:
OnCreate:
ArrayAdapter<Contact> currentContactsAdapter = new ContactArrayAdapter();
ListView lvcontacts = (ListView) findViewById(R.id.lvContacts);
lvcontacts.setAdapter(currentContactsAdapter);
tdb = new TestDBOpenHelper(this, "contact.db", null, 1);
sdb = tdb.getWritableDatabase();
new MyContacts().execute();
ListView Adapter:
private class ContactArrayAdapter extends ArrayAdapter<Contact>{
public ContactArrayAdapter(){
super(MainActivity.this, R.layout.listviewitem, addedContacts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.listviewitem, parent, false);
}
Contact currentContact = addedContacts.get(position);
TextView name = (TextView) itemView.findViewById(R.id.tvNameitem);
name.setText(currentContact.getName());
TextView phone = (TextView) itemView.findViewById(R.id.tvPhoneitem);
phone.setText(currentContact.getPhone());
TextView email = (TextView) itemView.findViewById(R.id.tvEmailitem);
email.setText(currentContact.getEmail());
return itemView;
}
}
GetContacts:
class MyContacts extends AsyncTask<String, String, String> {
List<Contact> retrievedContacts = new ArrayList<Contact>();
protected String doInBackground(String... args) {
String cname;
String cphone;
String cemail;
// name of the table to query
String table_name = "contact";
// the columns that we wish to retrieve from the tables
String[] columns = {"FIRST_NAME", "PHONE", "EMAIL"};
// where clause of the query. DO NOT WRITE WHERE IN THIS
String where = null;
// arguments to provide to the where clause
String where_args[] = null;
// group by clause of the query. DO NOT WRITE GROUP BY IN THIS
String group_by = null;
// having clause of the query. DO NOT WRITE HAVING IN THIS
String having = null;
// order by clause of the query. DO NOT WRITE ORDER BY IN THIS
String order_by = null;
// run the query. this will give us a cursor into the database
// that will enable us to change the table row that we are working with
Cursor c = sdb.query(table_name, columns, where, where_args, group_by,
having, order_by);
for(int i = 0; i < c.getCount(); i++) {
cname = c.getString(c.getColumnIndex("FIRST_NAME"));
cphone = c.getString(c.getColumnIndex("PHONE"));
cemail = c.getString(c.getColumnIndex("EMAIL"));
c.moveToNext();
retrievedContacts.add(new Contact(cname,cphone,cemail));
}
return null;
}
//Update Contact list when response from server is received
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
for(Contact contact: retrievedContacts)
addedContacts.add(contact);
}
}
It seems that your table "contact" doesn't have the exact structure you are trying to read.
Android.database.CursorIndexOutOfBoundsExecption: Index requested -1
This means that one of these column names is not part of it.
c.getColumnIndex("FIRST_NAME")
c.getColumnIndex("PHONE")
c.getColumnIndex("EMAIL")
So one of them return -1 instead of the index because they not exist in the table.
EDIT:
Then the for loop may be faulty. I suggest to use something like:
if (c != null ) {
if (c.moveToFirst()) { // Always move at the first item
do {
cname = c.getString(c.getColumnIndex("FIRST_NAME"));
cphone = c.getString(c.getColumnIndex("PHONE"));
cemail = c.getString(c.getColumnIndex("EMAIL"));
retrievedContacts.add(new Contact(cname, cphone, cemail));
} while (c.moveToNext());
}
}
c.close(); // always close when done!
I'm trying to get certain book data from my Inventory table based on the ISBN.
However, I'm getting an error: "attempt to re-open an already-closed object". The error only occurs when I click a listView object, go to a different screen, go back to this page via "finish()", and then try to click on another listView object. I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
Why does it not work if I try to getInventoryEntriesByISBN after returning to this activity from another activity via "finish()"?
The error occurs at SearchResultsScreen:
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
and by extension, occurs at InventoryAdapter:
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
SearchResultsScreen.java
// Set up search array
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
InventoryAdapter.java (Most relevant parts)
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
int publish = cursor.getInt(cursor.getColumnIndex("PUBLISH_DATE"));
String publishdate = ((Integer)publish).toString();
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
String callNumber = cursor.getString(cursor.getColumnIndex("CALL_NUMBER"));
int available = cursor.getInt(cursor.getColumnIndex("AVAILABLE_COUNT"));
String availablecount = ((Integer)available).toString();
int inventory = cursor.getInt(cursor.getColumnIndex("INVENTORY_COUNT"));
String inventorycount = ((Integer)inventory).toString();
int due = cursor.getInt(cursor.getColumnIndex("DUE_PERIOD"));
String dueperiod = ((Integer)due).toString();
int checkoutcount = cursor.getInt(cursor.getColumnIndex("COUNT"));
String count = ((Integer)checkoutcount).toString();
//combine variables into one array
searchEntry[0] = ISBN;
searchEntry[1] = title;
searchEntry[2] = author;
searchEntry[3] = publishdate;
searchEntry[4] = callNumber;
searchEntry[5] = availablecount;
searchEntry[6] = inventorycount;
searchEntry[7] = dueperiod;
searchEntry[8] = count;
cursor.close();
return searchEntry;
}
public String getTitleAndAuthorByISBN(String ISBN)
{
int entriesFound = getNumSearchEntries(ISBN);
if(entriesFound==0)
entriesFound = 1;
String searchEntry;
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
searchEntry = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
//close cursor and return
cursor.close();
return searchEntry;
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper
{
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
// ============================ End Variables ===========================
public DataBaseHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL(CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL(InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL(StatisticsAdapter.STATISTICS_TABLE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// on upgrade drop older tables
_db.execSQL("DROP TABLE IF EXISTS " + LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + StatisticsAdapter.STATISTICS_TABLE_CREATE);
// Create a new one.
onCreate(_db);
}
}
Check Database Connection before executing query:
if (!dbHelper.db.isOpen())
dbHelper.open();
you can also use cursor.requery(); for again same query.
and in last you have to close the cursor and database also.
cursor.close();
db.close();
Edited:
I have created DBHelper class which extends SQLiteOpenHelper, this class is inner class of DatabaseHelper class and that class have following methods.
/** For OPEN database **/
public synchronized DatabaseHelper open() throws SQLiteException {
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
/** For CLOSE database **/
public void close() {
dbHelper.close();
}
If you have still doubt then feel free to ping me. Thank you.
The error only occurs when I click an item, go to a different screen, go back to this page via "finish()", and then try to click on another listView object.
I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
The correct SearchResultsScreen is below:
SearchResultsScreen.java
// Set up search array
final String Entries[][] = new String[isbn.length][9];
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
Entries[i] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[i]);
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = Entries[position];
This is your problem
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
cursor.close();
Change to
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
{
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
}
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
Add SQLiteDatabase db = this.getWritableDatabase(); in this code before executing the raw Query