Multiple coloums in an array list - android

I am trying to fetch all the columns from my sqllite database to an ArrayList.My table name is Products.I have created an ArrayList adapter name Product.I am fetching my tables value in DBHELPER class.But when I am using ArrayList add to add all the columns value in my arrayadapter I got the following error
Cannot resolve method add(java.lang.string, java.lang.string)
DBHELPER.JAVA
public ArrayList<Product> getProductdetails()
{
ArrayList<Product> array_list = new ArrayList<Product>();
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
try {
String selectQuery = "SELECT * FROM " + TABLE_PRODUCTS;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String product_name = cursor.getString(cursor.getColumnIndex("PRODUCT_NAME"));
String Quantity = cursor.getString(cursor.getColumnIndex("Quantity"));
String PROD_VAT = cursor.getString(cursor.getColumnIndex("PROD_VAT"));
array_list.add(product_name,Quantity,PROD_VAT,PROD_VAT);
// array_list.addAll(Arrays.asList(product_name,Quantity,PROD_VAT,PROD_VAT));
}
}
}catch (Exception e){
e.printStackTrace();
}
finally {
db.endTransaction();
db.close();
}
return array_list;
}
PRODUCT.JAVA
public class Product {
//private variables
String _PRODUCT_CODE;
String _PRODUCT_NAME;
String _PRODUCT_RATE;
String _PRODUCT_VAT;
// Empty constructor
public Product(){
}
// constructor
public Product(String PRODUCT_CODE, String PRODUCT_NAME, String PRODUCT_RATE,String PRODUCT_VAT){
this._PRODUCT_CODE = PRODUCT_CODE;
this._PRODUCT_NAME = PRODUCT_NAME;
this._PRODUCT_RATE = PRODUCT_RATE;
this._PRODUCT_VAT = PRODUCT_VAT;
}
public String getproductcode(){ return this._PRODUCT_CODE;}
public String getproductname(){
return this._PRODUCT_NAME;
}
public String getproductrate(){return this._PRODUCT_RATE;}
public String getproductvat(){return this._PRODUCT_VAT;}
}

You are adding data to ArrayList in wrong way. Your ArrayList is type of object (eg. your Product class), So you need to pass instance of model class.
array_list.add(new Product(code,name,rate,vat));

Your Arraylist is type of Product which is one model class , so you have to add model class in that arraylist like this :
array_list.add(new Product(product_name,Quantity,PROD_VAT,PROD_VAT));

addAll() method of java.util.ArrayList class. This method is used for adding all the elements of a list to the another list.
What you want to is fetching single record & adding it to array list, and what you where trying to code is adding a single item as collection in to array list, which is wrong.
You need to add every single model as following way,
array_list.add(new Product(product_name,Quantity,PROD_VAT,PROD_VAT));

Modify
array_list.add(product_name,Quantity,PROD_VAT,PROD_VAT);
To
array_list.add(new Product(product_name,Quantity,PROD_VAT,PROD_VAT));

Related

Adding Cart Items to the Database and retrieving

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;
}
}

How to get and set json data on recyclerView?

