简体   繁体   English

从Firebase数据库检索对象到我的RecyclerView中

[英]Retrieving objects from Firebase database into my RecyclerView

I have tried some the suggestions from similar questions on here as you can see in some commented out code. 我在这里尝试了类似问题的一些建议,正如您在一些注释掉的代码中看到的那样。 I am new at all of this so could you please help me out? 我是新来的,所以您能帮帮我吗? Let me know if you need anymore to code to try to solve the problem. 让我知道是否需要编码以尝试解决问题。 Thank you in advance. 先感谢您。

I even tried to doing what the error says but I really dont know where to put the GenericTypeIndicator. 我什至尝试执行错误提示,但我真的不知道将GenericTypeIndicator放在哪里。

I am getting this error: 我收到此错误:

com.google.firebase.database.DatabaseException: Class java.util.List has generic type parameters, please use GenericTypeIndicator instead at com.google.android.gms.internal.zzelw.zzb(Unknown Source) at com.google.android.gms.internal.zzelw.zza(Unknown Source) at com.google.android.gms.internal.zzelw.zzb(Unknown Source) at com.google.android.gms.internal.zzelx.zze(Unknown Source) at com.google.android.gms.internal.zzelw.zzb(Unknown Source) at com.google.android.gms.internal.zzelw.zza(Unknown Source) at com.google.firebase.database.DataSnapshot.getValue(Unknown Source) at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:29) ... com.google.firebase.database.DatabaseException:类java.util.List具有通用类型参数,请改用com.google.android.com上的com.google.android.gms.internal.zzelw.zzb(未知源)使用GenericTypeIndicator。 com.google.android.gms.internal.zzelw.zzb(未知源)的com.google.android.gms.internal.zzelx.zze(未知源)的gms.internal.zzelw.zza(未知源)。 com.google.android.gms.internal.zzelw.zza(未知源)的com.google.firebase.database.DataSnapshot.getValue(未知源)处的google.android.gms.internal.zzelw.zzb(未知源) com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:29)...

Here is my code: 这是我的代码:

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.homeRecyclerView)
    RecyclerView mHomeRecyclerView;

    @BindView(R.id.emptyTextView)
    TextView mEmptyTextView;

    protected static final Query sInspirationQuery =
            FirebaseDatabase.getInstance().getReference().child("Inspirations");

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


        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setIcon(R.mipmap.ic_launcher);

        //mHomeRecyclerView.setHasFixedSize(true);
        mHomeRecyclerView.setLayoutManager(new LinearLayoutManager(this));


    }

    @Override
    protected void onStart() {
        super.onStart();


        attachRvAdapter();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_menu, menu);
        Drawable addInspirationDrawable = menu.findItem(R.id.addInspiration).getIcon();
        Drawable userAccountDrawable = menu.findItem(R.id.userAccount).getIcon();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if(id == R.id.addInspiration) {
            String className = "com.example.jessie.inspirationexchange.CreateActivity";
            nextActivity(className);
        } else if(id == R.id.userAccount) {
            String className = "com.example.jessie.inspirationexchange.UserActivity";
            nextActivity(className);
        }
        return super.onOptionsItemSelected(item);
    }

    private void nextActivity(String className) {
        Intent intent = null;
        try {
            intent = new Intent(this, Class.forName(className));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        startActivity(intent);
    }

    public void attachRvAdapter() {
        RecyclerView.Adapter adapter = newAdapter();
        mHomeRecyclerView.setAdapter(adapter);
    }



    protected RecyclerView.Adapter newAdapter() {
        FirebaseRecyclerOptions<Inspiration> options =
                new FirebaseRecyclerOptions.Builder<Inspiration>()
                        .setQuery(sInspirationQuery, Inspiration.class)
                        .setLifecycleOwner(this)
                        .build();

        return new FirebaseRecyclerAdapter<Inspiration, CardViewHolder>(options) {
            @Override
            public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                return new CardViewHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.inspiration_card, parent, false));
            }

            @Override
            protected void onBindViewHolder(@NonNull CardViewHolder holder, int position, @NonNull Inspiration model) {
                holder.bind(model);
            }

//            SnapshotParser<Inspiration> mSnapshotParser = new SnapshotParser<Inspiration>() {
//                @NonNull
//                @Override
//                public Inspiration parseSnapshot(@NonNull DataSnapshot snapshot) {
//                    GenericTypeIndicator<List<Inspiration>> t = new GenericTypeIndicator<List<Inspiration>>();
//
//                    return (Inspiration) snapshot.child("Inspirations").getValue(t);
//                }
//            };

            @Override
            public void onDataChanged() {
                super.onDataChanged();

                //GenericTypeIndicator<List<Inspiration>> t = new GenericTypeIndicator<List<Inspiration>>();
                mEmptyTextView.setVisibility(getItemCount() == 0 ? View.VISIBLE : View.GONE);
            }


        };

    }

}

My model: 我的模特:

public class Inspiration {

    private String mTitle;
    private String mBody;
    private List<String> mCategoriesChose;
    private String mAuthor;

    public Inspiration() {
    }

    public Inspiration(String title, String body, List categories) {
        mTitle = title;
        mBody = body;
        mCategoriesChose = categories;
    }

    public String getAuthor() {
        return mAuthor;
    }

    public void setAuthor(String author) {
        mAuthor = author;
    }

    public String getTitle() {
        return mTitle;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public String getBody() {
        return mBody;
    }

    public void setBody(String body) {
        mBody = body;
    }

    public List<String> getCategoriesChose() {
        return mCategoriesChose;
    }

    public void setCategoriesChose(List categoriesChose) {
        mCategoriesChose = categoriesChose;
    }

    @Override
    public String toString() {
        return "Inspiration{" +
                "mTitle='" + mTitle + '\'' +
                ", mBody='" + mBody + '\'' +
                ", mCategoriesChose=" + mCategoriesChose.toString() +
                '}';
    }

}

Here is what the JSON looks like(just 1 object) JSON如下所示(仅1个对象)

{
  "Inspirations" : {
    "-L5un07HfHu0XT-XfLX2" : {
      "author" : "User1",
      "body" : "test 1",
      "categoriesChose" : [ "Character", "Courage", "Determination" ],
      "title" : "gov"
    }
  }
}

You can't have List and Map type objects within the main object that you're trying to deserialize. 您要反序列化的主对象中不能包含List和Map类型的对象。 It's because of the way the Java type erasure system works. 这是因为Java类型擦除系统的工作方式。 At runtime, it's impossible to know via reflection what generic types your List or Map declares, which means it doesn't know what type of objects are safe to put in there. 在运行时,无法通过反射来了解List或Map声明了什么泛型类型,这意味着它不知道可以安全地放置哪种类型的对象。

GenericTypeIndicator works with getValue() when the top-level object you're trying to deserialize is a generic List, but that's about it. 当您要反序列化的顶级对象是通用List时, GenericTypeIndicator可与getValue()一起使用。 It doesn't work if it's embedded anywhere inside. 如果将其嵌入到内部的任何位置,则无法使用。 The error message is a bit misleading on that point. 在这一点上,错误消息有点误导。 You'll have to pull items out of the snapshot and create objects out of them yourself. 您必须从快照中拉出项目,然后自己从中创建对象。

I solved this problem by removing the nested array that I had inside of my database. 我通过删除数据库内部的嵌套数组解决了这个问题。 After removing this it worked like a charm. 删除后,它就像一个魅力。 If someone wants to answer how resolve that the nested array inside database problem, feel free to post. 如果有人想回答如何解决数据库中的嵌套数组问题,请随时发布。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM