Невозможно получить информацию из Firebase на пользовательский ListView Android - PullRequest
1 голос
/ 23 апреля 2019

Я новичок в Android Studio. Я пытаюсь разработать приложение для управления запасами, но не могу показать информацию в пользовательском ListView из базы данных Firebase. Я нашел подобные вопросы и решение здесь, но у меня не получилось. Ниже приведен код AccountHome (MainActivity). Этот код работает иногда, когда я закрываю и перезагружаю приложение несколько раз. Надеюсь получить какое-то рабочее решение. Спасибо Скриншот базы данных Firebase

public class AccountHom extends AppCompatActivity {

    ListView listview;
    FirebaseDatabase database;
    DatabaseReference myRef;
    ArrayList<String> dept ;
    ArrayList<Long> total;
    AccountSetBudgetHelper accountSetBudgetHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_home_activity);

        accountSetBudgetHelper = new AccountSetBudgetHelper();
        listview = findViewById(R.id.set_budget_listview);
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference("budget");
        dept = new ArrayList<>();
        total = new ArrayList<Long>();

        AccountSetBudgetAdaptr accountSetBudgetAdapter = new AccountSetBudgetAdaptr(AccountHom.this ,dept,total);

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    accountSetBudgetHelper = ds.getValue(AccountSetBudgetHelper.class);
                    dept.add(accountSetBudgetHelper.getName());
                    total.add(accountSetBudgetHelper.getTotal());
                } }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
        listview.setAdapter(accountSetBudgetAdapter);
    }
}
class AccountSetBudgetAdaptr extends ArrayAdapter {
    private final Activity context;
    private final ArrayList<String> dept;
    private final ArrayList<Long> total;

    AccountSetBudgetAdaptr(Activity context, ArrayList<String> dept, ArrayList<Long> total) {
        super(context, R.layout.single_row_listview_budget,dept);
        this.context = context;
        this.dept = dept;
        this.total = total;
    }
    @NonNull
    @Override
    public View getView(int position, View view, @NonNull ViewGroup parent) {

        Toast.makeText(getContext(), "this is a boy", Toast.LENGTH_SHORT).show();
        View rowView = view;
        if(rowView==null){
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.single_row_listview_budget, parent, false);
        }
        TextView mdept = rowView.findViewById(R.id.textView_setbudget_dept);
        TextView mtotal = rowView.findViewById(R.id.textView_setbudget_total);
        mdept.setText(dept.get(position));
        mtotal.setText(String.valueOf(total.get(position)));
        return rowView;
    }
}
class AccountSetBudgetHelpr {
    private String name;
    private Long total;
    public AccountSetBudgetHelpr() {
    }
    public AccountSetBudgetHelpr(String name, Long total) {
        this.name = name;
        this.total = total;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Long getTotal() {
        return total;
    }
    public void setTotal(Long total) {
        this.total = total;
    }
}[enter image description here][1]

1 Ответ

1 голос
/ 23 апреля 2019

Вы добавляете данные в оба списка, dept и total, но не уведомляете адаптер о новых данных. Чтобы решить эту проблему, добавьте следующую строку кода сразу после окончания цикла for:

myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            accountSetBudgetHelper = ds.getValue(AccountSetBudgetHelper.class);
            dept.add(accountSetBudgetHelper.getName());
            total.add(accountSetBudgetHelper.getTotal());
        }
        accountSetBudgetAdapter.notifyDataSetChanged(); //Notify the adapter
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {}
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...