How to add two tables in one RecyclerView with different colour values - android

I want to make above type of RecyclerView (in my case). In above sample pic, the expenses show in red colours with zebra lines and income shows in green colours. I've write code for expense table values and successfully shown in RecyclerView. Now I want to show income from income table and make view same as sample pic. kindly help.
RecyclerView with expense values:
arrayListExpense = new ArrayList<>();
AdapterViewItems adapter = new AdapterViewItems(MainActivity.this, arrayListExpense);
recyclerView = (RecyclerView) findViewById(R.id.view_item_recycle_view);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(adapter);
Cursor cursor = db.selectExpense();
cursor.moveToFirst();
if (cursor.getCount() == 0) {
Toast.makeText(this, "Empty list", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < cursor.getCount(); i++) {
HashMap<String, Object> hm = new HashMap<>();
hm.put(ID_EXPENSE, cursor.getString(cursor.getColumnIndex(ID_EXPENSE)));
hm.put(NAME_EXPENSE, cursor.getString(cursor.getColumnIndex(NAME_EXPENSE)));
long valueExpense = cursor.getLong(cursor.getColumnIndex(VALUE_EXPENSE));
showExpense(valueExpense);
hm.put(VALUE_EXPENSE, String.valueOf(valueExpense));
hm.put(DATE_EXPENSE, Utility.dateFormat(cursor.getLong(cursor.getColumnIndex(DATE_EXPENSE))));
String id = cursor.getString(cursor.getColumnIndex(TYPE_ID_EXPENSE));
hm.put("type", db.selectTypeById(id));
arrayListExpense.add(hm);
cursor.moveToNext();
}
cursor.close();
}
Database:
Cursor selectExpense() {
Cursor cursor = null;
try {
SQLiteDatabase db = this.getWritableDatabase();
cursor = db.rawQuery("SELECT " + ID_EXPENSE + "," + NAME_EXPENSE + "," + VALUE_EXPENSE
+ "," + DATE_EXPENSE + "," + TYPE_ID_EXPENSE + " FROM " + TABLE_EXPENSE
+ " ORDER BY " + DATE_EXPENSE + " DESC", null);
} catch (Exception e) {
Log.d("selectExpenses", " error " + e.getMessage());
}
return cursor;
}

All you need is getItemViewType which will allow you to inflate multiple views within a recyclerview.
Example : see this or this

Use a tag that gives you information like it is expanses or inform.
add that tag in hashmap.
if(expanses){ // use variable to check expanses or income
hm.put(INFO_EXPENSE_INCOME, "red");
}else{
hm.put(INFO_EXPENSE_INCOME, "green");
}
and in bindViewHolder get the hashmap value and setTextColor accordingly.

Related

Why i get Null ArrayList From The Select Query in Android DataBase?

Hello i get Null Array List From this Code:
public List<IndiviualUser> findBloodByBloodGroup(String final_blood_group)
{
List<IndiviualUser> userlist = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
String select = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL_4 + " = ' "+ final_blood_group + " ' " ;
Cursor cursor = db.rawQuery(select,null);
Log.d("FIND", "findBloodByBloodGroup"+ select);
if(cursor.moveToFirst())
{
do
{
IndiviualUser user = new IndiviualUser();
user.setName(cursor.getString(1));
user.setPassword(cursor.getString(2));
user.setBlood_Group(cursor.getString(3));
user.setBlood_Quantity(cursor.getString(4));
user.setMobile_No(cursor.getString(5));
user.setLat2(cursor.getDouble(6));
user.setLong2(cursor.getDouble(7));
userlist.add(user);
}
while (cursor.moveToNext());
}
Log.d("SELECT","THE MSG WAS SELECTED SUCCESSFULLY " + userlist);
return userlist;
}
And I Will Receive This userlist in Another Activity The Code is Below:
DataBaseHelper DBHepler;
String str1,s1,s2,s5;
double s3,s4;
DBHepler = new DataBaseHelper(Find_Blood_Now_Result.this);
List<IndiviualUser> indiviualUsers = DBHepler.findBloodByBloodGroup(str1);
for(IndiviualUser user: indiviualUsers)
{
s1 = user.getName();
s2 = user.getMobile_No();
s3 = user.getLat2();
s4 = user.getLong2();
s5 = user.getBlood_Group();
}
When i will SetText of All Strings it will give me Null Values,i hope you someone have Solution for this Thank You.