Android Question?
I get json value and set on recyclerView ,How can make condition if i select item name then only print regarding this data value like Rate, amount like this.
Example: online ordering food android app
When you want to parse JSON , first you have to study about JSON Parsing.
You can Parse JSON by Volley Library , Retrofit etc.
Site to convert JSON to POJO/Model class jsonschema2pojo
Steps to Parse JSON :
Create Pojo class according to your json.
Using Volley or Retrofit to parse the json.
After setting data on pojo send the ArrayList to Recyclerview Adapter class.
You can also use GSON , its easy to parse json and set data to pojo classes.
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<ItemObject> posts = new ArrayList<ItemObject>();
posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
adapter = new RecyclerViewAdapter(MainActivity.this, posts);
recyclerView.setAdapter(adapter);
Below is the tutorial to Json Parsing using Volley Library and set to RecyclerView .
Reference : https://inducesmile.com/android/android-json-parsing-using-gson-and-recyclerview/
How can make condition if i select item name then only print regarding
this data value like Rate, amount like this.
Ans : By position you can get the values of rate, amount on that position data on Recyclerview Adapter class.
How to pass all recyclerView data to next activity and save sqlite database in android, inside onclick Listener ?
When you want to send recyclerView Data to next Activity, you have to send the pojo class object to next activity by intent.
RecyclerView Data send to next Activity :
takeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Data send to next Activity
Intent intent = new Intent(HomeActivity.this,TakeSingleScanActivity.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)cList);
intent.putExtra("BUNDLE",args);
startActivity(intent);
}
});
RecyclerView Data Receive from Last Activity :
ArrayList<LoadDataResult> inList; //Global Variable
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
inList = (ArrayList<LoadDataResult>) args.getSerializable("ARRAYLIST");
Don't forget to implements your pojo class as Serializable :
public class LoadDataResult implements Serializable{
Create a loop to store all recyclerview data on Sqlite on your Activity Class :
for(int m = 0;m<mList.get(0).getResult().size();m++) {
callDataBaseHelper(mList.get(0).getResult().get(m).getName().trim(),
mList.get(0).getResult().get(m).getSku().trim(),
mList.get(0).getResult().get(m).getUpc().trim(),
mList.get(0).getResult().get(m).getPrice().trim(),
mList.get(0).getResult().get(m).getDisplaySize().trim(),
mList.get(0).getResult().get(m).getDisplaySizeYes(),
mList.get(0).getResult().get(m).getStatus().trim());
if(m == mList.get(0).getResult().size()-1) {
setData();
getRefreshTime();
utils.showtoast("Data Load Successful");
utils.hideDialog();
}
}
call DataBaseHelper class addData method :
private void callDataBaseHelper(String name, String sku, String upc, String price, String displaySize, int displaySizeYes, String status) {
boolean insertData = databaseHelper.addData(name,sku,upc,price,displaySize,displaySizeYes,status);
// if(insertData){
// Log.e("Inserted","Inserted ");
// }else{
// Log.e("NotInserted","NotInserted ");
// }
}
Create DataBaseHelper Class :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "GiftsDatabase.db";
SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null,Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
String createTable = " CREATE TABLE "+ Constants.TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, "+Constants.NAME+" TEXT, "+Constants.SKU+" TEXT ,"+Constants.UPC+" TEXT,"+Constants.PRICE+" TEXT, "+Constants.DISPLAY_SIZE+" TEXT, "+Constants.DISPLAY_SIZE_YES+" INTEGER , "+Constants.STATUS+" TEXT)";
db.execSQL(createTable);
String createTableCount = " CREATE TABLE "+ Constants.TABLE_NAME_COUNT +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, "+Constants.SKU_COUNT+" TEXT ,"+Constants.QUANTITY_COUNT+" TEXT)";
db.execSQL(createTableCount);
Log.e(TAG,"Created Database");
}catch (Exception e){
Log.e("EXCEPTION",""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS "+Constants.TABLE_NAME);
db.execSQL(" DROP TABLE IF EXISTS "+Constants.TABLE_NAME_COUNT);
onCreate(db);
}
public boolean addData(String name , String sku, String upc , String price, String displaySize, int displaySizeYes, String status){
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.NAME, name );
contentValues.put(Constants.SKU, sku );
contentValues.put(Constants.UPC, upc );
contentValues.put(Constants.PRICE, price );
contentValues.put(Constants.DISPLAY_SIZE, displaySize );
contentValues.put(Constants.DISPLAY_SIZE_YES, displaySizeYes );
contentValues.put(Constants.STATUS, status );
long result = db.insert(Constants.TABLE_NAME,null,contentValues);
Log.e(TAG,""+upc+" Inserted");
if(result == -1) {
return false;
}else{
// Log.e(TAG,"value inserted");
return true;
}
}
Store Checked RecyclerView data on ArrayList in RecyclerView Adapter Class
ArrayList<YourPojoClass> data = new ArrayList<YourPojoClass>();
inside onBindViewHolder(); This is used for store data in checked rows.
holder.checkBox..setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
data.add(name.get(position).getText,address.get(position).getText)
}
});
Send data to next Activity : Create a button at bottom of the recyclerView by Your Activity , and you click on that button send data to next activity.

android display data from database using listview

I am trying to make simple android app where the user enter his information and then save it in the database and display the user info using listview. I have three java files: DBHelper.java, MainActivity.java and userInfo.java.
(MainActivity.java) is where the user enters his name and email.
(DBHelper.java) is where the database is created to save the user info.
(userInfo.java) is where the user info can be displayed.
in my app I successfully displayed the data from database using textview, and my question is how I can display the data from database using listview.
updated:
this is the getData() method from DBHelper.java file:
public List<Person> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_EMAIL};
Cursor c = ourDbase.query(TABLE_SCORE, columns, null, null, null, null, null + " DESC");
List<Person> people = new ArrayList<Person>();
int iRow = c.getColumnIndex(KEY_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iEmail= c.getColumnIndex(KEY_EMAIL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
Person p = new Person();
p.setEmail(c.getString(iEmail));
//set other info, like id, name
people.add(person);
}
return people;
}
here is the Person class:
public class Person {
private int ID;
private String NAME;
private String EMAIL;
public Person()
{
ID=0;
NAME="";
EMAIL="";
}
public Person(String qNAME, int qEMAIL) {
NAME = qNAME;
EMAIL= qEMAIL;
}
public int getID()
{
return ID;
}
public String getNAME() {
return NAME;
}
public int getEMAIL() {
return EMAIL;
}
public void setID(int id)
{
ID=id;
}
public void setNAME(String qNAME) {
NAME = qNAME;
}
public void setSCORE(int qEMAIL) {
EMAIL= qEMAIL;
}
}
and this is the code where I get the data from database and set it in textview from userInfo.java:
DbHelper userInfo = new DbHelper(this);
userInfo .open();
String data = userInfo .getData();
userInfo .close();
tv.setText(data);
how I can display the data from database using listview.
Since you dont provide any code about the listview and its adapter, i assume you dont know where to start.
You should create a listview, either with custom-created adapter or basic adapter (from android). After that, add the data from the database to your listview's adapter and use notifyDataSetChanged() to make sure the data is refreshed on the listview.
Simple tutorial : http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
In-depth (recommended) tutorial : http://www.vogella.com/tutorials/AndroidListView/article.html

