简体   繁体   English

如何从 Firebase 数据库中检索数据 [ANDROID STUDIO]

[英]How to retrieve data from Firebase Database [ANDROID STUDIO]

I am very new to Android Studio.我对 Android Studio 很陌生。 I've made an app with a bottom navigation so users can access different screens (using fragments).我制作了一个带有底部导航的应用程序,因此用户可以访问不同的屏幕(使用片段)。 On one screen I've made a fragment which is meant to show users their upcoming tasks.在一个屏幕上,我制作了一个片段,旨在向用户展示他们即将完成的任务。 I've also made an activity so that users can create a new task, and when done they are redirected back to the Tasks screen.我还创建了一个活动,以便用户可以创建一个新任务,完成后他们将被重定向回任务屏幕。 I've connected my app to a Firebase database, so when users input their data it gets stored into the database (THAT WORKS AND SHOWS ON DATABASE).我已将我的应用程序连接到 Firebase 数据库,因此当用户输入他们的数据时,它会存储到数据库中(在数据库中有效并显示)。 However, when the user saves the task and is redirected back to the tasks screen their data is not shown and I am not sure why it doesn't show.但是,当用户保存任务并被重定向回任务屏幕时,他们的数据不会显示,我不确定它为什么不显示。

I've tried to watch loads of videos to try their solutions, but it doesn't work for me, and I am really not sure on how to do it.我试图观看大量视频来尝试他们的解决方案,但这对我不起作用,我真的不知道该怎么做。 How do I get the data to show up??如何让数据显示?

I have been using FIREBASE DATABASE for my database (not firestore).我一直在使用 FIREBASE DATABASE 作为我的数据库(不是 Firestore)。

[Sorry for showing lots of code in advance - I'm just trying to be thorough] [抱歉提前展示了很多代码-我只是想彻底]

[CHECK IMAGES THEY RELATE TO PROBLEM] [检查与问题相关的图像]

https://i.stack.imgur.com/thNWo.png - Tasks screen and button https://i.stack.imgur.com/thNWo.png - 任务屏幕和按钮

https://i.stack.imgur.com/d1Xg9.png - Add Tasks screen https://i.stack.imgur.com/d1Xg9.png - 添加任务屏幕

https://i.stack.imgur.com/BgLcC.png - Data being added into database after pressing 'save task' https://i.stack.imgur.com/BgLcC.png - 按“保存任务”后将数据添加到数据库中

https://i.stack.imgur.com/gTNpb.png - No data being shown on tasks screen??? https://i.stack.imgur.com/gTNpb.png - 任务屏幕上没有显示数据???

.Javas .Javas

MainActivity.java: MainActivity.java:

public class MainActivity extends AppCompatActivity {

TextView title, description, date;
LinearLayoutManager linearLayoutManager;
FirebaseDatabase firebaseDatabase;
DatabaseReference reference;

FirebaseRecyclerOptions<TaskItem> options;
FirebaseRecyclerAdapter<TaskItem, MyViewHolder> adapter;
RecyclerView recyclerView;


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

    HomeFragment fragment1 = new HomeFragment();
    FragmentManager homemanager = getSupportFragmentManager();
    homemanager.beginTransaction().add(R.id.fragment_container, fragment1).commit();

    BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
    bottomNav.setOnNavigationItemSelectedListener(navListener);

    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
            new HomeFragment()).commit();

}

private BottomNavigationView.OnNavigationItemSelectedListener navListener =
        new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;

                switch (item.getItemId()) {
                    case R.id.nav_home:
                        selectedFragment = new HomeFragment();
                        break;
                    case R.id.nav_calendar:
                        selectedFragment = new CalendarFragment();
                        break;
                    case R.id.nav_school:
                        selectedFragment = new SchoolFragment();
                        break;
                }

                FragmentManager navmanager = getSupportFragmentManager();
                navmanager.beginTransaction().replace(R.id.fragment_container,
                        selectedFragment).commit();

                return true;
            }
        };

} }

NewTaskHome.java [for adding new tasks] NewTaskHome.java [用于添加新任务]

public class NewTaskHome extends AppCompatActivity {

TextView title;
EditText titleName;
TextView description;
EditText descName;
TextView date;
EditText dateName;

Button saveTask;
Button cancelTask;

DatabaseReference database;

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

    database = FirebaseDatabase.getInstance().getReference().child("TASKS");


    titleName = findViewById(R.id.addTitleName);
    descName = findViewById(R.id.addDescName);
    dateName = findViewById(R.id.addDateName);

    saveTask = findViewById(R.id.btnSaveTask);
    cancelTask = findViewById(R.id.btnCancel);

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

            submitTask();


        }
    });

    cancelTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(NewTaskHome.this,MainActivity.class);
            startActivity(i);
        }
    });
}

