How to make FirestoreRecyclerAdapter work not with model class? - java

I mean how to make the adapter work not with the model class, but with the already created ArrayList (randomPlaceList)? I take 20 records from my Firestore and put 3 random of them to the ArrayList(randomPlaceList). And now, I want that my adapter connect ViewHolder object not with the model class(Places.class), but with this early created ArrayList(randomPlaceList), where I have already 3 random records..
RecycleView class:
public class Myactivity extends AppCompatActivity {
public RecyclerView mResultList;
public FirebaseFirestore mFirestore;
public com.google.firebase.firestore.Query query;
public FirestoreRecyclerAdapter<Places, PlaceViewHolder> firestoreRecyclerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycle_activity);
mResultList = findViewById(R.id.list_result);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
Boolean l_check2 = getIntent().getExtras().getBoolean("2");
Boolean l_check3 = getIntent().getExtras().getBoolean("3");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("colour", "1").limit(20);
//QUESTION START HERE
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
int placeCount = placesList.size();
int randomNumber = new Random().nextInt(placeCount);
//THIS ARRAYLIST I WANT TO USE INSTEAD THE PLACES.CLASS
List<Places> randomPlaceList = new ArrayList<>();
for (int i=1; i<=3; i++) {
randomPlaceList.add(placesList.get(randomNumber));
}
}
}
});
} else if (l_check2) {
query = mFirestore.collection("Places").whereEqualTo("colour", "2").limit(3);
} else if (l_check3) {
query = mFirestore.collection("Places").whereEqualTo("colour", "3").limit(3);
}
mResultList.setLayoutManager(new LinearLayoutManager(this));
FirestoreRecyclerOptions<Places> options = new FirestoreRecyclerOptions.Builder<Places>()
.setQuery(query, Places.class)
.build();
firestoreRecyclerAdapter = new FirestoreRecyclerAdapter<Places, PlaceViewHolder>(options) {
#Override
protected void onBindViewHolder(PlaceViewHolder holder, int position, Places model) {
holder.setDetails(getApplicationContext(), model.getName(), model.getImage());
}
#Override
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
return new PlaceViewHolder(view);
}
};
mResultList.setAdapter(firestoreRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firestoreRecyclerAdapter.startListening();
}
class PlaceViewHolder extends RecyclerView.ViewHolder {
View mView;
public PlaceViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context context, String placeName, String placeImage) {
final TextView place_Name = mView.findViewById(R.id.text_image_id);
ImageView place_Image = mView.findViewById(R.id.image_id);
place_Name.setText(placeName);
Glide.with(context).load(placeImage).into(place_Image);
place_Name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Card_activity.class);
intent.putExtra("qwerty", place_Name.getText());
startActivity(intent);
}
});
}
}
#Override
protected void onStop() {
super.onStop();
if (firestoreRecyclerAdapter != null) {
firestoreRecyclerAdapter.stopListening();
}
}
}
And that model class, that used in OnCreate method, for query, but I need to use in Adapter, randomPlaceList to take 3 records, that already put earlier in it. In other words, use 2 model class, if I can say so..:
My Model class:
public class Places {
private String image, name;
public Places() { }
public Places(String image, String name) {
this.image = image;
this.name = name;
}
public String getImage() { return image; }
public String getName() { return name; }
}
EDITED WITH LISTVIEW:
MyListAdaper:
class MyListAdapter extends ArrayAdapter {
public MyListAdapter(Context context, int resource,List<Places> randomPLaceList) {
super(context, 0, randomPLaceList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_list, parent, false);
}
TextView place_Name = convertView.findViewById(R.id.text_image_id);
ImageView place_Image = convertView.findViewById(R.id.image_id);
Places places = (Places) getItem(position);
place_Name.setText(places.getName());
Glide.with(getContext()).load(places.getImage()).into(place_Image);
return convertView;
}
}
ListViewPlaces.class:
public class ListViewPlaces extends AppCompatActivity {
public ListView mListView;
public MyListAdapter myListAdapter;
public FirebaseFirestore mFirestore;
public Query query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_places);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("meet", "1").whereEqualTo("cash", "1").limit(7);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
//mListView = findViewById(R.id.place_list);
//mListView.setAdapter(myListAdapter);
final int placeCount = placesList.size();
final Random randomGenerator = new Random();
List<Places> randomPlaceList = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
}
ListView mListView = (ListView) findViewById(R.id.place_list);
MyListAdapter mListAdapter = new MyListAdapter(this, randomPlaceList);
mListView.setAdapter(mListAdapter);
}
}
});
}
}
}
Error:
error: constructor MyListAdapter in class MyListAdapter cannot be
applied to given types; required: Context,int,List found:
>,List reason:
actual and formal argument lists differ in length

Related

Attempt to invoke virtual method 'void.estate.view.adapter.plucking.EmployeePluckingSessionAdapter.setList(java.util.List)' on a null object reference

I am getting this error but I cannot find the reason.
This is my code of Adapter.
public class EmployeePluckingSessionAdapter extends RecyclerView.Adapter<EmployeePluckingSessionAdapter.EmployeePluckingSessionAdapterHolder> {
private SubSessionListActivity.AdapterEvents adapterEvents;
private List<EmployeePluckingCollectionSummary> employeePluckingCollectionSummaries = new ArrayList<>();
public EmployeePluckingSessionAdapter(SubSessionListActivity.AdapterEvents adapterEvents){
this.adapterEvents = adapterEvents;
}
public void setList(List<EmployeePluckingCollectionSummary> employeePluckingCollectionSummaries){
this.employeePluckingCollectionSummaries = employeePluckingCollectionSummaries;
}
public void setAdapterEvents(SubSessionListActivity.AdapterEvents adapterEvents) {
this.adapterEvents = adapterEvents;
}
#NonNull
#Override
public EmployeePluckingSessionAdapterHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plucking_summary_data, parent, false);
return new EmployeePluckingSessionAdapterHolder(view);
}
#Override
public void onBindViewHolder(#NonNull EmployeePluckingSessionAdapterHolder holder, int position) {
EmployeePluckingCollectionSummary employeePluckingCollectionSummary = employeePluckingCollectionSummaries.get(position);
holder.userName.setText(String.valueOf(employeePluckingCollectionSummary.getEmployeeName()));
holder.userId.setText(String.valueOf(employeePluckingCollectionSummary.getEmployeeId()));
holder.session.setText(String.valueOf(employeePluckingCollectionSummary.getSessionName()));
holder.sessionTotal.setText(String.valueOf(employeePluckingCollectionSummary.getWeight()));
}
#Override
public int getItemCount() {
return 0;
}
class EmployeePluckingSessionAdapterHolder extends RecyclerView.ViewHolder {
private final LinearLayout plucking_data;
private final TextView userName;
private final TextView userId;
private final TextView session;
private final TextView sessionTotal;
public EmployeePluckingSessionAdapterHolder(View view) {
super(view);
this.plucking_data = view.findViewById(R.id.plucking_data);
this.userName = view.findViewById(R.id.userName);
this.userId =view.findViewById(R.id.userId);
this.session = view.findViewById(R.id.session);
this.sessionTotal = view.findViewById(R.id.sessionTotal);
}
}
}
This is my code of Activity.
public class PluckingChecklistReportActivity extends AppCompatActivity {
private PluckingCollectionViewModel pluckingCollectionViewModel;
RecyclerView recyclerView;
List<EmployeePluckingCollectionSummary> pluckingSummary = new ArrayList<>();
LinearLayoutManager linearLayoutManager;
EmployeePluckingSessionAdapter employeePluckingSessionAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plucking_checklist_report);
pluckingCollectionViewModel = new ViewModelProvider(this).get(PluckingCollectionViewModel.class);
recyclerView = findViewById(R.id.plucking_data);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(employeePluckingSessionAdapter);
recyclerView.setLayoutManager(linearLayoutManager);
pluckingCollectionViewModel.getEmployeePluckingSessionSummary().observe(this, new Observer<List<EmployeePluckingCollectionSummary>>() {
#Override
public void onChanged(List<EmployeePluckingCollectionSummary> employeePluckingCollectionSummaries) {
pluckingSummary = employeePluckingCollectionSummaries;
employeePluckingSessionAdapter.setList(pluckingSummary);
}
});
}
}
I found that "pluckingSummary" list is null. I don't know how to set values to the list. I tried to set the values to arrayList after convert it into JSONObject but it did not work as well. I get values correctly when I use System.out.println(new Gson().toJson(employeePluckingCollectionSummaries));