How to add SQLite rows to an ArrayList<>

I retrieve all the rows from my SQLite-DB Table
Cursor cursor = db.rawQuery("select * from table",null);
Then I want to add each row to an ArrayList
Please help!
IF you're using custom object array, then use like following :
public void fillDataToArray() {
ArrayList<BeanClass> arrayList = new ArrayList<BeanClass>();
DatabaseHandler db = new DatabaseHandler(getActivity());
db.open();
try
{
Cursor c = db.getImageNameForList();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Beanclass detail = new Beanclass ();
detail.setName(c.getString(c
.getColumnIndex(DatabaseHandler._ID)));
detail.setPath(c.getString(c
.getColumnIndexOrThrow(DatabaseHandler._PATH)));
arrayList.add(detail);
c.moveToNext();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
c.close();
db.close();
}
If you use this in activity, change getActivity() to local context or whichever way you use context in activities.
DATA RETRIEVAL METHOD IN DB ADAPTER CLASS :
> public Cursor getImageNameForList() {
return db.rawQuery("select " + IMAGE_PATH + " from "+ TABLE_PRODUCT_IMAGES , null);
}
Code to do that would look like this, depending on whats in your Table. You have to create a Class that is able to represent a Row in your table.
For example if there are people in your table, with name and age, you will need an object Human(String name, int age) to put into a list.
SQLiteDatabase db = helper.getReadableDatabase();
ArrayList<Human> results = new ArrayList<Human>();
try {
String rawQuery = "Select name, age from people";
Cursor c = db.rawQuery(rawQuery, null);
try {
if (!c.moveToFirst())
return null;
do {
results.add(new Human(c.getString(0),c.getInt(1)));
} while (c.moveToNext());
} finally {
c.close();
}
} finally {
db.close();
}
public class Human {
private String name;
private int age;
public Human (String name, int age) {
this.name = name;
this.age = age;
}
}
In your Db Adapter class, add this method
public ArrayList<String>getData()
{
ArrayList<String>names=new ArrayList<String>();
Cursor c = getReadableDatabase().rawQuery("Select * from tableName", null);
c.moveToFirst();
do
{
String s1=c.getString(c.getColumnIndex("<Column_Name>"));
names.add(s1);
}while(c.moveToNext());
return names;
}
after that in your activity class add this
ArrayList<String> cid;
DB_Adapter database = new DB_Adapter(getApplicationContext(), "<your schema name>", null, 1);
cid=database.getData();
After that add your arraylist to your array adapter which is set to ListView

Querying Multiple Fields in a Database

For example, I have this table:
I am using the following method to query from that table:
public ArrayList<ArrayList<String>> getAllViandCategory() {
ArrayList<ArrayList<String>> data2 = new ArrayList<ArrayList<String>>();
ArrayList<String> data = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + "tbl_viand_category";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
data.add(cursor.getString(0));
data.add(cursor.getString(1));
data2.add(data);
} while (cursor.moveToNext());
}
return data2;
}
I am not getting the desired output. I am getting this: [1,Fish,2,Vegetables,3,Meat,4,Rice,5,Etc] instead of [[1,Fish],[2,Vegetables],[3,Meat],[4,Rice],[5,Etc]]
What you have is a List of Lists. The outer list has objects which has lists.
// Code to add a list object into outer list.
data2.add(data);
You will notice that you have created the data object just once. So basically the same object is inserted into data2 again and again.
You need to create a new data object for each iteration.
// New Code
if (cursor.moveToFirst()) {
do {
data = new ArrayList<String>();
data.add(cursor.getString(0));
data.add(cursor.getString(1));
data2.add(data);
} while (cursor.moveToNext());
}
Hope that helps :D

Categories

Resources