how to refresh listview after deleting data from database? - java

All Transaction Activity is used to to fetch data from database
public class AllTransactionActivity extends MainActivity {
ArrayList<String> price = new ArrayList<String>();
ArrayList<String> category = new ArrayList<String>();
ArrayList<String> date = new ArrayList<String>();
ArrayList<String> id = new ArrayList<String>();
ArrayList<String> payment_mode = new ArrayList<String>();
ArrayList<String> description = new ArrayList<String>();
RadioButton rb1 , rb2 ;
ListView listView ;
Cursor cv;
LinearLayout list_lay;
RelativeLayout no_data_lay;
String date_change;
Boolean check_btn = false;
Transactiondata data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_transaction);
findViewById();
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.title);
mTitle.setText("All Transaction");
data = new Transactiondata(AllTransactionActivity.this);
data.open();
cv = data.incomeDisplayData();
id.clear();
price.clear();
category.clear();
date.clear();
payment_mode.clear();
description.clear();
if (cv.moveToFirst()) {
do {
category.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_CATEGORY)));
id.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_ID)));
// date.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_DATE)));
SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
try {
date1 = simpleDateFormate.parse(cv.getString(cv.getColumnIndex(Transactiondata.KEY_DATE)));
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
date_change = fmtOut.format(date1);
} catch (ParseException e) {
e.printStackTrace();
}
date.add(date_change);
price.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_PRICE)));
payment_mode.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_PAYMENT_MODE)));
description.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_DESCRIPTION)));
} while (cv.moveToNext());
}else {
list_lay.setVisibility(View.GONE);
no_data_lay.setVisibility(View.VISIBLE);
}
listView.setAdapter(new DisplayAllDataAdapter(this, AllTransactionActivity.this , check_btn , id , category , date , price , payment_mode , description ));
cv.close();
}
public void findViewById(){
listView = (ListView)findViewById(R.id.list);
rb1 =(RadioButton)findViewById(R.id.rb1) ;
rb2 =(RadioButton)findViewById(R.id.rb2) ;
no_data_lay = (RelativeLayout)findViewById(R.id.no_data_lay);
list_lay = (LinearLayout)findViewById(R.id.list_lay);
}
}
Custom Adapter Class which is used to bind data with list view
package app.dailyexpensemanager.adapters;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import app.dailyexpensemanager.R;
import app.dailyexpensemanager.activity.EditReminderActivity;
import app.dailyexpensemanager.activity.PaymentTransactionActivity;
import app.dailyexpensemanager.db.Transactiondata;
public class DisplayAllDataAdapter extends BaseAdapter {
private Context mContext;
private static Cursor cursor;
private static Activity activity;
private static Boolean check_btn;
private ArrayList<String> category_list;
private ArrayList<String> date_list;
private ArrayList<String> id_list ;
private ArrayList<String> price_list ;
private ArrayList<String> payment_mode_list ;
private ArrayList<String> description_list ;
public DisplayAllDataAdapter(Context cv, Activity activity, Boolean check_btn, ArrayList<String> id, ArrayList<String> category, ArrayList<String> date,
ArrayList<String> price, ArrayList<String> payment_mode, ArrayList<String> description) {
this.check_btn = check_btn;
this.id_list = id;
this.category_list = category;
this.date_list = date;
this.price_list = price;
this.payment_mode_list = payment_mode;
this.description_list = description;
this.mContext = cv;
this.activity = activity;
}
public DisplayAllDataAdapter(Context cv, Activity activity,Cursor cursor , Boolean check_btn, ArrayList<String> id, ArrayList<String> category, ArrayList<String> date,
ArrayList<String> price, ArrayList<String> payment_mode, ArrayList<String> description) {
this.check_btn = check_btn;
this.id_list = id;
this.category_list = category;
this.date_list = date;
this.price_list = price;
this.payment_mode_list = payment_mode;
this.description_list = description;
this.mContext = cv;
this.activity = activity;
this.cursor = cursor;
}
#Override
public int getCount() {
return date_list.size();
}
#Override
public Object getItem(int position) {
return date_list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
final Holder mHolder;
LayoutInflater layoutInflater = null;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.activity_list_all_transaction, null);
mHolder = new Holder();
mHolder.txt_category = (TextView) child.findViewById(R.id.category);
mHolder.txt_date = (TextView) child.findViewById(R.id.date);
mHolder.txt_id = (TextView) child.findViewById(R.id.id);
mHolder.txt_price = (TextView) child.findViewById(R.id.price);
mHolder.txt_payment = (TextView) child.findViewById(R.id.payment);
mHolder.txt_description = (TextView) child.findViewById(R.id.description);
child.setTag(mHolder);
}
else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_category.setText(category_list.get(position));
mHolder.txt_date.setText(date_list.get(position));
mHolder.txt_id.setText(id_list.get(position));
mHolder.txt_price.setText(price_list.get(position));
mHolder.txt_payment.setText(payment_mode_list.get(position));
mHolder.txt_description.setText(description_list.get(position));
child.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(R.drawable.item_pressed);
/*Animation animation1 = new AlphaAnimation(0.3f, 1.0f);
animation1.setDuration(2000);
v.startAnimation(animation1);*/
String price_lv = mHolder.txt_price.getText().toString();
String id_lv = mHolder.txt_id.getText().toString();
String category_lv = mHolder.txt_category.getText().toString();
String payment_lv = mHolder.txt_payment.getText().toString();
String date_lv = mHolder.txt_date.getText().toString();
String description_lv = mHolder.txt_description.getText().toString();
showCustomeDialogBox(mContext, false, price_lv, id_lv, category_lv, payment_lv,
date_lv, description_lv);
// notifyDataSetChanged();
}
});
return child;
}
public class Holder {
TextView txt_category;
TextView txt_price;
TextView txt_id;
TextView txt_date;
TextView txt_payment;
TextView txt_description;
}
public static void showCustomeDialogBox(final Context context, final boolean activityVisibility,String price,
final String id , String category , String payment , String date , String description ) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.activity_custom_dailog);
Button positivebtn = (Button) dialog.findViewById(R.id.positive);
Button negativebtn = (Button) dialog.findViewById(R.id.negative);
LinearLayout category_lay = (LinearLayout) dialog.findViewById(R.id.category_lay);
TextView dialog_title = (TextView) dialog.findViewById(R.id.dialog_title);
TextView price_tv = (TextView) dialog.findViewById(R.id.price);
TextView category_tv = (TextView) dialog.findViewById(R.id.category);
TextView payment_tv = (TextView) dialog.findViewById(R.id.payment_mode);
TextView date_tv = (TextView) dialog.findViewById(R.id.date);
TextView description_tv = (TextView) dialog.findViewById(R.id.description);
category_lay.setVisibility(View.GONE);
dialog_title.setText(category);
price_tv.setText(price);
category_tv.setText(category);
payment_tv.setText(payment);
date_tv.setText(date);
description_tv.setText(description);
positivebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
} else {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
}
}
});
negativebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
}
In dialog box code I have done it with recreate activity but I think it is not good solution. Now how to delete and refresh same time listview data only? hlep me :(

Try this,
positivebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
} else {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
}
}
});