How can I repeat a ListView item a certain number of times using Android and SQLite data and changing one column each iteration?

I am trying to repeat certain data from a table in a ListView with one row changing each iteration of the item. I want to have a user input an int of the times to repeat and press a button to update the list.
I am working with dates as the updating item. So if a user inputs '3', I want 3 rows added to the list, and inserted into the table, adding 1 month to the date for the 3 months.
Main Activity
planAheadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (planAheadMonths.getText().toString().trim().isEmpty()) {
Toast.makeText(getBaseContext(), "Add months to plan by", Toast.LENGTH_SHORT).show();
} else {
int plan = Integer.parseInt(planAheadMonths.getText().toString());
mDBHelper.updateCheckingPlanner(plan, mChecking.getCheckingId());
planAheadMonths.setText("");
mDBHelper.getTransRepeater(plan, mChecking.getCheckingId());
}
}
});
DBHelper
public void getTransactionRepeater(int repeat, int id) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = TRANSACTION_DATE + " BETWEEN " + getCurrentMonth() + " AND " + getFutureMonth() + " AND " +
TRANSACTION_CHECKING_ID + " = " + id + " AND " + TRANSACTION_REPEAT + " != 'NONE' ";
String[] whereargs = new String[1];
Cursor res = db.query(TABLE_TRANSACTIONS, null, whereclause, null, null, null, TRANSACTION_DATE + " ASC, " + TRANSACTION_ID);
db.beginTransaction();
while (res.moveToNext()) {
if (res.getString(res.getColumnIndex(TRANSACTION_REPEAT)).equals("MONTH")) {
for (int i = 0; i < repeat; i++) {
+ i);
ContentValues cv = new ContentValues();
cv.put(TRANSACTION_NAME, res.getString(res.getColumnIndex(TRANSACTION_NAME)));
cv.put(TRANSACTION_TYPE, res.getString(res.getColumnIndex(TRANSACTION_TYPE)));
cv.put(TRANSACTION_DATE, sdf.format(cFuture.getTime()) + res.getString(res.getColumnIndex(TRANSACTION_NAME)) + i);
cv.put(TRANSACTION_AMOUNT, res.getInt(res.getColumnIndex(TRANSACTION_AMOUNT)));
cv.put(TRANSACTION_NOTES, res.getString(res.getColumnIndex(TRANSACTION_NOTES)));
cv.put(TRANSACTION_REPEAT, res.getString(res.getColumnIndex(TRANSACTION_REPEAT)));
cv.put(TRANSACTION_CHECKING_ID, res.getInt(res.getColumnIndex(TRANSACTION_CHECKING_ID)));
cv.put(TRANSACTION_NEW_BALANCE, res.getInt(res.getColumnIndex(TRANSACTION_NEW_BALANCE)));
cv.put(TRANSACTION_CREDIT_ID, res.getString(res.getColumnIndex(TRANSACTION_CREDIT_ID)));
whereargs[0] = res.getString(res.getColumnIndex(TRANSACTION_DATE));
db.insert(TABLE_TRANSACTIONS, null, cv);
}
}
}
res.close();
db.setTransactionSuccessful();
db.endTransaction();
}

How to multiply sql values

