我遇到错误
“ com.google.firebase.database.DatabaseException: 无法将类型java.lang.String的对象转换为type krunoslavkovac.ferit.test.Add“
无法弄清楚为什么会发生这种情况。
我在这里搜索了许多解决方案,但仍然没有弄清楚。
主要活动:
public class MainActivity extends AppCompatActivity {
EditText et_task ;
Button btn_add;
RecyclerView recycler_view;
//Firebase
FirebaseDatabase database;
DatabaseReference dbRef ;
FirebaseRecyclerOptions<Add> options;
FirebaseRecyclerAdapter<Add, MyRecyclerViewHolder> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_task = (EditText) findViewById(R.id.et_task);
btn_add = (Button) findViewById(R.id.btn_add);
recycler_view = (RecyclerView) findViewById(R.id.recycler_view);
recycler_view.setLayoutManager(new LinearLayoutManager(this));
database = FirebaseDatabase.getInstance();
dbRef = database.getReference("Test");
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addTask();
}
});
displayTask();
}
private void addTask(){
String task = et_task.getText().toString();
Add add = new Add(task);
dbRef.push().setValue(task);
adapter.notifyDataSetChanged();
}
private void displayTask() {
options =
new FirebaseRecyclerOptions.Builder<Add>()
.setQuery(dbRef,Add.class)
.build();
adapter =
new FirebaseRecyclerAdapter<Add, MyRecyclerViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull MyRecyclerViewHolder holder, int position, @NonNull Add model) {
holder.tv_task.setText(model.getTask());
}
@NonNull
@Override
public MyRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(getBaseContext()).inflate(R.layout.add_item,viewGroup, false);
return new MyRecyclerViewHolder(itemView);
}
};
adapter.startListening();
recycler_view.setAdapter(adapter);
}
}
添加课程
public class Add {
private String task;
public Add(){
}
public Add(String task) {
this.task = task;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
}
RecyclervViewHolder
public class MyRecyclerViewHolder extends RecyclerView.ViewHolder {
TextView tv_task;
public MyRecyclerViewHolder(@NonNull View itemView) {
super(itemView);
tv_task = (TextView) itemView.findViewById(R.id.tv_task);
}
}
数据库:
我想显示Firebase中的数据。
答案 0 :(得分:1)
替换此
dbRef.push().setValue(task);
收件人
dbRef.push().setValue(add);