Firebase数据在我的RecyclerView中不会加载

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

Firebase data won't load in my RecyclerView

问题

The screen launches but doesn't throw any errors or bugs. I just launch the blank recycler view as if it's not reading any of the Java codes, although they are in my manifest. I've tried bumping the Firebase path down to "Book," but then I receive a `can't convert object to java.lang.string` error.

**Main activity**

public class BarberView extends AppCompatActivity {
    private ArrayList<Book> books;
    private List<String> key;
    private Context mContext;
    private static final String TAG = "RealtimeDatabaseDemo";
    private MyViewHolder adapter;
    private TextView list_u, list_p, list_d, list_t, list_c;
    DatabaseReference ref;

    private FirebaseRecyclerOptions<Book> options;

    RecyclerView recyclerView;

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

        recyclerView = findViewById(R.id.list_jobs);
        recyclerView.setHasFixedSize(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        ref = FirebaseDatabase.getInstance().getReference();
        Query query = ref.child("gregs-281717");

        final FirebaseRecyclerOptions<Book> options = new FirebaseRecyclerOptions.Builder<Book>()
                .setQuery(query, Book.class)
                .setLifecycleOwner(this)
                .build();

        adapter = new MyViewHolder(options);
        recyclerView.setAdapter(adapter);

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot mdatasnapshot : snapshot.getChildren()) {
                    Book mbook = new Book();
                    mbook.setTime(mdatasnapshot.getValue().toString());
                    mbook.setDates(mdatasnapshot.getValue().toString());
                    mbook.setPayDone(mdatasnapshot.getValue().toString());
                    mbook.setCutDone(mdatasnapshot.getValue().toString());
                    mbook.setUser_id(mdatasnapshot.getValue().toString());
                    books.add(mbook);
                }
                adapter = new MyViewHolder(options);
                adapter.notifyDataSetChanged();
            }

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

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        adapter.startListening();
        adapter.notifyDataSetChanged();
    }

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

**ViewHolder**

public class MyViewHolder extends FirebaseRecyclerAdapter<Book, MyViewHolder.Holder> {

    public MyViewHolder(@NonNull FirebaseRecyclerOptions<Book> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull Holder holder, int position, @NonNull Book book) {
        holder.list_u.setText(book.getUser_id());
        holder.list_c.setText(book.getCutDone());
        holder.list_d.setText(book.getDates());
        holder.list_t.setText(book.getTime());
        holder.list_p.setText(book.getPayDone());
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);
        return new Holder(view);
    }

    class Holder extends RecyclerView.ViewHolder {
        public TextView list_u, list_p, list_d, list_t, list_c;

        public Holder(@NonNull View itemView) {
            super(itemView);
            list_u = itemView.findViewById(R.id.list_user);
            list_p = itemView.findViewById(R.id.list_price);
            list_d = itemView.findViewById(R.id.list_date);
            list_t = itemView.findViewById(R.id.list_time);
            list_c = itemView.findViewById(R.id.list_cut);
        }
    }
}

**Model**

import com.google.firebase.database.IgnoreExtraProperties;
import org.jetbrains.annotations.NotNull;

@IgnoreExtraProperties
public class Book {
    public String time;
    public String dates;
    public String payDone;
    public String cutDone;
    public String user_id;

    public Book() {
    }

    @NotNull
    @Override
    public String toString() {
        return "Book{" +
                "time='" + time + '\'' +
                ", dates='" + dates + '\'' +
                ", payDone='" + payDone + '\'' +
                ", cutDone='" + cutDone + '\'' +
                ", user_id='" + user_id + '\'' +
                '}';
    }

    public Book(String time, String dates, String cutDone, String payDone, String user_id) {
        this.time = time;
        this.dates = dates;
        this.payDone = payDone;
        this.cutDone = cutDone;
        this.user_id = user_id;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getDates() {
        return dates;
    }

    public void setDates(String dates) {
        this.dates = dates;
    }

    public String getPayDone() {
        return payDone;
    }

    public void setPayDone(String payDone) {
        this.payDone = payDone;
    }

    public String getCutDone() {
        return cutDone;
    }

    public void setCutDone(String cutDone) {
        this.cutDone = cutDone;
    }

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }
}

**RecyelerView.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=".BarberView">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_jobs"/>
</androidx.constraintlayout.widget.ConstraintLayout>

**List.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="wrap_content"
    android:padding="16dp"
    android:id="@+id/list_books">

    <TextView
        android:textColor="#000000"
        android:id="@+id/list_cut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/list_price"
        android:layout_width="62dp"
        android:layout_height="19dp"
        android:text="TextView"
        android:textSize="14sp"
        android:textColor="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/list_date"
        app:layout_constraintStart_toEndOf="@+id/list_cut"
        app:layout_constraintTop_toTopOf="parent

<details>
<summary>英文:</summary>

The screen launches but doesn&#39;t throw any errors or bugs I just launch the blank recycler view as if it&#39;s not reading any of the java codes although they are in my manifest. I&#39;ve tried bumping the firebase path down on to &quot;Book&quot; but then I receive a `can&#39;t convert object to java.lang.string` error.

**Main activity**
   
        
    public  class BarberView extends AppCompatActivity {
        private ArrayList&lt;Book&gt; books ;
        private List&lt;String&gt; key;
        private Context mContext;
        private static final String TAG = &quot;RealtimeDatabaseDemo&quot;;
        private MyViewHolder adapter;
        private TextView list_u, list_p, list_d, list_t, list_c;
        DatabaseReference ref;
  

        private FirebaseRecyclerOptions&lt;Book&gt; options;
    
    
        /**
         * Get the last 50 chat messages.
         */
    
    
        RecyclerView recyclerView;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate ( savedInstanceState );
            setContentView ( R.layout.barber_view );
    
            recyclerView =findViewById ( R.id.list_jobs );
            recyclerView.setHasFixedSize ( false );
            recyclerView.setLayoutManager ( new LinearLayoutManager ( this ) );
    
            ref =  FirebaseDatabase.getInstance ( ).getReference ( );
            Query query = ref.child ( &quot;gregs-281717&quot; );
    
            final FirebaseRecyclerOptions&lt;Book&gt; options=new FirebaseRecyclerOptions.Builder&lt;Book&gt; ( )
                    .setQuery ( query, Book.class )
                    .setLifecycleOwner ( this )
                    .build ( );
    
            adapter = new MyViewHolder ( options );
            recyclerView.setAdapter ( adapter );
    
            query.addValueEventListener ( new ValueEventListener ( ) {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    for (DataSnapshot mdatasnapshot: snapshot.getChildren()) {
                        Book mbook =new Book();
                        mbook.setTime( mdatasnapshot.getValue ( ).toString () );
                        mbook.setDates( mdatasnapshot.getValue ( ).toString () );
                        mbook.setPayDone( mdatasnapshot.getValue ( ).toString () );
                        mbook.setCutDone( mdatasnapshot.getValue ( ).toString () );
                        mbook.setUser_id( mdatasnapshot.getValue ( ).toString () );
                        books.add(mbook);
                    }
                    adapter = new MyViewHolder (options );
                    adapter.notifyDataSetChanged();
    
                    }
    
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
    
                }
            });
    
        }
    
        @Override
        public void onStart() {
            super.onStart ( );
            adapter.startListening ();
            adapter.notifyDataSetChanged();
    
        }
    
        @Override
        protected void onStop() {
            super.onStop ( );
            adapter.startListening ();
            adapter.notifyDataSetChanged();
    
        }
    }




**ViewHolder**


            
    
    
    public class MyViewHolder extends FirebaseRecyclerAdapter&lt;Book, MyViewHolder.Holder&gt; {
    
    
        /**
         * Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
         * {@link FirebaseRecyclerOptions} for configuration options.
         *
         * @param options
         */
        public MyViewHolder(@NonNull FirebaseRecyclerOptions&lt;Book&gt; options) {
            super ( options );
        }
    
        @Override
        protected void onBindViewHolder(@NonNull Holder holder, int position, @NonNull Book book) {
            holder.list_u.setText ( book.getUser_id () );
            holder.list_c.setText ( book.getCutDone () );
            holder.list_d.setText ( book.getDates () );
            holder.list_t.setText ( book.getTime () );
            holder.list_p.setText ( book.getPayDone () );
        }
    
        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from ( parent.getContext ( ) )
                    .inflate ( R.layout.list_item, parent, false );
            return new Holder ( view );
        }
    
    
        class Holder extends RecyclerView.ViewHolder{
            public TextView list_u, list_p, list_d, list_t, list_c;
    
            public Holder(@NonNull View itemView) {
              super(itemView);
            list_u = itemView.findViewById ( R.id.list_user );
            list_p = itemView.findViewById ( R.id.list_price );
            list_d = itemView.findViewById ( R.id.list_date );
            list_t = itemView.findViewById ( R.id.list_time );
            list_c = itemView.findViewById ( R.id.list_cut );
        }}
    
      }


**Model**

    import com.google.firebase.database.IgnoreExtraProperties;
    
    import org.jetbrains.annotations.NotNull;
    
    @IgnoreExtraProperties
    
    public class Book {
        public String time;
        public String dates;
        public String payDone;
        public String cutDone;
        public String user_id;
    
        public Book() {
        }
    
        @NotNull
        @Override
        public String toString() {
            return &quot;Book{&quot; +
                    &quot;time=&#39;&quot; + time + &#39;\&#39;&#39; +
                    &quot;, dates=&#39;&quot; + dates + &#39;\&#39;&#39; +
                    &quot;, payDone=&#39;&quot; + payDone + &#39;\&#39;&#39; +
                    &quot;, cutDone=&#39;&quot; + cutDone + &#39;\&#39;&#39; +
                    &quot;, user_id=&#39;&quot; + user_id + &#39;\&#39;&#39; +
                    &#39;}&#39;;
        }
    
        public Book(String time, String dates, String cutDone, String payDone, String user_id) {
            this.time = time;
            this.dates = dates;
            this.payDone = payDone;
            this.cutDone = cutDone;
            this.user_id = user_id;
        }
    
        public String getTime() {
            return time;
        }
    
        public void setTime(String time) {
            this.time = time;
        }
    
        public String getDates() {
            return dates;
        }
    
        public void setDates(String dates) {
            this.dates = dates;
        }
    
        public String getPayDone() {
            return payDone;
        }
    
        public void setPayDone(String payDone) {
            this.payDone = payDone;
        }
    
        public String getCutDone() {
            return cutDone;
        }
    
        public void setCutDone(String cutDone) {
            this.cutDone = cutDone;
        }
    
        public String getUser_id() {
            return user_id;
        }
    
        public void setUser_id(String user_id) {
            this.user_id = user_id;
        }
    }


**RecyelerView.xml**

            
    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
        xmlns:tools=&quot;http://schemas.android.com/tools&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        tools:context=&quot;.BarberView&quot;&gt;
    
        &lt;androidx.recyclerview.widget.RecyclerView
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;match_parent&quot;
            android:id=&quot;@+id/list_jobs&quot;/&gt;
    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;


**List.XML**
            
    
    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
        xmlns:tools=&quot;http://schemas.android.com/tools&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:padding=&quot;16dp&quot;
        android:id=&quot;@+id/list_books&quot;&gt;
    
    
        &lt;TextView
            android:textColor=&quot;#000000&quot;
            android:id=&quot;@+id/list_cut&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;TextView&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
    
        &lt;TextView
            android:id=&quot;@+id/list_price&quot;
            android:layout_width=&quot;62dp&quot;
            android:layout_height=&quot;19dp&quot;
            android:text=&quot;TextView&quot;
            android:textSize=&quot;14sp&quot;
            android:textColor=&quot;#000000&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toStartOf=&quot;@+id/list_date&quot;
            app:layout_constraintStart_toEndOf=&quot;@+id/list_cut&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
    
        &lt;TextView
            android:id=&quot;@+id/list_time&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;TextView&quot;
            android:textColor=&quot;#000000&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot;
            tools:ignore=&quot;MissingConstraints&quot; /&gt;
    
        &lt;TextView
            android:id=&quot;@+id/list_date&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;TextView&quot;
            android:textColor=&quot;#000000&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
    
        &lt;TextView
            android:id=&quot;@+id/list_user&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;TextView&quot;
            android:textColor=&quot;#000000&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toStartOf=&quot;@+id/list_time&quot;
            app:layout_constraintStart_toEndOf=&quot;@+id/list_date&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

    
**gregs-281717.jason Firebase realtime database**

            
    {
      &quot;Book&quot; : {
        &quot;cutDone&quot; : &quot;cut1&quot;,
        &quot;dates&quot; : &quot;11/9/2020&quot;,
        &quot;payDone&quot; : &quot;20.00&quot;,
        &quot;time&quot; : &quot;03:36AM&quot;,
        &quot;user_id&quot; : &quot;notme@badcode.com&quot;
      }
    }

</details>


# 答案1
**得分**: 0

你应该在从Firebase加载数据后,在你的主活动中设置适配器,就像这样:

```java
public class BarberView extends AppCompatActivity {
    private ArrayList<Book> books;
    private List<String> key;
    private Context mContext;
    private static final String TAG = "RealtimeDatabaseDemo";
    private MyViewHolder adapter;
    private TextView list_u, list_p, list_d, list_t, list_c;
    DatabaseReference ref;

    private FirebaseRecyclerOptions<Book> options;

    RecyclerView recyclerView;

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

        recyclerView = findViewById(R.id.list_jobs);
        recyclerView.setHasFixedSize(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        ref = FirebaseDatabase.getInstance().getReference();
        Query query = ref.child("gregs-281717");

        final FirebaseRecyclerOptions<Book> options = new FirebaseRecyclerOptions.Builder<Book>()
                .setQuery(query, Book.class)
                .setLifecycleOwner(this)
                .build();

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot mdatasnapshot : snapshot.getChildren()) {
                    Book mbook = new Book();
                    mbook.setTime(mdatasnapshot.child("Book").getValue(true).toString());
                    mbook.setDates(mdatasnapshot.getValue(true).toString());
                    mbook.setPayDone(mdatasnapshot.getValue(true).toString());
                    mbook.setCutDone(mdatasnapshot.getValue(true).toString());
                    mbook.setUser_id(mdatasnapshot.getValue(true).toString());
                }
                adapter = new MyViewHolder(options);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }

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

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        recyclerView.setAdapter(adapter);
    }
}
英文:

You should set your adapter after loading data from firebase in your main activity

like this :-


public  class BarberView extends AppCompatActivity {
private ArrayList&lt;Book&gt; books ;
private List&lt;String&gt; key;
private Context mContext;
private static final String TAG = &quot;RealtimeDatabaseDemo&quot;;
private MyViewHolder adapter;
private TextView list_u, list_p, list_d, list_t, list_c;
DatabaseReference ref;
private FirebaseRecyclerOptions&lt;Book&gt; options;
/**
* Get the last 50 chat messages.
*/
RecyclerView recyclerView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.barber_view );
recyclerView =findViewById ( R.id.list_jobs );
recyclerView.setHasFixedSize ( false );
recyclerView.setLayoutManager ( new LinearLayoutManager ( this ) );
ref =  FirebaseDatabase.getInstance ( ).getReference ( );
Query query = ref.child ( &quot;gregs-281717&quot; );
final FirebaseRecyclerOptions&lt;Book&gt; options=new FirebaseRecyclerOptions.Builder&lt;Book&gt; ( )
.setQuery ( query, Book.class )
.setLifecycleOwner ( this )
.build ( );
query.addValueEventListener ( new ValueEventListener ( ) {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot mdatasnapshot: snapshot.getChildren()) {
Book mbook =new Book();
mbook.setTime( mdatasnapshot.child ( &quot;Book&quot; ).getValue ( true).toString () );
mbook.setDates( mdatasnapshot.getValue (true ).toString () );
mbook.setPayDone( mdatasnapshot.getValue ( true).toString () );
mbook.setCutDone( mdatasnapshot.getValue (true ).toString () );
mbook.setUser_id( mdatasnapshot.getValue ( true).toString () );
}
adapter = new MyViewHolder (options );
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
@Override
public void onStart() {
super.onStart ( );
recyclerView.setAdapter(adapter);
}
@Override
protected void onStop() {
super.onStop ( );
recyclerView.setAdapter(adapter);
}
}

huangapple
  • 本文由 发表于 2020年9月12日 01:42:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63851911.html
匿名

发表评论

匿名网友

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

确定