Firebase实时数据库 – 检索数据Android Studio

huangapple go评论77阅读模式
英文:

Firebase Realtime Database - retrieve data Android Studio

问题

出错信息:
com.google.firebase.database.DatabaseException: 无法将类型为 java.lang.String 的对象转换为类型 com.example.ken.careerapp.Models.Jobs

以下为使用的片段:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.job_listings_fragment, container, false);
    recyclerView = view.findViewById(R.id.recyclerviewjob);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerAdapterJob = new RecyclerAdapterJob(jobs,JobFragment.this::onJobClick);
    recyclerView.setAdapter(recyclerAdapterJob);
    jobs = new ArrayList<Jobs>();
    //initData();
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Jobs");

    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot ds: dataSnapshot.getChildren()){
                Jobs data = ds.getValue(Jobs.class);
                jobs.add(data);
            }
            recyclerAdapterJob.notifyDataSetChanged();
        }

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

        }
    });
    //recyclerView.setAdapter(new RecyclerViewAdapter2(initData()));

    return view;
}

上述数据快照中传递给 getValue 的职位模型类:

public class Jobs {
    private String description;
    private String location;
    private String deadline;

    public Jobs() {
    }

    public Jobs(String description, String location, String deadline) {
        this.description = description;
        this.location = location;
        this.deadline = deadline;
    }

    public String getDescription() {
        return description;
    }

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

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getDeadline() {
        return deadline;
    }

    public void setDeadline(String deadline) {
        this.deadline = deadline;
    }
}

Firebase 实时数据库结构:

Firebase实时数据库 – 检索数据Android Studio

英文:

> Getting error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.ken.careerapp.Models.Jobs

Using a fragment below:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.job_listings_fragment, container, false);
        recyclerView = view.findViewById(R.id.recyclerviewjob);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerAdapterJob = new RecyclerAdapterJob(jobs,JobFragment.this::onJobClick);
        recyclerView.setAdapter(recyclerAdapterJob);
        jobs = new ArrayList&lt;Jobs&gt;();
        //initData();
        databaseReference = FirebaseDatabase.getInstance().getReference().child(&quot;Jobs&quot;);

        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds: dataSnapshot.getChildren()){
                    Jobs data = ds.getValue(Jobs.class);
                    jobs.add(data);
                }
                recyclerAdapterJob.notifyDataSetChanged();
            }

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

            }
        });
        //recyclerView.setAdapter(new RecyclerViewAdapter2(initData()));

        return view;
    }

The job model class which is passed to getValue in datasnapshot above:

public class Jobs {
private String description;
private String location;
private String deadline;

public Jobs() {
}

public Jobs(String description, String location, String deadline) {
    this.description = description;
    this.location = location;
    this.deadline = deadline;
}

public String getDescription() {
    return description;
}

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

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

public String getDeadline() {
    return deadline;
}

public void setDeadline(String deadline) {
    this.deadline = deadline;
}

}

FirebaseRealtime database

Firebase实时数据库 – 检索数据Android Studio

答案1

得分: 0

给出一张照片或者你们实时数据库架构的图示,这将有助于回答这个问题。

英文:

Give a photo or your realtime database architecture.
that will help much to ans this issue.

答案2

得分: 0

你遇到了以下错误:

> 出现错误:com.google.firebase.database.DatabaseException:无法将类型为java.lang.String的对象转换为类型com.example.ken.careerapp.Models.Jobs

因为你正试图将一个字符串转换为Jobs类型的对象,这在Java中实际上是不可能的。从你的截图中我看到,在“Jobs”节点下,只有一个包含三个字符串属性的Jobs对象。因此,当你迭代该节点时,会返回字符串对象而不是Jobs对象,因此出现了错误。

为了解决这个问题,你应该在该节点下创建多个对象,我理解你想要在RecyclerView中显示它们。为了解决这个问题,在将这些工作添加到数据库时,你应该使用push()方法。虽然你没有分享代码的这部分,但我想像它看起来类似于这样:

databaseReference = FirebaseDatabase.getInstance().getReference().child("Jobs");
databaseReference.setValue(jobs);

其中jobs是Jobs类型的对象。这是不正确的,因为在读取数据时会产生错误。为了解决这个问题,请将上面的代码行更改为:

databaseReference.push().setValue(jobs);

在这种情况下,你的新结构将如下所示:

Firebase-root
  |
  --- Jobs
       |
       --- pushedId
             |
             ---deadline: "September"
             |
             ---description: "Intern Software Developer"
             |
             ---location: "Moi Avenue Street"

其余的代码应该能正常工作。

附言:

不要忽视潜在的错误!

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
    Log.d("TAG", databaseError.getMessage());
}

始终记录错误消息。

英文:

You are getting the following error:

> Getting error: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.ken.careerapp.Models.Jobs

Because you are trying to convert a String, into an object of type Jobs, and this actually not possible in Java. As I see in your screenshot, under the Jobs node, there is only a single Jobs object that contains exactly three String properties. So when you iterate that node, you get String objects back and not Jobs objects, hence that error.

To solve this, you should create multiple objects under that node, as I understand, you want to display them in a RecyclerView. To solve this, you should use the push() method, when you add those jobs to the database. You didn't share that part of code, but I imagine that looks similar to this:

databaseReference = FirebaseDatabase.getInstance().getReference().child(&quot;Jobs&quot;);
databaseReference.setValue(jobs);

In which jobs is an object of type Jobs. This is not correct, as it produces that error when reading data. To solve this, please change the above line of code to:

databaseReference.push().setValue(jobs);

In this case, your new structure will look like this:

Firebase-root
  |
  --- Jobs
       |
       --- pushedId
             |
             ---deadline: &quot;September&quot;
             |
             ---description: &quot;Intern Software Developer&quot;
             |
             ---location: &quot;Moi Avenue Street&quot;

And the rest of the code should work.

P.S.

Don't ignore potential errors!

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
	Log.d(&quot;TAG&quot;, databaseError.getMessage());
}

Always log the error message.

huangapple
  • 本文由 发表于 2020年10月13日 15:57:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64330997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定