I have made an android application using java, and I have made a click listener interface but nothing seems to happen and I can't figure out what is wrong with my code. Please help.
Following is the code of my recyclerViewAdapter:
package com.example.ashwamedh.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.ashwamedh.R;
import com.example.ashwamedh.model.AdminConfirmation;
import com.example.ashwamedh.model.Attendance;
import com.example.ashwamedh.model.Confirmation;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.List;
import java.util.Objects;
public class ManageAttendanceRecyclerViewAdapter extends RecyclerView.Adapter<ManageAttendanceRecyclerViewAdapter.ViewHolder> {
private List<Confirmation> practiceList;
private Context context;
private OnAttendanceClickListener onAttendanceClickListener;
private CollectionReference collectionReference = FirebaseFirestore.getInstance().collection("Users");
public ManageAttendanceRecyclerViewAdapter(List<Confirmation> practiceList, Context context, OnAttendanceClickListener onAttendanceClickListener) {
this.practiceList = practiceList;
this.context = context;
this.onAttendanceClickListener = onAttendanceClickListener;
}
#NonNull
#Override
public ManageAttendanceRecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context)
.inflate(R.layout.manage_attendance_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(#NonNull ManageAttendanceRecyclerViewAdapter.ViewHolder holder, int position) {
Confirmation confirmation = practiceList.get(position);
holder.nameTextView.setText(confirmation.getUsername());
if (confirmation.getRemarkOrReason() == "") {
holder.remarkOrReasonTextView.setText("null");
}else {
holder.remarkOrReasonTextView.setText(confirmation.getRemarkOrReason());
}
if (Objects.equals(confirmation.getConfirmation(), "present")) {
holder.confirmation.setImageResource(R.drawable.ic_baseline_check_24);
} else if (Objects.equals(confirmation.getConfirmation(), "absent")){
holder.confirmation.setImageResource(R.drawable.ic_baseline_close_24);
}
}
#Override
public int getItemCount() {
return practiceList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView nameTextView;
private ImageView confirmation;
private TextView remarkOrReasonTextView;
OnAttendanceClickListener onAttendanceClickListener;
public ViewHolder(#NonNull View itemView, Context ctx) {
super(itemView);
this.onAttendanceClickListener = ManageAttendanceRecyclerViewAdapter.this.onAttendanceClickListener;
context = ctx;
nameTextView = itemView.findViewById(R.id.manage_attendance_name_textview);
confirmation = itemView.findViewById(R.id.manage_attendance_confirmation);
remarkOrReasonTextView = itemView.findViewById(R.id.manage_attendance_remark_reason_textview);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.manage_attendance_row:
Log.d("from recycler view", "onClick: " + "row clicked");
Confirmation confirmation = practiceList.get(getAdapterPosition());
String userId = confirmation.getUserId();
onAttendanceClickListener.OnAttendanceClick(userId);
}
}
}
}
Following is the code of OnAttendanceClickListener:
package com.example.ashwamedh.adapter;
public interface OnAttendanceClickListener {
void OnAttendanceClick(String userId);
}
Following is the code of the activity where the recycler view is used and the interface implemented:
package com.example.ashwamedh;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ashwamedh.adapter.ManageAttendanceRecyclerViewAdapter;
import com.example.ashwamedh.adapter.OnAttendanceClickListener;
import com.example.ashwamedh.model.Confirmation;
import com.example.ashwamedh.util.UserApi;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class ManagePracticeConfirmationActivity extends AppCompatActivity implements OnAttendanceClickListener {
private static final String TAG = "PRACTICE_CONFIRMATION";
private RecyclerView recyclerView;
private BottomNavigationView bottomNavigationView;
private CardView markAttendanceCardView;
private FloatingActionButton presentFab;
private FloatingActionButton absentFab;
private Button updateButton;
private TextView noPracticeTextView;
private ImageButton signOut;
private Boolean isAdmin;
private String attendance;
private ManageAttendanceRecyclerViewAdapter manageAttendanceRecyclerViewAdapter;
private String practiceDate;
private List<Confirmation> practiceList;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference collectionReference = db.collection("Confirmations");
private CollectionReference userCollection = db.collection("Users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_practice_confirmation);
Objects.requireNonNull(getSupportActionBar()).hide();
practiceList = new ArrayList<>();
recyclerView = findViewById(R.id.manage_attendance_recycler_view);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
markAttendanceCardView = findViewById(R.id.mark_attendance_cardView);
presentFab = findViewById(R.id.present_fab);
absentFab = findViewById(R.id.absent_fab);
updateButton = findViewById(R.id.update_attendance_button);
noPracticeTextView = findViewById(R.id.no_practice_textView);
signOut = findViewById(R.id.signOut_manage_attendance);
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
bottomNavigationView.setSelectedItemId(R.id.manage_practice_confirmation_button);
markAttendanceCardView.setVisibility(View.INVISIBLE);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
attendance = "";
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
Log.d(TAG, "onCreate: " + Calendar.DAY_OF_WEEK);
if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
recyclerView.setVisibility(View.INVISIBLE);
noPracticeTextView.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
noPracticeTextView.setVisibility(View.INVISIBLE);
}
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.council_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, CouncilActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.attendance_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, BatchmateAttendance.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.manage_practice_confirmation_button) {
return true;
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
collectionReference.whereEqualTo("practiceDate", practiceDate)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) {
Confirmation confirmation = snapshot.toObject(Confirmation.class);
practiceList.add(confirmation);
}
manageAttendanceRecyclerViewAdapter = new ManageAttendanceRecyclerViewAdapter(practiceList,
ManagePracticeConfirmationActivity.this,
ManagePracticeConfirmationActivity.this);
recyclerView.setAdapter(manageAttendanceRecyclerViewAdapter);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
#Override
public void OnAttendanceClick(String userId) {
Log.d(TAG, "OnAttendanceClick: "+ isAdmin);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
if (isAdmin) {
markAttendanceCardView.setVisibility(View.VISIBLE);
presentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "present";
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
}
});
absentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "absent";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
}
});
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Confirmation confirmation = new Confirmation();
confirmation.setUserId(userId);
confirmation.setConfirmation(attendance);
confirmation.setPracticeDate(practiceDate);
if (Objects.equals(attendance, "present")) {
confirmation.setRemarkOrReason("PRESENT ON PRACTICE");
} else if (Objects.equals(attendance, "absent")){
confirmation.setRemarkOrReason("ABSENT ON PRACTICE");
}
SimpleDateFormat documentDateFormat = new SimpleDateFormat("dd_MM_yyyy");
String docDate = documentDateFormat.format(practiceDate);
String docAddress = userId+"_"+docDate;
collectionReference.document(docAddress)
.set(confirmation)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Attendance marked!", Toast.LENGTH_SHORT)
.show();
}
});
attendance = "";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
markAttendanceCardView.setVisibility(View.INVISIBLE);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
});
} else {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Only admins can mark attendance!", Toast.LENGTH_SHORT)
.show();
}
}
}
Please help me I am clueless of where is the error
RecyclerView clicks doesn't work like that.
Firstly you should write click event in onBindViewHolder
holder.itemView.setOnClickListener(view -> onAttendanceClickListener.OnAttendanceClick(userId));
Put this code in your onBindViewHolder and you are good to go!
You will receive click events in Activity.
Related
I wanna ask regarding this recycleview issues, my code doesnt show any problem,but why my recycleview output became like this RecycleView Output. I had tried by change switch case() to if else() but it will give error if I write throw new IllegalStateException("Unexpected value:" + data.getItem()); at the end of else. The app will crash and stop running if I did not commend the exception. When I still using switch case, it will came out an error of NullException
This is my code:
MainActivity() code
package com.example.assignment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button AddBtn;
private Button signOutBtn;
private RecyclerView recyclerView;
private FirebaseAuth auth;
private DatabaseReference ref;
private String userID = "";
private ProgressDialog progressDialog;
private ItemsAdapter itemsAdapter;
private ArrayList<Data> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
textView=findViewById(R.id.totalAmount);
AddBtn = findViewById(R.id.add_new);
auth = FirebaseAuth.getInstance();
userID = auth.getCurrentUser().getUid();
ref = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
progressDialog = new ProgressDialog(this);
AddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addItem();
}
});
recyclerView =findViewById(R.id.recycleView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
dataList = new ArrayList<>();
itemsAdapter = new ItemsAdapter(MainActivity.this, dataList);
recyclerView.setAdapter(itemsAdapter);
readItems();
// signOutBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// FirebaseAuth.getInstance().signOut();
// }
// });
}
private void readItems(){
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar = Calendar.getInstance();
String date = format.format(calendar.getTime());
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
Query query = databaseReference.orderByChild("date").equalTo(date);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
dataList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Data data = snapshot.getValue(Data.class);
dataList.add(data);
}
itemsAdapter.notifyDataSetChanged();
int totalAmount = 0;
for(DataSnapshot ds : snapshot.getChildren()){
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object total = map.get("amount");
int getTotal = Integer.parseInt(String.valueOf(total));
totalAmount+=getTotal;
textView.setText("Total Spending : RM" + totalAmount);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void addItem() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//LayoutInflater layout = LayoutInflater.from(this);
LayoutInflater layout = getLayoutInflater();
View view = layout.inflate(R.layout.input_layout, (ViewGroup)findViewById(R.id.inputLayout));
setContentView(view);
final AlertDialog dialog = alert.create();
dialog.setCancelable(false);
final Spinner spinnerItem = view.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.category));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerItem.setAdapter(adapter);
final EditText amount = view.findViewById(R.id.insert_amount);
final EditText notes = view.findViewById(R.id.insert_note);
final Button saveButton = view.findViewById(R.id.add_button);
final Button cancelButton = view.findViewById(R.id.cancel_button);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountGet = amount.getText().toString();
String notesGet = notes.getText().toString();
String categoryGet = spinnerItem.getSelectedItem().toString();
Drawable icon = getResources().getDrawable(R.drawable.error);
if(amountGet.isEmpty()){
amount.setError("Please enter an amount!!!", icon );
return;
}
if(notesGet.isEmpty()){
notes.setError("Please enter a notes!!!", icon );
return;
}
if(categoryGet.equals("Select a Category")){
Toast.makeText(MainActivity.this, "Please select a valid category", Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Had added the information into database");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
String id = ref.push().getKey();
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar = Calendar.getInstance();
String date = format.format(calendar.getTime());
Data inform = new Data(categoryGet, date, id, notesGet, Integer.parseInt(amountGet));
ref.child(id).setValue(inform).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Information added successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Fail to add the information", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
});
}
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
dialog.dismiss();
}
});
}
}
ItemsAdapter() code
package com.example.assignment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.viewHolder> {
private Context context;
private List<Data> dataList;
public ItemsAdapter(Context context, List<Data> data) {
this.context = context;
this.dataList = data;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.output_layout, parent, false);
//return new ItemsAdapter.viewHolder(view);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
final Data data = dataList.get(position);
holder.category.setText("Category :" + data.getItem());
holder.amount.setText("Amount :" + data.getAmount());
holder.date.setText("Date :" + data.getDate());
holder.notes.setText("Note :" + data.getNotes());
// switch(data.getItem()){
//
// case "Petrol Spend":
// holder.imageView.setImageResource(R.drawable.petrol);
// break;
//
// case "Groceries Spend":
// holder.imageView.setImageResource(R.drawable.grocery);
// break;
//
// case "eWallet Transaction":
// holder.imageView.setImageResource(R.drawable.wallet);
// break;
//
// case "Other Eligible Spend":
// holder.imageView.setImageResource(R.drawable.spend);
// break;
//
// default:
// throw new IllegalStateException("Unexpected value:" + data.getItem());
// }
if(data.getItem() == "Petrol Spend"){
holder.imageView.setImageResource(R.drawable.petrol);
}else if(data.getItem() == "Groceries Spend"){
holder.imageView.setImageResource(R.drawable.grocery);
}else if(data.getItem() == "eWallet Transaction"){
holder.imageView.setImageResource(R.drawable.wallet);
}else if(data.getItem() == "Other Eligible Spend"){
holder.imageView.setImageResource(R.drawable.spend);
}
//else throw new IllegalStateException("Unexpected value:" + data.getItem());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
public TextView category, amount, date, notes;
public ImageView imageView;
public viewHolder(#NonNull View itemView) {
super(itemView);
category = itemView.findViewById(R.id.category);
amount = itemView.findViewById(R.id.amount);
date = itemView.findViewById(R.id.date);
notes = itemView.findViewById(R.id.note);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
Instead of :
dataList.add(data);
itemsAdapter.notifyDataSetChanged();
Try this:
// add this in the place of dataList.add(data)
adapter.setDataList(data);
// Add this setter inside the adapter;
setDataList(List<Data> datalist){
this.dataList = dataList;
notifyItemChanged(0,dataList);
}
I want to get total price in Activity from Price and Quantity in Adapter, it's mean like qty * price = total_price.
Here is my Adapter for handling the list of Items Activity:
package com.example.aulaherbalfinal.Adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.R;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
public class AdapterDataPembelian extends RecyclerView.Adapter<AdapterDataPembelian.HolderDataPembelian>{
private Context ctx;
private List<DataModel> listDataPembelian;
private int count;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
}
#NonNull
#Override
public HolderDataPembelian onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item_pembelian, parent, false);
HolderDataPembelian holder = new HolderDataPembelian(layout);
return holder;
}
#Override
public void onBindViewHolder(#NonNull HolderDataPembelian holder, int position) {
DataModel dm = listDataPembelian.get(position);
holder.tvId.setText(String.valueOf(dm.getId()));
holder.tvBarang.setText(dm.getBarang());
holder.tvStok.setText("Stok : "+String.valueOf(dm.getStok()));
holder.tvHarga.setText(formatRupiah(Double.parseDouble(String.valueOf(dm.getHarga()))));
holder.jmlBarang.setText(String.valueOf(dm.getQuantity()));
//holder.totalHarga.setText(String.valueOf(dm.getTotalHarga()));
Intent intent = new Intent("custom-message");
holder.btnRemove.setOnClickListener(v -> {
minusCartItem(holder,listDataPembelian.get(position));
});
holder.btnAdd.setOnClickListener(v -> {
plusCartItem(holder,listDataPembelian.get(position));
});
}
private void plusCartItem(HolderDataPembelian holder, DataModel dataModel) {
dataModel.setQuantity(dataModel.getQuantity()+1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
}
private void minusCartItem(HolderDataPembelian holder, DataModel dataModel) {
if (dataModel.getQuantity() > 0){
dataModel.setQuantity(dataModel.getQuantity()-1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
} else {
holder.jmlBarang.setText("0");
}
}
#Override
public int getItemCount() {
return listDataPembelian.size();
}
public class HolderDataPembelian extends RecyclerView.ViewHolder {
TextView tvId, tvBarang, tvStok, tvHarga;
Button btnAdd, btnRemove;
TextView jmlBarang, totalHarga;
public HolderDataPembelian(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.tv_id);
tvBarang = itemView.findViewById(R.id.tv_barang);
tvStok = itemView.findViewById(R.id.tv_stok);
tvHarga = itemView.findViewById(R.id.tv_harga);
btnAdd = itemView.findViewById(R.id.btn_add);
btnRemove = itemView.findViewById(R.id.btn_remove);
jmlBarang = itemView.findViewById(R.id.jml_barang);
totalHarga = itemView.findViewById(R.id.total_harga);
}
}
private String formatRupiah(Double number){
Locale localeID = new Locale("IND", "ID");
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(localeID);
String formatRupiah = numberFormat.format(number);
String[] split = formatRupiah.split(",");
int length = split[0].length();
return split[0].substring(0,2)+". "+split[0].substring(2,length);
}
public int getTotalPrice(){
int totalPrice = 0;
for (int i=0 i<listDataPembelian.size(); i++){
}
}
}
And here is my Activity
package com.example.aulaherbalfinal.Activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aulaherbalfinal.API.APIRequestData;
import com.example.aulaherbalfinal.API.RetroServer;
import com.example.aulaherbalfinal.Adapter.AdapterDataPembelian;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.Model.ResponseModel;
import com.example.aulaherbalfinal.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PembelianActivity extends AppCompatActivity {
private RecyclerView rvData;
private RecyclerView.Adapter adData;
private RecyclerView.LayoutManager lmData;
private List<DataModel> listDataPembelian = new ArrayList<>();
private SwipeRefreshLayout srlData;
private ProgressBar pbData;
private TextView totalHarga;
private EditText jmlBarang;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pembelian);
rvData = findViewById(R.id.rv_data);
lmData = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rvData.setLayoutManager(lmData);
srlData = findViewById(R.id.srl_data);
pbData = findViewById(R.id.pb_data);
totalHarga = findViewById(R.id.total_harga);
jmlBarang = findViewById(R.id.jml_barang);
totalHarga = findViewById(R.id.total_harga);
//retrieveData();
CardView cvTotal = findViewById(R.id.cv_total);
rvData.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE){
cvTotal.setVisibility(View.INVISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP){
cvTotal.setVisibility(View.VISIBLE);
}
return false;
}
});
BottomNavigationView bottom_navigation = findViewById(R.id.bottom_navigation);
bottom_navigation.setItemIconTintList(null);
bottom_navigation.setSelectedItemId(R.id.navigation_pembelian);
ImageView profile =findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PembelianActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
});
bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch ( (item.getItemId())){
case R.id.navigation_stok:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.navigation_pembelian:
return true;
case R.id.navigation_penjualan:
startActivity(new Intent(getApplicationContext(), PenjualanActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
srlData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
srlData.setRefreshing(true);
retrieveData();
srlData.setRefreshing(false);
}
});
}
#Override
protected void onResume() {
super.onResume();
retrieveData();
}
public void retrieveData(){
pbData.setVisibility(View.VISIBLE);
APIRequestData ardData = RetroServer.konekRetrofit().create(APIRequestData.class);
Call<ResponseModel> tampildata = ardData.ardRetrieveData();
tampildata.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
//Toast.makeText(MainActivity.this, "Kode : "+kode+" | Pesan : "+pesan, Toast.LENGTH_SHORT).show();
listDataPembelian = response.body().getData();
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian);
rvData.setAdapter(adData);
adData.notifyDataSetChanged();
pbData.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(PembelianActivity.this, "Gagal Menghubungi Server", Toast.LENGTH_SHORT).show();
pbData.setVisibility(View.INVISIBLE);
}
});
}
}
Here is my app
I would do something like this:
Create an Interface for your activity to implement:
public interface CallbackIF {
double tally(double amount, int quantity)
}
public class PembelianActivity extends AppCompatActivity implements CallbackIF {
#Override
public double tally(double amount, int quantity) {
return amount * quantity;
}
}
Then when you initialize your recyclerview adapter pass in the interface like so:
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian, PembelianActivity.this);
And change your constructor for the data adapter to be
private CallbackIF callback;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian, CallbackIF callback) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
this.callback = callback;
}
Then in your onClicklistener for your list / wherever you want to trigger a tally just call
double value = callback.tally(amount, quantity);
If you have any questions please ask
Hey i want to implement google billing into my app but everytime i open the activty where the button is to call my purchase the Console prints
"E/RecyclerView: No adapter attached; skipping layout"
I have a ProductAdapterclass my Information Activity where the button is located.
package com.test.smartbuyapp.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.SkuDetails;
import com.test.smartbuyapp.InformationActivity;
import com.test.smartbuyapp.Interface.IProductClickListener;
import com.test.smartbuyapp.R;
import java.util.List;
public class MyProductAdapter extends RecyclerView.Adapter<MyProductAdapter.MyViewHolder> {
InformationActivity informationActivity;
List<SkuDetails> skuDetailsList;
BillingClient billingClient;
public MyProductAdapter(InformationActivity informationActivity, List<SkuDetails> skuDetailsList, BillingClient billingClient) {
this.informationActivity = informationActivity;
this.skuDetailsList = skuDetailsList;
this.billingClient = billingClient;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(informationActivity.getBaseContext())
.inflate(R.layout.layout_product_item,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.txt_product.setText(skuDetailsList.get(position).getTitle());
//Product click
holder.setiProductClickListener(new IProductClickListener() {
#Override
public void onProductClickListerner(View view, int position) {
//Launch Billing flow
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(position))
.build();
billingClient.launchBillingFlow(informationActivity,billingFlowParams);
}
});
}
#Override
public int getItemCount() {
return skuDetailsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txt_product;
IProductClickListener iProductClickListener;
public void setiProductClickListener(IProductClickListener iProductClickListener) {
this.iProductClickListener = iProductClickListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txt_product = (TextView) itemView.findViewById(R.id.txt_product_name);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
iProductClickListener.onProductClickListerner(v, getAdapterPosition());
}
}
}
And My Informationactivity
package com.test.smartbuyapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.test.smartbuyapp.Adapter.MyProductAdapter;
import java.util.Arrays;
import java.util.List;
public class InformationActivity extends AppCompatActivity implements PurchasesUpdatedListener {
BillingClient billingClient;
Button loadProduct;
RecyclerView recyclerProduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
setupBillingClient();
//View
loadProduct = (Button) findViewById(R.id.btn_load_product);
recyclerProduct = (RecyclerView)findViewById(R.id.recycler_product);
recyclerProduct.setLayoutManager(new LinearLayoutManager(this));
recyclerProduct.setHasFixedSize(true);
//Event
loadProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(billingClient.isReady()) {
SkuDetailsParams params = SkuDetailsParams.newBuilder()
.setSkusList(Arrays.asList("adfree"))
.setType(BillingClient.SkuType.INAPP)
.build();
billingClient.querySkuDetailsAsync(params, new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
loadProductToRecyclerView(list);
}else{
Toast.makeText(InformationActivity.this,"Cannot query product",Toast.LENGTH_SHORT);
}
}
});
}else {
Toast.makeText(InformationActivity.this,"Billing client not Ready",Toast.LENGTH_SHORT);
}
}
});
//////////// Toolbar //////////////////////////////////////////////////////////////
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Information");
}
private void loadProductToRecyclerView(List<SkuDetails> list) {
MyProductAdapter adapter= new MyProductAdapter(this,list,billingClient);
recyclerProduct.setAdapter(adapter);
}
private void setupBillingClient() {
billingClient = BillingClient.newBuilder(this).setListener(this).enablePendingPurchases().build();
billingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
Toast.makeText(InformationActivity.this,"Sucessfully Billing Connect",Toast.LENGTH_SHORT);
}else {
Toast.makeText(InformationActivity.this,"Failed to Billing Connect"+billingResult.getResponseCode(),Toast.LENGTH_SHORT);
}
}
#Override
public void onBillingServiceDisconnected() {
Toast.makeText(InformationActivity.this,"You are disconnected from billing",Toast.LENGTH_SHORT);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
startActivity(new Intent(com.test.smartbuyapp.InformationActivity.this, ListMainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return true;
}
return false;
}
public void PrivacyPerform(View view) {
TextView agb = (TextView) findViewById(R.id.AGB);
agb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://sites.google.com/view/smartbuyapp/"));
startActivity(intent);
}
});
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> list) {
//Here if user clicks Buy, we will receive data
Toast.makeText(InformationActivity.this,"Purchase item",Toast.LENGTH_SHORT);
}
}
Excuse me i already had an Application which Display my Sites articles and Novels in Android the codes in Main Activity to display only one Section
i create in the site 5 sections every section had a different content
i Added items to Navigation Drawers and i defined the fragment and its connectivity but the Problem in the Code i failed so
i want to know how to load Data in 4 Fragments
RecyclerViewAdapter.class
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int previousPosition = 0;
private List<com.salim3dd.recyclerview_moredata.List_Item> List_Item;
private Context context;
public RecyclerViewAdapter(List<List_Item> list_Item, Context context) {
List_Item = list_Item;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View menu1 = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.row_item, viewGroup, false);
return new MenuItemViewHolder(menu1);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
menuItemHolder.TextName.setText(List_Item.get(position).getStory());
Picasso.with(context).load(List_Item.get(position).getImg_link()).into(menuItemHolder.imageView);
menuItemHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, List_Item.get(position).getStory(), Toast.LENGTH_SHORT).show();
}
});
if (position > previousPosition) { //scrolling DOWN
AnimationUtil.animate(menuItemHolder, true);
} else { // scrolling UP
AnimationUtil.animate(menuItemHolder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return (null != List_Item ? List_Item.size() : 0);
}
protected class MenuItemViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView imageView;
private TextView TextName;
public MenuItemViewHolder(View view) {
super(view);
cardView = (CardView) view.findViewById(R.id.cardView);
imageView = (ImageView) view.findViewById(R.id.imageView);
TextName = (TextView) view.findViewById(R.id.TextName);
}
}
}
MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.salim3dd.recyclerview_moredata.CheckInternetConnection;
import com.salim3dd.recyclerview_moredata.List_Item;
import com.salim3dd.recyclerview_moredata.R;
import com.salim3dd.recyclerview_moredata.RecyclerViewAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerView_dAdapter;
public List<List_Item> listItem = new ArrayList<>();
private GridLayoutManager gridLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.m_RecyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView_dAdapter = new RecyclerViewAdapter(listItem, this);
recyclerView.setAdapter(recyclerView_dAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (gridLayoutManager.findLastCompletelyVisibleItemPosition() == listItem.size() - 1) {
Get_All_Users(listItem.get(listItem.size()-1).getId());
}
}
});
Get_All_Users(0);
}
public void Get_All_Users(int limit) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"Data Link" + limit
,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonResponse = jsonArray.getJSONObject(0);
JSONArray jsonArray_usersS = jsonResponse.getJSONArray("All_storys");
for (int i = 0; i < jsonArray_usersS.length(); i++) {
JSONObject responsS = jsonArray_usersS.getJSONObject(i);
int id = responsS.getInt("id");
String story = responsS.getString("story_name");
String img_link = responsS.getString("img_link");
listItem.add(new List_Item(id, story, img_link));
}
recyclerView_dAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
stringRequest.setShouldCache(false);
}
}
}
List Items.class
public class List_Item {
public int id;
public String story;
public String img_link;
public List_Item(int id, String story, String img_link) {
this.id = id;
this.story = story;
this.img_link = img_link;
}
public int getId() {
return id;
}
public String getStory() {
return story;
}
public String getImg_link() {
return img_link;
}
public void setId(int id) {
this.id = id;
}
}
I have this weird periodic error, when i boot the app, and the onCreate is called, but the CardView is not showing anything. Other times I do the exact same thing, booting the app, and the CardView is showing exactly what it should.
I can't seem to find the error..
The main class:
package lassebjoerklund.easyfridge;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class BootActivity extends Activity {
//TODO Make get method for table with barcode.
//TODO Update postRequest so that it macthes the barcode to the database, and getting a json object. object -> toString
private ArrayList<Products> productsToDisplayInlist;
private String TAG = BootActivity.class.getSimpleName();
private String getDataurl = "http://XXX.XXX.XXX.XXX/selectAll.php";
private static String insertDataUrl = "http://XXX.XXX.XXX.XXX/insertAll.php";
private JsonArrayRequest jsonArrayRequest;
private RecyclerView.Adapter mAdapter;
private String jsonRespons = "";
private static RequestQueue rQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Layout
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boot_layout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.cardList);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
//RequestQueue
rQueue = Volley.newRequestQueue(this);
productsToDisplayInlist = new ArrayList<>();
getRequest();
Log.d(TAG, productsToDisplayInlist.toString());
mAdapter = new ProductCardAdapter(productsToDisplayInlist);
recyclerView.setAdapter(mAdapter);
//Intent to switch to activity
//final Intent dispalyProductsIntent = new Intent(BootActivity.this, ProductViewController.class);
//final Intent scanBarcodeIntent = new Intent(BootActivity.this, BarcodeTracking.class);
//final ImageButton updateViewButton = (ImageButton) findViewById(R.id.bViewProducts);
/*updateViewButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dispalyProductsIntent);
}
});*/
/* final ImageButton addNewEntry = (ImageButton) findViewById(R.id.addEntry);
addNewEntry.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
startActivity(scanBarcodeIntent);
}
});*/
}
#Override
protected void onResume() {
Log.d("onResume", "onResume");
/*Toast toast = Toast.makeText(this, "onResume", Toast.LENGTH_LONG);
toast.show();*/
super.onResume();
}
#Override
protected void onRestart() {
Log.d("onRestart", "onRestart");
/*Toast toast = Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT);
toast.show();*/
super.onRestart();
}
#Override
protected void onStop() {
Log.d("onStop", "onStop");
// productsToDisplayInlist.clear();
super.onStop();
}
#Override
protected void onPause() {
Log.d("onPause", "onPause");
super.onPause();
}
//TODO make error msg if there is no connection.
public void getRequest() {
productsToDisplayInlist.clear();
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getDataurl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject productToBuild = (JSONObject) response.get(i);
jsonRespons = productToBuild.toString();
String barcode = productToBuild.getString("code");
String name = productToBuild.getString("name");
String type = productToBuild.getString("type");
int id = productToBuild.optInt("id");
String rmDate = productToBuild.getString("rm_date");
String exDate = productToBuild.getString("ex_date");
String placementDate = productToBuild.getString("add_date");
Products product = new Products(barcode, name, placementDate, exDate, rmDate, type);
productsToDisplayInlist.add(product);
Log.d("Product", product.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volly", "Error");
error.printStackTrace();
}
});
rQueue.add(jsonArrayRequest);
}
public static void postRequest(final Products product) {
try {
StringRequest stringRequest = new StringRequest(Request.Method.POST, insertDataUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d("onResponse", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley insertData", "ERROR");
Log.d("error: ", error.getCause().toString());
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> perameters = new HashMap<>();
perameters.put("barcode", product.getBarcode());
perameters.put("addDate", product.getDayOfadd());
perameters.put("exDate", product.getExDate());
return perameters;
}
};
rQueue.add(stringRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here I init the layout and add the adapter for the RecycleView. The productsToDisplayInList is populated in the getRequest() method. But somehow, it's only periodic getting populated..
Adapter class:
package lassebjoerklund.easyfridge;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ProductCardAdapter extends RecyclerView.Adapter<ProductHolder> {
private CardView cardView;
private List<Products> productses;
private Calendar c;
public ProductCardAdapter(ArrayList<Products> items) {
productses = items;
}
#Override
public int getItemCount() {
return productses.size();
}
#Override
public void onBindViewHolder(ProductHolder holder, int position) {
Products product = productses.get(position);
Date returnDate = Util.parseDateString(product.getExDate());
if (Util.getCurrentDate().after(returnDate)) {
cardView.setCardBackgroundColor(Color.parseColor("#FF000D"));
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
} else {
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
}
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardlayout, parent, false);
cardView = new CardView(parent.getContext());
return new ProductHolder(itemView);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Holder Class:
package lassebjoerklund.easyfridge;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView cardName;
protected TextView cardAddDate;
protected TextView cardExDate;
protected TextView cardType;
public ProductHolder(View itemView) {
super(itemView);
cardName = (TextView) itemView.findViewById(R.id.cardName);
cardAddDate = (TextView) itemView.findViewById(R.id.cardAddDate);
cardExDate = (TextView) itemView.findViewById(R.id.cardExDate);
cardType = (TextView) itemView.findViewById(R.id.cardType);
}
}