I made SQL database and populated it with values. In TextView I need to show multiply result of specific rows.
I made SQL statement and I hope that is correct.
public List<Food> multiplyFat(){
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " FROM " + FoodEntry.TABLE_NAME + " WHERE ( "
+FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
SQLiteDatabase db = this.getWritableDatabase();
List<Food> storeTotalFat = new ArrayList<>();
Cursor cursor = db.rawQuery(totalFat, null);
if (cursor.moveToFirst()){
do {
double fat = Double.parseDouble(cursor.getString(0));
storeTotalFat.add(new Food(fat));
} while (cursor.moveToNext());
}
cursor.close();
return storeTotalFat;
}
To be more clear I need to multiply values from row COLUMN_FAT_TOTAL with row COLUMN_GRAM and display result into the TextView. Or should I put these SQL statement:
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " * " +FoodEntry.COLUMN_GRAM + " FROM " +FoodEntry.TABLE_NAME;
That is simplier way but I am not sure that it is correct way.
Anyhow I need to display this multiplyFat() function (result) into TextView. Any help or advice would be really helpfull.
public List multiplyFat(){
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " FROM " + FoodEntry.TABLE_NAME + " WHERE ( "
+FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
The above works perfectly in MySQL, I just tried it.
SQLiteDatabase db = this.getWritableDatabase(); --> db = this.getReadableDatabase();
Since you are not changing anything in the SQLite database you want a '.getReadableDatbase();' not '.getWritableDatabase();'
List<Food> storeTotalFat = new ArrayList<>();
Cursor cursor = db.rawQuery(totalFat, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
do {
double fat = Double.parseDouble(cursor.getString(0));
storeTotalFat.add(new Food(fat));
} cursor.moveToNext();
}
cursor.close();
return storeTotalFat;
}
See how I first moved to the first index, then I ask it to continue in a while loop until it has reached the final element in the SQL results. Your way was not actually incrementing the cursor, it would have only been able to add the first result to the storeTotalFat ArrayList.
-------- part 2 ---------
Now let's pretend we are back in the activity, woo!
Let's say there is a class variable reference to the database helper and add a new ArrayList to house the results from the query result we just gained.
DBHelper myDBhelper = DBHelper.getInstance(MainActivity.this)
ArrayList<String> sqlResultArray = new ArrayList<>();
If you want a Recyclerview you make a separate RviewAdapter class, in your case FoodFatRecyclerViewAdapter and add the following
RecyclerView rv = (RecyclerView) findViewById(R.id.foodFatRecView);
LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(llm);
FoodFatRecyclerViewAdapter foodFatAdapter = new FoodFatRecyclerViewAdapter(MainActivity.this, sqlResultArray);
rv.setAdapter(foodFatAdapter);
Now as for the adding of the result to the textview create a new class called FoodFatRecyclerViewAdapter
public class FoodFatRecyclerViewAdapter extends RecyclerView.Adapter<FoodFatViewHolder> {
ArrayList<String> mFoodFatItems;
Context mContext;
public FoodFatRecyclerViewAdapter(Context context, ArrayList<String> array) {
mContext = context;
mFoodFatItems = array;
}
#Override
public FoodFatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.this_xml_layout_will_describe_the_arrangement_of_the_indi_item_in_the_list_not_the_master_view, parent, false);
FoodFatViewHolder recyclerView = new FoodFatViewHolder(view);
return recyclerView;
}
#Override
public void onBindViewHolder(FoodFatViewHolder holder, final int position) {
holder.mFatTotalTextView.setText(mFoodFatItems.get(position));
}
#Override
public int getItemCount() {
return mFoodFatItems.size();
}
}
Now the final piece to the puzzle, the View Holder so create a class called FoodFatViewHolder
public class FoodFatViewHolder extends RecyclerView.ViewHolder{
TextView mFatTotalTextView;
public FoodFatViewHolder(View itemView) {
super(itemView);
mFatTotalTextView = (TextView) itemView.findViewById(R.id.the_textview_id_within_the_individ_item_in_rv_xml_layout);
}
}
Voila! It should work
You need to show the multiplication total then you shouldn't do a select on COLUMN_FAT_TOTAL. Instead you should do the computation in your select query and store that computation in an alias. You can then use that alias as a result.
Modify your query as below
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + "AS Result FROM " + FoodEntry.TABLE_NAME";
You are on the right track. Do the math in the database if it is easy and straight forward, which this example is.
Might I suggest the following (similar to kapsym answer) for your sql statement:
String totalFat = "SELECT " + FoodEntry.COLUMN_FAT_TOTAL + ", " + FoodEntry.COLUMN_GRAM + "," FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + "AS TotalFat FROM " + FoodEntry.TABLE_NAME + " WHERE ( " + FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
You should study the basics of MySQL : https://www.tutorialspoint.com/mysql/mysql-select-query.htm
After the SELECT, you add column names that you want to retrieve and not expressions.
For your case, Use this Query to get all fat_total & gram entries :
String totalFat = "SELECT " + FoodEntry.COLUMN_FAT_TOTAL + "," + FoodEntry.COLUMN_GRAM + " FROM " + FoodEntry.TABLE_NAME;
Then you retrieve fatTotal * gram for each cursor, multiply it and feed it into your storeTotalFat array based on (!= 0) condition.
Cursor cursor = db.rawQuery(totalFat, null);
if (cursor.moveToFirst()){
do {
double fat = Double.parseDouble(cursor.getString(0));
double gram= Double.parseDouble(cursor.getString(1));
if (fat * gram != 0)
storeTotalFat.add(new Food(fat * gram));
} while (cursor.moveToNext());
}