private void submitTask() {

    String title_val = titleName.getText().toString().trim();
    String desc_val = descName.getText().toString().trim();
    String date_val = dateName.getText().toString().trim();

    DatabaseReference newTask = database.push();

    newTask.child("title").setValue(title_val);
    newTask.child("description").setValue(desc_val);
    newTask.child("date").setValue(date_val);

    Intent i = new Intent(NewTaskHome.this,MainActivity.class);
    startActivity(i);


}

} }

HomeFragment.java [for Tasks screen]: HomeFragment.java [用于任务屏幕]:

public class HomeFragment extends Fragment {

Button addNewBtn;

public HomeFragment(){
    //Required empty constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_home, container, false);

    addNewBtn = v.findViewById(R.id.btnAddNew);
    addNewBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            startActivity(new Intent(getActivity(),NewTaskHome.class));
        }
    });

    return v;
}

} }

I also made a TaskItem class with getter and setter methods when I was trying out some solutions (that I couldn't make work)?当我尝试一些解决方案(我无法工作)时,我还使用 getter 和 setter 方法制作了一个 TaskItem class?

public class TaskItem {
String title, description, date;

public TaskItem(){
}

public TaskItem(String title, String description, String date) {
    this.title = title;
    this.description = description;
    this.date = date;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

XMLs: XML:

activity_main.xml: activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@android:color/holo_blue_dark" >

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

fragment_home.xml:片段_home.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".MainActivity"
     android:background="#F4F4F4"
     android:orientation="vertical">

     <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/colorPrimaryDark">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginLeft="16dp">

                <TextView
                    android:id="@+id/heading"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:text="TASKS"
                    android:textColor="#FFF"
                    android:textSize="32sp" />
                    <!-- android:fontFamily="@font/montserrat2" -->

                <TextView
                    android:id="@+id/subheading"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="8dp"
                    android:text="To-do list:"
                    android:textSize="18sp"
                    android:textColor="#4A4E6A"/>

            </LinearLayout>

            <Button
                android:id="@+id/btnAddNew"
                android:layout_width="55dp"
                android:layout_height="55dp"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="230dp"
                android:background="@drawable/bg_btn_new"
                android:text="+"
                android:textSize="38sp"
                android:textColor="#fff"
                android:textAlignment="center"/>

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="1dp"
            android:background="#131E69"/>

     </LinearLayout>

     <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/taskList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginRight="16dp"
        android:layout_marginLeft="16dp">

     </androidx.recyclerview.widget.RecyclerView>

     <TextView
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="No More To Do"
        android:textAlignment="center"
        android:textColor="#9A9A9A"
        android:textSize="16dp">

     </TextView>


</LinearLayout>

task_item.xml: task_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp">
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/bg_do_item"
        android:layout_marginBottom="20dp">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="220dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="16dp">

            <TextView
                android:id="@+id/taskTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="19dp"
                android:text="Title name"
                android:textSize="22sp"
                android:textColor="#000C5D"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/taskDesc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="Description"
                android:textSize="18sp"
                android:textColor="#ADADAD"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="45dp"
            android:layout_marginTop="30dp">

            <TextView
                android:id="@+id/taskDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="Date"
                android:textSize="18sp"
                android:textColor="#F63EA5"/>

        </LinearLayout>



    </LinearLayout>
</androidx.cardview.widget.CardView>

Again sorry for the amount of code, and for it not being so organised well.. i struggled to put my code into the question.再次对代码量感到抱歉,并且组织得不好......我努力将我的代码放入问题中。

Please help me.. If you need more code for explanation then I'm happy to show it.请帮助我..如果您需要更多代码进行解释,那么我很乐意展示它。

You have to add a listener, like this:您必须添加一个侦听器,如下所示:

// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 Android Studio 中的实时 firebase 数据库中检索数据 - Retrieve data from realtime firebase database in Android Studio 无法从 Android 工作室中的 Firebase 实时数据库中检索数据 - Not able to retrieve data from Firebase real time database in Android studio 如何在firebase数据库中检索特定孩子的数据 - android studio/java? - How to retrieve data for a specific child in firebase database - android studio/ java? Firebase 实时数据库 - 检索数据 Android Studio - Firebase Realtime Database - retrieve data Android Studio 如何在Android Studio的RecyclerView中从Firebase数据库检索arraylist? - How to retrieve arraylist from firebase database in recyclerview in android studio? 如何使用 Android Studio 从 Firebase 实时数据库中的节点检索特定数据? - How to retrieve a specific data from a node in Firebase Realtime Database using Android Studio? 如何使用 android studio 从 Firebase 数据库中检索用户保存的所有收集数据? - How can I retrieve all the collection data users saved from Firebase Database using android studio? 如何在Android Studio中从Firebase检索特定数据 - How to retrieve specific data from firebase in android studio Android Studio:如何从 Firebase 检索特定数据? - Android studio : How do I retrieve specific data from Firebase? 在 Android Studio 上从 Firebase 检索数据 - Retrieve data from Firebase on Android Studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM