android - 如何从 Firebase 数据库中检索数据 [ANDROID STUDIO]
问题描述
我对 Android Studio 很陌生。我制作了一个带有底部导航的应用程序,因此用户可以访问不同的屏幕(使用片段)。在一个屏幕上,我制作了一个片段,旨在向用户展示他们即将完成的任务。我还创建了一个活动,以便用户可以创建一个新任务,完成后他们将被重定向回任务屏幕。我已将我的应用程序连接到 Firebase 数据库,因此当用户输入他们的数据时,它会存储到数据库中(在数据库上工作并显示)。但是,当用户保存任务并被重定向回任务屏幕时,他们的数据不会显示,我不确定它为什么不显示。
我试图观看大量视频来尝试他们的解决方案,但这对我不起作用,我真的不知道该怎么做。如何让数据显示?
我一直在为我的数据库(不是 firestore)使用 FIREBASE DATABASE。
[抱歉提前展示了很多代码-我只是想彻底]
[检查与问题相关的图像]
https://i.stack.imgur.com/thNWo.png - 任务屏幕和按钮
https://i.stack.imgur.com/d1Xg9.png - 添加任务屏幕
https://i.stack.imgur.com/BgLcC.png - 按“保存任务”后将数据添加到数据库中
https://i.stack.imgur.com/gTNpb.png - 任务屏幕上没有显示数据???
.Javas
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 [用于添加新任务]
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 [用于任务屏幕]:
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;
}
}
当我尝试一些解决方案(我无法工作)时,我还使用 getter 和 setter 方法创建了一个 TaskItem 类?
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;
}
XML:
活动主.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>
片段主页.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:
<?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>
再次对代码量感到抱歉,并且组织得不好......我努力将我的代码放入问题中。
请帮助我..如果您需要更多代码进行解释,那么我很乐意展示它。
解决方案
您必须添加一个侦听器,如下所示:
// 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());
}
});
推荐阅读
- javascript - 在列表项中反应 useRef 未定义
- sql - SQL 不可修复的参数嗅探?SSMS 需要几秒钟,SSRS 需要几分钟
- python - 计算平均中位数和标准差返回字符串
- c++ - 在 C++ 中使用 OpenSSL 将 RSA 密钥格式化为公钥
- laravel - 使用访问器在 Eloquent 中进行慢速查询
- java - 在 Java 8 中匹配两个列表中的字符串
- biztalk - BizTalk 映射中从“System.String”到“System.Guid”的无效转换
- r - 根据在列表中找到的条件/分组列 Y 值计算列 X 的中位数
- javascript - 将一个数组中的首字母转换为与另一个数组中的全名匹配,但当数组长度不同时则不行
- python - 从 csv 文件阅读器将值存储到字典中 - ValueError