How to update total price in cart listview in android

I have a ListView which displays items in my shopping cart from my existing database and at the bottom i have created TextView of total price of all the items in my cart,but the total price that displays at the bottom does not get updated according to the products in my cart.I am not getting where am I making mistake,please help me out.
xml code for TextView of Total price:
<TextView
android:id="#+id/totalItemPrice"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="RS "
android:textSize="20dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="20dp"
android:textColor="#FFFFFF"/>
AddToCartFragment.java :
private ArrayList<GenieCart_List_Model> mAddList;
private void getCart_Data() {
try {
db = new DataBasehelper1(getActivity());
mAddList = new ArrayList<GenieCart_List_Model>();
mAddList = db.getAllCotacts();
long sum = db.sum_Of_Rs();
mTotalItemPrice.setText("Total Rs : " + sum);
db.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
DataBaseHelper1.java:
public long sum_Of_Rs() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(" select * from " +CONTACTS_TABLE_NAME + " ORDER BY " + CONTACTS_PRODUCT_ID + " DESC " , null);
ArrayList<GenieCart_List_Model> list = new ArrayList<GenieCart_List_Model>();
try {
res.moveToFirst();
for (int i = 0; i < res.getCount(); i++) {
GenieCart_List_Model Prod_Details = new GenieCart_List_Model();
Prod_Details.setPrice(res.getString(res.getColumnIndex(CONTACTS_PRODUCT_RS)));
Prod_Details.setProdID(res.getString(res.getColumnIndex(CONTACTS_PRODUCT_ID)));
try {
int total = Integer.parseInt(res.getString(res.getColumnIndex(CONTACTS_PRODUCT_RS)));
Sum = Sum + total;
return Sum;
} catch (Exception e) {
e.printStackTrace();
}
list.add(Prod_Details);
res.moveToNext();
}
}
catch (Exception e) {
e.printStackTrace();
}
return Sum;
}
I think this is a conversion issue.
Set Text like that
mTotalItemPrice.setText("Total Rs : " + String.valueOf(sum));
Remove the line " return sum; " from try catch .
Your method sum_Of_Rs() is right. To update the total cost call your method sum_Of_Rs() and set the result to the TextView every time you add or delete an item in the cart i.e. if you are using ListView always do these steps when you notify the listview about the data changes using notifyDataSetChanged() you can also improve your method sum_Of_Rs() by changing your method to the following:
public long sum_Of_Rs() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT SUM (" + CONTACTS_PRODUCT_RS + ") FROM " + CONTACTS_TABLE_NAME , null);
cursor.moveToFirst();
int sum = cursor.getInt(0);
cursor.close();
return sum;
}
I Suggest to change your SQL Query to :
public long sum_Of_Rs() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM ( " +CONTACTS_PRODUCT_RS + ") FROM " + CONTACTS_TABLE_NAME , null);
c.moveToFirst();
int i = c.getInt(0);
c.close();
return i;
}
PS: SUM() will return a number in the same format of the column that you are reading. if CONTACTS_PRODUCT_RS is a float/double use
float i = c.getFloat(0);
double i = c.getDouble(0);
Hope it help !! :))