Try to Write mContext.notifyDataSetChanged();.
After this.
delete.deleteIncomeEntry(id);
mContext.notifyDataSetChanged();
EDIT 1:
Just do this.
this.notifyDataSetChanged();
EDIT 2:
Look your data is deleted from database that is sure. so in your Base Adapter to refresh your List View you need to again call the method which is getting data from database. and then do notifydatasetchanged().I hope you will understand.

try this code
adapter=new CustomListAdapter(getActivity(),List);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
And Also add notifyDataSetChanged(); in GetView method below Where you set value.

Check edited first method, just change your showDialog method by below nothing else.
One more thing pass position in your method at last as like below.
showCustomeDialogBox(mContext, false, price_lv, id_lv, category_lv, payment_lv,
date_lv, description_lv, position);
See new DialogBox method below,
public static void showCustomeDialogBox(final Context context, final boolean activityVisibility,String price,
final String id , String category , String payment , String date , String description, int position ) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.activity_custom_dailog);
Button positivebtn = (Button) dialog.findViewById(R.id.positive);
Button negativebtn = (Button) dialog.findViewById(R.id.negative);
LinearLayout category_lay = (LinearLayout) dialog.findViewById(R.id.category_lay);
TextView dialog_title = (TextView) dialog.findViewById(R.id.dialog_title);
TextView price_tv = (TextView) dialog.findViewById(R.id.price);
TextView category_tv = (TextView) dialog.findViewById(R.id.category);
TextView payment_tv = (TextView) dialog.findViewById(R.id.payment_mode);
TextView date_tv = (TextView) dialog.findViewById(R.id.date);
TextView description_tv = (TextView) dialog.findViewById(R.id.description);
category_lay.setVisibility(View.GONE);
dialog_title.setText(category);
price_tv.setText(price);
category_tv.setText(category);
payment_tv.setText(payment);
date_tv.setText(date);
description_tv.setText(description);
positivebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
//activity.recreate();
//dialog.dismiss();
} else {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
//activity.recreate();
//dialog.dismiss();
}
id_list.remove(position);
category_list.remove(position);
date_list.remove(position);
price_list.remove(position);
payment_mode_list.remove(position);
description_list.remove(position);
dialog.dismiss();
notifyDataSetChanged();
}
});
negativebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
Try Below Code It will help you,
First comment your dialog box method, and write below method to use.
public void deleteData(int position)
{
String id = id_list.get(position);
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
delete.close();
}
else
{
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
delete.close();
}
id_list.remove(position);
category_list.remove(position);
date_list.remove(position);
price_list.remove(position);
payment_mode_list.remove(position);
description_list.remove(position);
notifyDataSetChanged();
}
Now, replace your onCLick method by below.
child.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(R.drawable.item_pressed);
deleteData(position);
}
});