How to set banner ad(admob) in firebase recyclerview in android studio

I am a beginner in android development. I make the firebase recycler view and try switch-case to add AdMob ads in the firebase recycler view but it didn't work. anybody, please guide me about banner ad(Admob) in firebase recycler view. [![enter image description here][1]][1]
here is my code :
MyAdapterWith
public class MyAdapterWith extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<Object> list;
DatabaseReference database;
private static final int item_data = 0;
private static final int item_banner = 1;
public MyAdapterWith(Context context, List<Object> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType){
case item_data:
View dataview = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemwith, parent, false);
return new MyViewHolder(dataview);
case item_banner:
default:
View bannerview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bannersinglerow, parent, false);
return new bannerviewholder(bannerview);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
int viewtype = getItemViewType(position);
switch (viewtype){
case item_data:
MyViewHolder mvh = (MyViewHolder) holder;
Historywith users = (Historywith) list.get(position);
mvh.status.setText(users.getStatus());
mvh.created_at.setText(users.getCreated_at());
mvh.plandetails.setText(users.getPlandetails());
mvh.amountfigure.setText(users.getAmountfigure());
mvh.amountwords.setText(users.getAmountwords());
database = FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("requestpayment").child(users.getStatus()).child("status");
if ((Integer.parseInt(users.getStatus()) == 1)){
mvh.statusaccept.setText("Accepted");
mvh.statusaccept.setVisibility(View.VISIBLE);
mvh.statuspendding.setVisibility(View.GONE);
}
else {
if((Integer.parseInt(users.getStatus()) == 0)){
mvh.statuspendding.setText("Pedding");
mvh.statusaccept.setVisibility(View.GONE);
mvh.statuspendding.setVisibility(View.VISIBLE);
}
}
break;
case item_banner:
default:
bannerviewholder bvh = (bannerviewholder) holder;
AdView adView = (AdView) list.get(position);
ViewGroup adcardview = (ViewGroup) bvh.itemView;
if (adcardview.getChildCount()>0)
adcardview.removeAllViews();
if (adcardview.getParent()!=null)
((ViewGroup)adView.getParent()).removeView(adView);
adcardview.addView(adView);
}
}
#Override
public int getItemCount() {
return list.size();
}
public int getItemViewType(int position){
if (position%withdraw.ITEM_PER_AD==0)
return item_banner;
else
return item_data;
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView status, created_at, plandetails, amountfigure, amountwords, statusaccept, statuspendding;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
status = itemView.findViewById(R.id.statuspendding);
created_at = itemView.findViewById(R.id.date);
plandetails = itemView.findViewById(R.id.plandetails);
amountfigure = itemView.findViewById(R.id.amountfigure);
amountwords = itemView.findViewById(R.id.amountwords);
statusaccept = itemView.findViewById(R.id.statusaccept);
statuspendding = itemView.findViewById(R.id.statuspendding);
}
}
public static class bannerviewholder extends RecyclerView.ViewHolder{
public bannerviewholder(#NonNull View itenView){
super(itenView);
}
}
}
withdraw(Activity)
public class withdraw extends AppCompatActivity {
RecyclerView recystatement;
DatabaseReference database;
MyAdapterWith myAdapter;
List<Object> list;
AdView adView;
FirebaseStorage storage;
static int ITEM_PER_AD = 2;
private static final String BANNER_AD_ID = "ca-app-pub-****************~**********";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_withdraw);
recystatement = findViewById(R.id.recystatement);
database = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getUid()).child("requestpayment");
recystatement.setHasFixedSize(true);
recystatement.setLayoutManager(new LinearLayoutManager(this));
storage = FirebaseStorage.getInstance();
list = new ArrayList();
myAdapter = new MyAdapterWith(this, list);
recystatement.setAdapter(myAdapter);
getbanneritems();
loadbannerads();
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.blue)));
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Object users = dataSnapshot.getValue(Object.class);
// users.setUserId(dataSnapshot.getKey());
list.add(users);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public void getbanneritems(){
for (int i=0; i<list.size(); i+=ITEM_PER_AD){
AdView adView = new AdView(withdraw.this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(BANNER_AD_ID);
list.add(i, adView);
}
}
public void loadbannerads(){
for (int i=0; i<list.size(); i++){
Object item = list.get(i);
if (item instanceof AdView){
final AdView adView = (AdView) item;
adView.loadAd(new AdRequest.Builder().build());
}
}
}
}```
[1]: https://i.stack.imgur.com/X84oJ.jpg

How to get total by adding all the recycler views rows

I have recycler view in my activity and below there is a total cost field which shows the total value comes after adding the values from each row. As shown in the screen below:
In a recycler view, there is a spinner that shows quantity on selecting a value from spinner it will be multiplied by the MRP like this every same row have some values. I want to add this value and want to show it in the Lower left corner.
So far I am sending MRP value from adapter class to activity using LocalBroadcatManager class.
But every time I selecting data from another row it does not add cost with the previous value
but it replaces the older value.
Below is my code:
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ProductsModel> productList;
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
if (!item.equals("Select qty")) {
int qty = Integer.parseInt(item);
int cost = Integer.parseInt(model.getMrp());
int val = cost * qty;
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
SelectPack.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pack);
fAuth = FirebaseAuth.getInstance();
ActionBar ab = getSupportActionBar();
assert ab!= null;
ab.setTitle("Select Pack");
ab.setDisplayHomeAsUpEnabled(true);
marketSpinner = findViewById(R.id.marketSpinner);
progress = findViewById(R.id.progress);
products = findViewById(R.id.products);
totalCost = findViewById(R.id.totalCost);
products.setHasFixedSize(true);
products.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<>();
List<String> categories = new ArrayList<String>();
categories.add("Select market");
categories.add("Crown");
categories.add("Long Book A4");
categories.add("Long Book");
categories.add("Crown Junior");
categories.add("Physics");
categories.add("Chemistry");
categories.add("Biology");
categories.add("Universal");
categories.add("Sketch Book");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
marketSpinner.setAdapter(dataAdapter);
marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(item.equals("Select market")){
progress.setVisibility(View.INVISIBLE);
}
else{
getData(item);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
LocalBroadcastManager.getInstance(SelectPack.this).registerReceiver(message,new IntentFilter("msg"));
}
private void getData(String item){
progress.setVisibility(View.VISIBLE);
products.setVisibility(View.INVISIBLE);
productList.clear();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("name",item)
.build();
Request request = new Request.Builder().post(formBody).url(URL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NotNull Call call, #NotNull final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
if(jsonArray.length() > 0){
products.setVisibility(View.VISIBLE);
progress.setVisibility(View.INVISIBLE);
}
for(int i=0;i<jsonArray.length();i++){
progress.setVisibility(View.INVISIBLE);
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("market");
String str2 = object.getString("product_no");
String str3 = object.getString("page");
String str4 = object.getString("mrp");
String str5 = object.getString("inner_pack");
String str6 = object.getString("outer_pack");
Log.d("prod",str2);
ProductsModel model = new ProductsModel(str1,str2,str3,str4,str5,str6);
productList.add(model);
}
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
products.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onFailure(#NotNull Call call, #NotNull final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setVisibility(View.INVISIBLE);
products.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
public BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String nam = intent.getStringExtra("cost");
if(nam != null){
int val = Integer.parseInt(nam);
totalCost.setText("Total: "+val+".00");
}
}
};
Someone, please let me know what I am doing wrong or how should I implement it correctly. Any help would be appreciated.
THANKS
why you are using local broadcasts to communicate with activity. Instead, use interface to communicate it will be easy to use.
I found the problem when the item is getting selected you are passing the only current value not all the selected value that's why it is showing the latest value instead of all the value.
You should pass all the selected values from the list, let's say If I select one value, keep that in the separate list or you can manage with a flag in the current list object and when user selects any item then loop through that list and add all the price and pass it to activity.
Add one field in ProductsModel called Qty
Here is my updated adapter class I have added a comment as well please try this Hope it helps
public class ProductAdapter extends RecyclerView.Adapter {
private Context context;
private List<ProductsModel> productList;
// add this list
private List<ProductsModel> selectedProductList = new ArrayList();
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
// add this line
adapterView.getItemAtPosition(i);
if (!item.equals("Select qty")) {
// add this line
model.setQty(Integer.parseInt(item));
selectedProductList.add(model);
}
int val = 0;
for(int j = 0; j < selectedProductList.size(); j++){
ProductsModel model = selectedProductList.get(i);
int mrp = model.getMrp();
int qty = model.getQty();
val = val + (mrp * qty);
}
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}

RecyclerView doesn't inflate, rather updates the same view?

I have an activity to implement a to-do list, containing a recyclerview with each item being a checkbox and textview, and each task is added from an edittext.
It stores data using Realm.io. The behaviour that I keep getting is that the single element in the recyclerview merely get updated, and not inflated! Please help.
TasksActivity -
public class TasksActivity extends AppCompatActivity implements View.OnClickListener{
TextView courseTitle;
RecyclerView TaskList;
EditText addTask;
Button addButton;
String transName; //Transferred Course name from MainActivity
TaskAdapter TA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
courseTitle = findViewById(R.id.CourseName);
TaskList = findViewById(R.id.TaskListRV);
TaskList.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
addTask = findViewById(R.id.InputTask);
addButton = findViewById(R.id.AddTaskButton);
//Course name is the obtained from the previous acivity.
transName =getIntent().getExtras().getString("CourseName");
courseTitle.setText(transName);
TA = new TaskAdapter(transName);
TaskList.setAdapter(TA);
addButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String task = addTask.getText().toString();
// Checking if the text is empty.
boolean flag = false;
for(int i = 0;i<task.length();i++)
{
if(task.charAt(i)!=' ')
flag = true;
}
if(!flag || task.equals(""))
{
Toast emptyWarning = Toast.makeText(getApplicationContext(),"Task cannot be Empty!",Toast.LENGTH_SHORT);
emptyWarning.show();
}
else
{
addTask.setText("");
TA.addNewTask(task);
}
}
}
TasksAdapter -
public class TaskAdapter extends RecyclerView.Adapter<TaskViewHolder> implements RealmChangeListener<RealmResults<TaskModel>>
{
private ArrayList<TaskModel> TaskList;
private String course;
private final Realm realm;
public TaskAdapter(String course)
{
this.course = course;
this.TaskList = new ArrayList<>();
realm = Realm.getDefaultInstance();
loadTaskData();
}
void loadTaskData()
{
RealmResults<TaskModel> taskModelRealmResults = realm.where(TaskModel.class).equalTo("courseName",course).findAll();
taskModelRealmResults.addChangeListener(this);
for(TaskModel iTM : taskModelRealmResults)
{
TaskList.add(realm.copyFromRealm(iTM));
}
notifyDataSetChanged();
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view= layoutInflater.inflate(R.layout.item_task,parent,false);
TaskViewHolder Tvh = new TaskViewHolder(view);
return Tvh;
}
#Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
holder.populateTask(TaskList.get(position));
}
#Override
public int getItemCount() {
return TaskList.size();
}
public void addNewTask(String task)
{
TaskModel newTaskObj = new TaskModel(task,course,false);
TaskList.add(newTaskObj);
notifyDataSetChanged();
realm.beginTransaction();
realm.insertOrUpdate(newTaskObj);
realm.commitTransaction();
}
#Override
public void onChange(RealmResults<TaskModel> taskModels) {
taskModels = realm.where(TaskModel.class).equalTo("courseName",course).findAll();
this.TaskList = new ArrayList<>();
for(TaskModel iTM : taskModels)
{
this.TaskList.add(realm.copyFromRealm(iTM));
}
notifyDataSetChanged();
}
}
TaskViewHolder and TaskModel - (in case you might need them)
public class TaskModel extends RealmObject {
String task;
#PrimaryKey
String courseName;
boolean isDone;
public TaskModel() {
task = "";
courseName = "";
isDone = false;
}
public TaskModel(String task, String courseName, boolean isDone) {
this.task = task;
this.courseName = courseName;
this.isDone = isDone;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean done) {
isDone = done;
}
}
public class TaskViewHolder extends RecyclerView.ViewHolder {
CheckBox isdone;
TextView Taskname;
public TaskViewHolder(View itemView) {
super(itemView);
isdone = itemView.findViewById(R.id.TaskCheckBox);
Taskname = itemView.findViewById(R.id.TaskName);
}
void populateTask(final TaskModel T)
{
Taskname.setText(T.getTask());
isdone.setChecked(T.isDone());
isdone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
T.setDone(isdone.isChecked());
}
});
}
}
I advise you to use Realm Android dapter, this adapter is taking care of updating your app UI. Don't need to implement OnChangeListener, your list will be automatically updated after insertion, deletion or edition
Use findAllAsync in order to not block the UI thread
OrderedRealmCollection<TaskModel> taskModels = realm.where(TaskModel.class).equalTo("courseName", course).findAllAsync();
public RealmAdapter(OrderedRealmCollection<TaskModel> data) {
super(data, true);
}
EDIT:
Also always do the process using Async method when it's possible. You can replace your addNewTask method by:
public void addNewTask(String task) {
final TaskModel newTaskObj = new TaskModel(task, course, false);
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(newTaskObj);
}
});
}
Yous should have something like this:
TasksActivity
public class TasksActivity extends AppCompatActivity implements View.OnClickListener {
private EditText addTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
String transName = getIntent().getExtras().getString("CourseName");
TextView courseTitle = findViewById(R.id.CourseName);
courseTitle.setText(transName);
addTask = findViewById(R.id.InputTask);
findViewById(R.id.AddTaskButton).setOnClickListener(this);
OrderedRealmCollection<TaskModel> taskModels = Realm.getDefaultInstance().where(TaskModel.class).equalTo("courseName", transName).findAllAsync()
TaskAdapter adapter = new TaskAdapter(this, taskModels);
RecyclerView taskList = findViewById(R.id.TaskListRV);
taskList.setLayoutManager(new LinearLayoutManager(this));
taskList.setAdapter(adapter);
}
#Override
public void onClick(View view) {
String task = addTask.getText().toString().trim();
if (task.trim().isEmpty()) {
Toast emptyWarning = Toast.makeText(getApplicationContext(),"Task cannot be Empty!",Toast.LENGTH_SHORT);
emptyWarning.show();
return;
}
addTask.setText("");
addNewTask(task);
}
private void addNewTask(String task) {
final TaskModel newTaskObj = new TaskModel(task, course, false);
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(newTaskObj);
}
});
}
}
And TaskAdapter:
public class TaskAdapter extends RealmRecyclerViewAdapter<TaskModel, TaskViewHolder> {
private LayoutInflater layoutInflater
public TaskAdapter(Context context, OrderedRealmCollection<TaskModel> taskModels) {
super(taskModels, true);
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new TaskViewHolder(layoutInflater.inflate(R.layout.item_task , parent, false));
}
#Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
holder.populateTask(getItem(position));
}
}
OP here. I ended up using the standard ReacyclerView.Adapter.
The problem was with the usage of Realm's insertOrUpdate method, when the #PrimaryKey was courseName which thus caused it to indeed update the same object and not create a new one!
insert() should have been used.
Here is the insert task method -
public void addNewTask(String task)
{
boolean flag = false;
for(int i = 0;i<TaskList.size();i++)
{
if(task.equals(TaskList.get(i).getTask()))
{
Toast.makeText(context,"Task already exists!",Toast.LENGTH_SHORT).show();
flag = true;
break;
}
}
if(!flag)
{
TaskModel newTaskObj = new TaskModel();
newTaskObj.setTask(task);
newTaskObj.setDone(false);
newTaskObj.setCourseName(course);
TaskList.add(newTaskObj);
notifyDataSetChanged();
realm.beginTransaction();
realm.insert(newTaskObj);
realm.commitTransaction();
} }
The entire project can be found here, do check it out -
https://github.com/Hariram-R/ToDoList-App

get and set global variables from CustomListViewAdapter

Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}

Categories