How to check values in HashMap<String, String> and setBackgroundResource when record = value?

I have just started coding an Android App using Android Studio 2.1 and my app was sort of an offline messaging - this is using SQLite Database (basically compose of two tables message and contact).
I am now in my last activity where I need to populate a list of message exchange from the contacts created. I was able to list them but without aesthetics. I would like to set different setBackgroundResource whenever the type is either a LEFT or RIGHT but was struggling to apply it.
Below is my code:
MessageRepo - the SQLite DBhelper:
public ArrayList<HashMap<String, String>> getMessageListById(int fromid, int toid) {
SQLiteDatabase db = helper.getWritableDatabase();
String toquery = "SELECT " + MessageModel.messageId +
", " + MessageModel.fromId +
", " + MessageModel.toId +
", " + MessageModel.messageContent +
", 'RIGHT' AS type FROM " + MessageModel.tableMessage +
" WHERE " + MessageModel.toId +
" = ? AND " + MessageModel.fromId +
" = ? ";
String fromquery = "SELECT " + MessageModel.messageId +
", " + MessageModel.fromId +
", " + MessageModel.toId +
", " + MessageModel.messageContent +
", 'LEFT' AS type FROM " + MessageModel.tableMessage +
" WHERE " + MessageModel.fromId +
" = ? AND " + MessageModel.toId +
" = ? ";
String query = toquery +
" UNION " + fromquery +
" ORDER BY " + MessageModel.messageId;
ArrayList<HashMap<String, String>> messageList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(fromid), String.valueOf(toid), String.valueOf(fromid), String.valueOf(toid)});
if (cursor.moveToFirst()) {
do {
HashMap<String, String> messages = new HashMap<String, String>();
messages.put("messageId", cursor.getString(0));
messages.put("messageFromId", cursor.getString(1));
messages.put("messageToId", cursor.getString(2));
messages.put("messageContent", cursor.getString(3));
messages.put("type", cursor.getString(4));
messageList.add(messages);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return messageList;
}
Message Activity - this will display in a ListView but not working as I was intending it to display:
ArrayList<HashMap<String, String>> messageList = messagehandler.getMessageListById(_fromid, _toid);
if (messageList.size() != 0) {
ListView listView = getListView();
if(messageList.contains("RIGHT")) {
listView.setBackgroundResource(R.drawable.right);
} else {
listView.setBackgroundResource(R.drawable.left);
}
ListAdapter adapter = new SimpleAdapter(MessageDetailActivity.this, messageList, R.layout.message, new String[]{"messageFromId", "messageToId", "messageContent"}, new int[]{R.id.FromId, R.id.ToId, R.id.message});
setListAdapter(adapter);
}
I've checked a lot of posts and I can't seem to make it work for me:
The constructor ArrayAdapter>>(Context, int, ArrayList>) is undefined
Android Alternate row Colors in ListView
Thanks a lot in advance!
After researching a bit more. I finally found the answer by opting to use List and a setter/getter class:
public class MessagesAdapter extends ArrayAdapter<ContactsAndMessages> {
public MessagesAdapter(Context context, List<ContactsAndMessages> contacts) {
super(context, 0, contacts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactsAndMessages contact = getItem(position);
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica.ttf");
if(convertView == null) {
if (contact.type.equalsIgnoreCase("me")) {....

Categories

Resources