Related

Data retrieved from firebase not showing up in recyclerview

I am fairly new in android studio. So when I click on the floating action button, put in new data, it stores the data in my firebase database but displays blank screen and a notification that "budget item added successfully" and the app does not crash either. I'm not sure what I did wrong in the code or maybe the codes were not properly typed. Any help would be appreciated very much.
Activity class.
public class TodaySpendingActivity extends AppCompatActivity {
private Toolbar toolbar;
private TextView totalAmountSpentOn;
private ProgressBar progressBar;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog loader;
private FirebaseAuth mAuth;
private String onlineUserId = "";
private DatabaseReference expensesRef;
private TodayItemAdapter todayItemAdapter;
private List<Data> myDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_spending);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar((androidx.appcompat.widget.Toolbar)toolbar);
getSupportActionBar().setTitle("Today's Spending");
totalAmountSpentOn = findViewById(R.id.totalAmountSpentOn);
progressBar = findViewById(R.id.progressBar);
fab = findViewById(R.id.fab);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
onlineUserId = mAuth.getCurrentUser().getUid();
expensesRef = FirebaseDatabase.getInstance().getReference("expenses").child(onlineUserId);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
myDataList = new ArrayList<>();
todayItemAdapter = new TodayItemAdapter( TodaySpendingActivity.this, myDataList);
recyclerView.setAdapter(todayItemAdapter);
readItems();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addItemSpentOn();
}
private void addItemSpentOn() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(TodaySpendingActivity.this);
LayoutInflater inflater = LayoutInflater.from(TodaySpendingActivity.this);
View myView = inflater.inflate(R.layout.input_layout, null);
myDialog.setView(myView);
final AlertDialog dialog = myDialog.create();
dialog.setCancelable(false);
final Spinner itemSpinner = myView.findViewById(R.id.itemspinner);
final EditText amount = myView.findViewById(R.id.amount);
final EditText note = myView.findViewById(R.id.note);
final Button cancel = myView.findViewById(R.id.cancel);
final Button save = myView.findViewById(R.id.save);
note.setVisibility(View.VISIBLE);
save.setOnClickListener(view -> {
String Amount = amount.getText().toString();
String Item = itemSpinner.getSelectedItem().toString();
String notes = note.getText().toString();
if(TextUtils.isEmpty(Amount)){
amount.setError("Please input an amount!");
return;
}
if (Item.equals("Select item")){
Toast.makeText(TodaySpendingActivity.this,"Select a valid item", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(notes)){
note.setError("Note is Requires");
return;
}
else {
loader.setMessage("Adding a budget item");
loader.setCanceledOnTouchOutside(false);
loader.show();
String id = expensesRef.push().getKey();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
String date = dateFormat.format(cal.getTime());
MutableDateTime epoch = new MutableDateTime();
epoch.setDate(0);
DateTime now = new DateTime();
Months months = Months.monthsBetween(epoch, now);
Data data = new Data(Item, date, id, notes, Integer.parseInt(Amount), months.getMonths());
expensesRef.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(TodaySpendingActivity.this, "Budget item added successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(TodaySpendingActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
loader.dismiss();
}
});
}
dialog.dismiss();
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
private void readItems() {
Query query = expensesRef.orderByChild("month").equalTo(new DateTime().getMonthOfYear());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
myDataList.clear();
for (DataSnapshot ds: snapshot.getChildren()){
Data data = ds.getValue(Data.class);
myDataList.add(data);
}
todayItemAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
int totalAmount = 0;
for (int i = 0; i < myDataList.size(); i++){
totalAmount += myDataList.get(i).getAmount();
String stTotal = String.valueOf(totalAmount);
totalAmountSpentOn.setText(stTotal);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Adapter Class.
public class TodayItemAdapter extends RecyclerView.Adapter<TodayItemAdapter.ViewHolder>{
private Context mContext;
private List<Data> myDataList;
private String post_key= "";
private String item= "";
private String note="";
private int amount = 0;
public TodayItemAdapter(Context mContext, List<Data> myDataList) {
this.mContext = mContext;
this.myDataList = myDataList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.retrieve_layout, parent, false);
return new TodayItemAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Data data = myDataList.get(position);
holder.item.setText("Item: "+ data.getItem());
holder.amount.setText("Amount: "+ data.getAmount());
holder.date.setText("On: "+ data.getDate());
holder.note.setText("Note: "+ data.getNotes());
switch (data.getItem()){
case "Transport":
holder.imageView.setImageResource(R.drawable.ic_transport);
break;
case "Food":
holder.imageView.setImageResource(R.drawable.ic_food);
break;
case "House":
holder.imageView.setImageResource(R.drawable.ic_house);
break;
case "Entertainment":
holder.imageView.setImageResource(R.drawable.ic_entertainment);
break;
case "Education":
holder.imageView.setImageResource(R.drawable.ic_education);
break;
case "Charity":
holder.imageView.setImageResource(R.drawable.ic_charity);
break;
case "Clothing":
holder.imageView.setImageResource(R.drawable.ic_clothing);
break;
case "Health":
holder.imageView.setImageResource(R.drawable.ic_health);
break;
case "Personal":
holder.imageView.setImageResource(R.drawable.ic_personal);
break;
case "Other":
holder.imageView.setImageResource(R.drawable.ic_other);
break;
}
}
#Override
public int getItemCount() {
return myDataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView item, amount, date, note;
public ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item = itemView.findViewById(R.id.item);
amount = itemView.findViewById(R.id.amount);
date = itemView.findViewById(R.id.date);
note = itemView.findViewById(R.id.note);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
First check addValueEventListener is called when new data is stored
if yes then change code as mentioned below and try again
in readItems method
From
todayItemAdapter.notifyDataSetChanged();
To
todayItemAdapter.addData(myDataList);
add method in TodayItemAdapter class as mentioned below
public void addData(List< Data> list){
myDataList.addAll(list);
notifyDataSetChanged();
}

How do I use intent from arrayAdapter to go into a third activity?

I am almost done with this project, and the code is janky, but I am trying to pass data through the arrayadapter to the third activity, but even without data passing the intent wont take it to the third activity.
I've been looking through stackoverflow, I've changed the context. I've tried adding flags and such.
I have three main activities, one adapter and two custom classes.
Also, the list view uses a custom adapter to a different card view depending on data entered, if that matters.
public class BookAdaptor extends ArrayAdapter {
int mLayoutID;
List<BookList> dataset;
Context mContext;
public BookAdaptor(Context context, int resource, List<BookList> objects) {
super(context, resource, objects);
mContext = context;
dataset = objects;
mLayoutID = resource;
}
public class pickedAuthor implements Serializable {
private String genre;
private String bookTitle;
private String synopsis;
private String bookAuthor;
private String bookPublisher;
private String bookImage;
private int currentPlace;
public pickedAuthor(String genre, String bookTitle, String synopsis, String bookAuthor, String bookPublisher, String bookImage, int currentPlace) {
this.genre = genre;
this.bookTitle = bookTitle;
this.synopsis = synopsis;
this.bookAuthor = bookAuthor;
this.bookPublisher = bookPublisher;
this.bookImage = bookImage;
this.currentPlace = currentPlace;
}
public int getCurrentPlace() {
return currentPlace;
}
public String getCategoryImage() {
return genre;
}
public String getBookImage() {
return bookImage;
}
public String getBookTitle() {
return bookTitle;
}
public String getBookSynopsis() {
return synopsis;
}
public String getBookAuthor() {
return bookAuthor;
}
public String getBookPublisher() {
return bookPublisher;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View currentListViewItem = convertView;
// Check if the existing view is being reused, otherwise inflate the view
if (currentListViewItem == null) {
currentListViewItem = LayoutInflater.from(getContext()).inflate(mLayoutID, parent, false);
}
//Get the Number object for the current position
final BookList currentNumber = dataset.get(position);
//Set the attributed of list_view_number_item views
ImageView iconImageView = (ImageView) currentListViewItem.findViewById(R.id.image_view_book_icon);
int i = mContext.getResources().getIdentifier(
currentNumber.getBookImage(), "drawable",
mContext.getPackageName());
//Setting the icon
iconImageView.setImageResource(i);
TextView titleNameTextView = (TextView) currentListViewItem.findViewById(R.id.text_view_book_title);
titleNameTextView.setText(currentNumber.getBookTitle());
TextView authorNameTextView = (TextView) currentListViewItem.findViewById(R.id.text_view_author_name);
authorNameTextView.setText(currentNumber.getBookAuthor());
TextView publisherNameTextView = (TextView) currentListViewItem.findViewById(R.id.text_view_publisher_name);
publisherNameTextView.setText(currentNumber.getBookPublisher());
CardView button = (CardView) currentListViewItem.findViewById(R.id.card_view_list_item);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
int currentDigit;
intent = new Intent(mContext.getApplicationContext(), DetailsActivity.class);
String currentGenre,currentTitle, currentBookImage, currentCategoryImage, currentSynopsis, currentAuthor, currentPublisher;
currentDigit = 1;
currentGenre = currentNumber.getCategoryImage();
currentTitle = currentNumber.getBookImage().toString();
currentBookImage = currentNumber.getBookImage();
currentSynopsis = currentNumber.getBookSynopsis();
currentAuthor = currentNumber.getBookAuthor();
currentPublisher = currentNumber.getBookPublisher();
pickedAuthor author;
author = new pickedAuthor(currentGenre, currentTitle, currentSynopsis, currentAuthor, currentPublisher, currentBookImage, currentDigit);
intent.putExtra("Author", author);
mContext.getApplicationContext().startActivity(intent);
}
});
return currentListViewItem;
}
}
package com.example.bookstore;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class DetailsActivity extends AppCompatActivity {
public BookAdaptor.pickedAuthor author;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Intent intent = getIntent();
author = (BookAdaptor.pickedAuthor) intent.getSerializableExtra("Author Name");
TextView titleNameTextView = (TextView) findViewById(R.id.text_view_book_title);
titleNameTextView.setText(author.getBookTitle());
TextView authorNameTextView = (TextView) findViewById(R.id.details_text_view_author_name);
authorNameTextView.setText(author.getBookAuthor());
TextView publisherNameTextView = (TextView) findViewById(R.id.details_text_view_publisher_name);
publisherNameTextView.setText(author.getBookPublisher());
TextView synopsisTextView = (TextView) findViewById(R.id.text_view_synopsis);
synopsisTextView.setText(author.getBookSynopsis());
}
}
Change onclick like this
Intent intent = new Intent(v.getContext, ThirdActivity.class);
DataClass data = new DataClass(param1, param2);
intent.putExtra("param", data);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
If it did not work, try changing the Dataclass to implement parcelable and sent parcelable object using intent.
Note : Always prefer parcelable over serializable (Parcelable is
perfomant) if you have no specific advantage using serializables.
intent.putExtra("Author", new Gson().toJson(author));
Author author= new Gson().fromJson(intent.getStringExtra("Author"), Author.class);
try like this.

How to correctly use the spinner

I have some items (strings) in my spinner and when I select one of these items, I want back an associated value, for example:
If I select SAE 1020, it returns me 250.0
If I select E-155, it returns me 300.0
The value is suposed to be shown in a EditText, but the only value I see is 250.0.
After all, this value should be sent to the next Activity (I also do not know if I'm doing the transfer correctly).
What is happening? What can I do?
Code:
package com.mateus.ligacoestubulares;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class Dados extends AppCompatActivity {
String [] AçoMontante = {"SAE 1020", "E-155"};
String [] AçoBanzo = {"SAE 1020", "E-155"};
String [] EspessuraT1 = {"0,75 mm", "0,90 mm", "0,95 mm"};
String [] EspessuraTo = {"0,75 mm", "0,90 mm", "0,95 mm"};
EditText campoFy1;
EditText campoFyo;
EditText campoT1;
EditText campoTo;
EditText normalM;
EditText normalB;
EditText momentoB;
EditText teta;
Button next;
Intent intentNext;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dados);
Spinner spinnerMont = (Spinner) findViewById(R.id.spinnerM);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoMontante);
spinnerMont.setAdapter(arrayAdapter1);
campoFy1 = (EditText) findViewById(R.id.fy1);
String montStr = spinnerMont.getSelectedItem().toString();
String fy1 = Double.toString(choiceM(montStr));
campoFy1.setText(fy1);
Spinner spinnerBanzo = (Spinner) findViewById(R.id.spinnerB);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoBanzo);
spinnerBanzo.setAdapter(arrayAdapter2);
campoFyo = (EditText) findViewById(R.id.fyo);
String banzoStr = spinnerBanzo.getSelectedItem().toString();
String fyo = Double.toString(choiceB(banzoStr));
campoFyo.setText(fyo);
next = (Button) findViewById(R.id.prosseguir);
intentNext = new Intent(Dados.this, ConferenciaDosDados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resistenciaM = campoFy1.getText().toString();
String resistenciaB = campoFyo.getText().toString();
bundle.putString("fy1",resistenciaM);
bundle.putString("fyo",resistenciaB);
intentNext.putExtras(bundle);
startActivity(intentNext);
}
});
}
public double choiceM(String str) {
Double f1 = 0.0;
if (str.equals(AçoMontante[0])) {
f1 = 250.0;
} else if (str.equals(AçoMontante[1])) {
f1 = 300.0;
}
return f1;
}
public double choiceB(String str) {
Double fo = 0.0;
if (str.equals(AçoMontante[0])) {
fo = 250.0;
} else if (str.equals(AçoMontante[1])) {
fo = 300.0;
}
return fo;
}
}
Try this. This code is working as you want it to.
String [] AçoMontante = {"SAE 1020", "E-155"};
String [] AçoBanzo = {"SAE 1020", "E-155"};
String [] EspessuraT1 = {"0,75 mm", "0,90 mm", "0,95 mm"};
String [] EspessuraTo = {"0,75 mm", "0,90 mm", "0,95 mm"};
EditText campoFy1;
EditText campoFyo;
Button next;
Intent intentNext;
Bundle bundle;
String montStr,banzoStr, f1,fo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
campoFy1 = (EditText) findViewById(R.id.fy1);
campoFyo = (EditText) findViewById(R.id.fyo);
Spinner spinnerMont = (Spinner) findViewById(R.id.spinnerM);
Spinner spinnerBanzo = (Spinner) findViewById(R.id.spinnerB);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, AçoMontante);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoBanzo);
spinnerMont.setAdapter(arrayAdapter1);
spinnerBanzo.setAdapter(arrayAdapter2);
spinnerMont.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
montStr = (String) parent.getItemAtPosition(i);
if(montStr == "SAE 1020"){
f1 = "250.0";
}
else if (montStr == "E-155"){
f1 = "300.0";
}
else{}
campoFy1.setText(f1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinnerBanzo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
banzoStr = (String) parent.getItemAtPosition(i);
if(banzoStr == "SAE 1020"){
fo = "250.0";
}
else if (banzoStr == "E-155"){
fo = "300.0";
}
else{}
campoFyo.setText(fo);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
next = (Button) findViewById(R.id.prosseguir);
intentNext = new Intent(MainActivity.this, Second.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resistenciaM = campoFy1.getText().toString();
String resistenciaB = campoFyo.getText().toString();
bundle.putString("fy1",resistenciaM);
bundle.putString("fyo",resistenciaB);
intentNext.putExtras(bundle);
startActivity(intentNext);
}
});
}
Also, instead of bundles, you can just use private static variables to pass the value.
set f1 and fo as
private static String f1,fo; instead of String f1,fo;.
And call them in another activity as Dados.f1 or Dados.fo [ Dados here is your current activity ]

