简体   繁体   中英

Recyclerview only shows 1 item

I have the following code from my app where I am trying to retrieve expenses' items that happened today's day (dd) in the past, more than 2 times, I want to populate those items in a recyclerview. I get the expected result but only one item at the time, the recyclerview is not showing the list as expected.

I use realtime database.

I am looking for some ideas, please see my code;

    //suggestions
    databaseReference.addValueEventListener(new ValueEventListener() {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            suggestions.clear();
            int occurrences = 0;
            Expense expense1 = new Expense();

            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                Expense expense = dataSnapshot.getValue(Expense.class);

                assert expense != null;
                if (expense.getDate().substring(0, 2).equals(day) && expense.getDate().substring(6, 10).equals(year)) {
                    for (Expense e : all_expenses) {
                        if (!today_expenses.contains(e)) {
                            suggestions_title.setVisibility(View.VISIBLE);
                            occurrences = Collections.frequency(all_expenses, e);
                            expense1 = e;
                        }
                    }
                }
            }

            if (occurrences > 2) suggestions.add(expense1);

            suggestionsAdapter.notifyDataSetChanged();

            if (suggestionsAdapter.getItemCount() == 0) {
                suggestions_title.setVisibility(View.INVISIBLE);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });

and this below is my adapter class;

public class SuggestionsAdapter extends RecyclerView.Adapter<SuggestionsAdapter.ViewHolder> {

Activity activity;
private final ArrayList<Expense> suggestions;

private String item;
private String category;
private int amount;

FirebaseAuth mAuth;
int totalMonth;

public SuggestionsAdapter(Activity activity, ArrayList<Expense> suggestions) {
    this.activity = activity;
    this.suggestions = suggestions;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(activity).inflate(R.layout.suggestions, parent, false);

    mAuth = FirebaseAuth.getInstance();
    monthTotalLimit();

    return new ViewHolder(view);
}

@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
    final Expense expense = suggestions.get(position);

    holder.expense.setText("" + expense.getItem());

    holder.add.setOnClickListener(view -> {
        item = expense.getItem();
        category = expense.getCategory();
        amount = expense.getAmount();

        updateExpense();
    });

}

@Override
public int getItemCount() {
    return suggestions.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    private final TextView expense;
    private final TextView add;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        expense = itemView.findViewById(R.id.expense);
        add = itemView.findViewById(R.id.add_suggestion);

    }
}

//saving amount for limit check
private void monthTotalLimit() {
    final Calendar c = Calendar.getInstance();
    @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("MM");
    String month = dateFormat.format(c.getTime());

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(Objects.requireNonNull(mAuth.getCurrentUser()).getUid());
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            int totalAmount = 0;

            for (DataSnapshot ds : snapshot.getChildren()) {
                Expense expense = ds.getValue(Expense.class);

                //dd-MM-yyyy
                assert expense != null;
                if (expense.getDate().substring(3, 5).equals(month)) {
                    totalAmount += expense.getAmount();
                    totalMonth = totalAmount;
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

private void updateExpense() {
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());

    AlertDialog.Builder myDialog = new AlertDialog.Builder(activity);
    LayoutInflater inflater = LayoutInflater.from(activity);

    View myView = inflater.inflate(R.layout.input_layout, null);
    myDialog.setView(myView);

    final AlertDialog dialog = myDialog.create();
    dialog.setCancelable(false);

    final EditText mItem = myView.findViewById(R.id.item);
    final TextView mDate = myView.findViewById(R.id.date);
    final EditText mAmount = myView.findViewById(R.id.amount);

    final Calendar c = Calendar.getInstance();
    @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = dateFormat.format(c.getTime());

    mItem.setText(item);
    mDate.setText(date);
    mAmount.setText(String.valueOf(amount));

    final Spinner categorySpinner = myView.findViewById(R.id.spinner);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity, R.array.Category, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    categorySpinner.setAdapter(adapter);

    int spinnerPosition = adapter.getPosition(category);
    categorySpinner.setSelection(spinnerPosition);

    final Button cancel_btn = myView.findViewById(R.id.cancel_btn);
    final Button save_btn = myView.findViewById(R.id.save_btn);

    mDate.setOnClickListener(view -> datePicker(mDate));

    save_btn.setOnClickListener(view -> {
        String itemString = mItem.getText().toString();
        String amountString = mAmount.getText().toString();
        String spinnerString = categorySpinner.getSelectedItem().toString();
        String userInputDate = mDate.getText().toString();

        int amountInt;

        if (itemString.isEmpty()) {
            mItem.setError(activity.getString(R.string.name_required));
            mItem.requestFocus();
            return;
        }
        if (amountString.equals("") || amountString.equals("0")) {
            mAmount.setError(activity.getString(R.string.amount_required));
            mAmount.requestFocus();
            return;
        } else {
            amountInt = Integer.parseInt(amountString);
        }
        if ((totalMonth + amountInt) > 2000000000) {
            mAmount.setError(activity.getString(R.string.monthly_limit));
            mAmount.requestFocus();
            return;
        }
        if (spinnerString.equals(activity.getString(R.string.category))) {
            Toast.makeText(activity, R.string.category_required, Toast.LENGTH_SHORT).show();
            return;
        } else {

            String id = databaseReference.push().getKey();

            Expense expense = new Expense(itemString.toUpperCase(Locale.ROOT), spinnerString, userInputDate, id, amountInt);

            assert id != null;
            databaseReference.child(id).setValue(expense).addOnCompleteListener(task -> {
                if (!task.isSuccessful()) {
                    Toast.makeText(activity, activity.getString(R.string.input_error) + task.getException(), Toast.LENGTH_SHORT).show();
                }
            });
        }
        dialog.dismiss();
    });
    cancel_btn.setOnClickListener(view -> dialog.dismiss());

    dialog.show();
}

private void datePicker(TextView textView) {
    Calendar calendar = Calendar.getInstance();

    // Get current time
    int currentYear = calendar.get(Calendar.YEAR);
    int currentMonth = calendar.get(Calendar.MONTH);
    int currentDay = calendar.get(Calendar.DAY_OF_MONTH);

    // Create listener
    @SuppressLint("SetTextI18n") DatePickerDialog.OnDateSetListener listener = (view, year, month, day) -> {

        @SuppressLint("DefaultLocale") String dayS = String.format("%02d", day);
        @SuppressLint("DefaultLocale") String monthS = String.format("%02d", month + 1);

        textView.setText(dayS + "-" + monthS + "-" + year);

    };

    // Move day as today
    calendar.set(Calendar.DAY_OF_MONTH, currentDay);

    // Min = time after changes
    long minTime = calendar.getTimeInMillis();

    // Move day as first day of the month
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    // Move to next month
    calendar.add(Calendar.MONTH, +1);
    // Go back one day (so last day of current month)
    calendar.add(Calendar.DAY_OF_MONTH, -1);

    // Max = current
    long maxTime = calendar.getTimeInMillis();

    // Create dialog
    DatePickerDialog datePickerDialog = new DatePickerDialog(activity,
            listener,
            currentYear,
            currentMonth,
            currentDay);

    // Set dates
    datePickerDialog.getDatePicker().setMinDate(minTime);
    datePickerDialog.getDatePicker().setMaxDate(maxTime);

    // Show dialog
    datePickerDialog.show();
}

}

Your code looks fine and must be fetching multiple items from the firebase database but only one is displayed on the whole screen because in the adapter layout, the height of the parent would be match_parent instead of wrap_content , that's why one item is taking up the whole screen and you can't see the rest of the items. If you even scroll your screen vertically, you will see the other items as well. Just change it to wrap_content and everything will be good to go :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM