Firebase-无法在应用程序界面上读取数据-Android Studio

时间:2019-01-21 16:07:50

标签: java android firebase firebase-realtime-database

我正在使用Firebase在Android Studio上开发任务管理应用程序。我创建了一个向数据库添加数据的类,但是我尝试了多种方法来集成和读取应用程序上的数据,但是没有任何进展。

Main Activity.java

database = FirebaseDatabase.getInstance();
    ref = database.getReference().child("Task List");
    final ArrayList<String> mTaskName = new ArrayList<>();

    taskListView = (ListView) findViewById(R.id.taskListView);
    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.task_info, mTaskName);
    taskListView.setAdapter(arrayAdapter);
    ref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            String value = dataSnapshot.getValue(String.class);
            mTaskName.add(value);
            arrayAdapter.notifyDataSetChanged();

        }

add_task.java

 mDatabase = FirebaseDatabase.getInstance().getReference().child("Task List"); // Reference database

    addTaskbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String taskName = newTask.getText().toString().trim();
            String date = dateField.getText().toString().trim();
            String assignee = spinnerAssign.getSelectedItem().toString();
            String descrip = description.getText().toString();

            if (!TextUtils.isEmpty(taskName) && !TextUtils.isEmpty(date)) {

                HashMap<String, String> taskData = new HashMap<>();
                taskData.put("Name", taskName);
                taskData.put("Date", date);
                taskData.put("Assigned to", assignee);
                taskData.put("Description", descrip);

                mDatabase.push().setValue(taskData).addOnCompleteListener(new OnCompleteListener<Void>() {

数据库的结构如下:

经理任务列表

  -任务列表

       -PushID
        -分配给:“名称”
        -日期:“日期”
        -说明:“说明”
        -名称:“任务名称”

1 个答案:

答案 0 :(得分:0)

 ValueEventListener eventListener = new ValueEventListener() {
        //Searching the database and adding each to list
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                //adding the key to an arraylist to be referenced when deleting records or passing intents from specific button
                mTaskName.add(ds.getKey());
                String name = ds.child("Name").getValue(String.class);
                String date = ds.child("Date").getValue(String.class);
                id.add(name  + "\n" + date);
                Log.d("TAG", name);
            }
            taskListView.setAdapter(arrayAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };
    database.addListenerForSingleValueEvent(eventListener);