Display no. of items of a recyclerview in a textview in android studio

I want to display number of total items of my recyclerview in a textview. If new item is added or deleted that textview should be update. And also calculate total price of items in a list of Items in a recyclerview and display in a textview below recyclerview list.
Below is my recyclerview adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.into(holder.imgProduct);
// holder.tvProductStatus.setText(productModelList.get(position).getIsAvailable());
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
//holder.tvMaterial.setText(productModelList.get(position).getMaterial());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity,tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView)itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and java Class:
public class CartActivity extends AppCompatActivity {
DatabaseHandler helper;
List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
TextView tvTotalNoOfItems, tvTotalPrice;
String p;
String i;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
p = getIntent().getStringExtra("variant_id");
i = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
p = extras.getString("variant_id");
i= extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList= new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CartAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
tvTotalNoOfItems = (TextView)findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView)findViewById(R.id.tvTotalCartItemsPrice);
String totalPrice = "";
for (int i = 0; i<dbList.size(); i++)
{
totalPrice = totalPrice + dbList.get(i).getPrice().toString();
}
tvTotalPrice.setText(totalPrice);
btnContinueShopping = (Button)findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCOllectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCOllectionActivity);
finish();
}
});
btnCheckout = (Button)findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCheckoutActivity = new Intent(CartActivity.this,CheckoutActivity.class);
startActivity(launchCheckoutActivity);
}
});
}
}
First, add following getter to your adapter:
public List<ProductModel> getItems(){
return productModelList;
}
Then, you can subscribe on adapter data change and do the following:
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged () {
tvTotalNoOfItems.setText(mAdapter.getItemCount());
String totalPrice = "";
for (int i = 0; i < ((CartAdapter)mAdapter).getItems().size(); i++) {
totalPrice = totalPrice + ((CartAdapter)mAdapter).getItems().get(i).getPrice().toString();
}
tvTotalPrice.setText("" + totalPrice);
}
});
just add this line below the adapter set line
tvTotalNoOfItems.setText(mAdapter.getCount());
and add this into you adapter class where you delete action perform
String totalPrice = "";
((CartActivity)context).tvTotalNoOfItems.setText(getCount());
for (int i = 0; i<productModelList.size(); i++)
{
totalPrice = totalPrice + productModelList.get(i).getPrice().toString();
}
((CartActivity)context).tvTotalPrice.setText(""+totalPrice);
Just public you textview like this
public TextView tvTotalNoOfItems, tvTotalPrice;

startActivity(intent) on Android not working

So I am trying to pass some info with serialization, but for some reason it is not working, I wrote a couple of Log.e() for testing, and according to the LogCat it says it is not getting passed the startactivity(intent).
Here is my code
public class MainActivity extends Activity {
FileManager file = new FileManager();
FileInputStream fileInput;
FileOutputStream fileOutput;
SortedArrayList<Contact> contactList = new SortedArrayList<Contact>();
ArrayList<Contact> theList =new ArrayList<Contact>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
fileInput = openFileInput("contacts.txt");
Log.e("FILE INPUT","FOUND!!");
contactList = file.read(fileInput,getApplicationContext());
Log.e("_____",contactList.toString());
}
catch (Exception e) {
Log.e("Error","ERROR CREATING FILE");
}
if(contactList.size() != 0){
ListView lv =(ListView)findViewById(R.id.contactList);
for(int i=0;i<contactList.size();i++){
theList.add(contactList.get(i));
}
ArrayAdapter<Contact> adapter = new MyListAdapter();
lv.setAdapter(adapter);
clickOnContact();
}
// Create The Adapter with passing ArrayList as 3rd parameter
//OrderAdapter arrayAdapter = new OrderAdapter(this, R.layout.list_view, contactListNameView, contactListLastNameView, contactListCellphoneView);
//Set The Adapter
//lv.setAdapter(arrayAdapter);
}
private void clickOnContact() {
ListView list = (ListView) findViewById(R.id.contactList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int pos,
long id) {
Contact Contact = theList.get(pos);
Log.e("contact: ",Contact.getFirstName());
try{
Intent intent = new Intent(MainActivity.this, ShowContactActivity.class);
Log.e("pass ","1");
intent.putExtra("Contact",Contact);
Log.e("pass ","2");
startActivity(intent);
}
catch (Exception e){
Log.e("didnt","pass catch");
}
}
});
}
private class MyListAdapter extends ArrayAdapter<Contact> {
public MyListAdapter() {
super(MainActivity.this, R.layout.list_view, theList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.list_view, parent, false);
}
Contact contact = theList.get(position);
//Fill First Name
TextView name = (TextView) itemView.findViewById(R.id.contactName);
name.setText(contact.getFirstName());
//Fill Last Name
TextView lastname = (TextView) itemView.findViewById(R.id.contactLastName);
lastname.setText(contact.getLastName());
return itemView;
}
}
This is the Activity is trying to contact:
public class ShowContactActivity extends Activity {
TextView name;
TextView lastname;
TextView email;
TextView cell;
TextView homenumber;
Contact contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_contact_info);
// Show the Up button in the action bar.
setupActionBar();
name = (TextView) findViewById(R.id.nametextview);
lastname = (TextView) findViewById(R.id.lastnametextview);
email = (TextView) findViewById(R.id.emailtextview);
cell = (TextView) findViewById(R.id.celltextview);
homenumber = (TextView) findViewById(R.id.homenumbertextview);
Contact contact = new Contact();
try{
Intent i = getIntent();
contact = (Contact) i.getSerializableExtra("Contact");
}
catch (Exception e){
Log.e("problema","con serializacion");
}
name.setText(contact.getFirstName());
lastname.setText(contact.getLastName());
cell.setText(contact.getCell());
homenumber.setText(contact.getHomeNumber());
email.setText(contact.getEmail());
}
}
use like
Contact contact = theList.get(pos); //contact is the object of the class (small c)

Categories