嗨,我是Android Studio的新手,我有类似以下的代码:
HomeFragment.java
package fragments;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.example.asuss.myapplication.R;
import com.firebase.client.Firebase;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import adapters.TweetAdapter;
import models.Tweet;
public class HomeFragment extends Fragment {
private ArrayList<Tweet> tweets = new ArrayList<Tweet>();
private RecyclerView mRecyclerView;
private TweetAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private OnFragmentInteractionListener mListener;
private View view;
public interface OnFragmentInteractionListener{
void onFragmentInteraction(Uri uri);
}
public HomeFragment(){
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
//loadTweets();
getData();
buildRecyclerView();
return view;
}
private void getData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firebaseDatabase.getReference().child("Tweets");
final DatabaseReference ref2 = firebaseDatabase.getReference().child("Users");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (final DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println("Selam" + ds.toString());
if (ds.child("authorId") != null) {
final String authorID = ds.child("authorId").getValue().toString();
final String id = ds.child("id").getValue().toString();
final String content = ds.child("content").getValue().toString();
final int likeNumber = Integer.parseInt(ds.child("likeNumber").getValue().toString());
final boolean isActive = Boolean.parseBoolean(ds.child("isActive").getValue().toString());
ref2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshotID) {
if (dataSnapshotID.exists()) {
for (DataSnapshot ds2 : dataSnapshotID.getChildren()) {
if (ds2.child("id").getValue().toString().equals(authorID)) {
System.out.println("AuthorID: " + authorID + " İsim: " + ds2.child("username").getValue().toString());
tweets.add(new Tweet(id, R.drawable.ic_adb_black_24dp, ds2.child("username").getValue().toString(),
content, likeNumber, isActive));
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseErrorID) {
}
});
}
}
}
else{
Log.i("Database: ","Fail");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void addTweet() {
//String tweetContent = editText.getText().toString();
//tweets.add(new Tweet(tweets.size(), R.drawable.ic_adb_black_24dp, "yarenska", tweetContent, 0));
// notifyDataSetChanged de çağırılabilir ama animasyonlu olmasını istersek
// notifyItemInserted çağrılır.
//mAdapter.notifyItemInserted(tweets.size()-1);
}
private void buildRecyclerView() {
Log.i("Hello","Hello");
mRecyclerView = view.findViewById(R.id.recyclerView);
//mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
mAdapter = new TweetAdapter(tweets);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new TweetAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Log.i("onItemClicked","Hello" + position);
}
});
}
private void loadTweets() {
//tweets.add(new Tweet(1, R.drawable.ic_adb_black_24dp, "yarenska", "Çok güzel bir gün", 2));
//tweets.add(new Tweet(2, R.drawable.ic_adb_black_24dp, "aligunes73", "Yaşasın", 0));
//tweets.add(new Tweet(3, R.drawable.ic_adb_black_24dp, "jally_jam", "Matematikten 100 almışım.", 1));
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
//Fragment ilk oluştuğu zaman çağrılır.
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
问题在于该程序无法呈现我从数据库中收集的推文。当我尝试调试时,它首先进入getData方法,但紧接在getData的ref.addValueEventListener(new ValueEventListener())方法之后,然后进入buildRecyclerView方法,因此按预期,它尝试呈现长度为0的数组列表。防止那个?
最佳答案
onDataChange()
是异步的,这意味着它不会等到检索到所有数据后,才在检索所有数据之前执行方法buildRecyclerView()
。您需要在buildRecyclerView()
内添加onDataChange()
并将其从onCreateView()
删除:
private void getData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firebaseDatabase.getReference().child("Tweets");
final DatabaseReference ref2 = firebaseDatabase.getReference().child("Users");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (final DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println("Selam" + ds.toString());
if (ds.child("authorId") != null) {
final String authorID = ds.child("authorId").getValue().toString();
final String id = ds.child("id").getValue().toString();
final String content = ds.child("content").getValue().toString();
final int likeNumber = Integer.parseInt(ds.child("likeNumber").getValue().toString());
final boolean isActive = Boolean.parseBoolean(ds.child("isActive").getValue().toString());
ref2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshotID) {
if (dataSnapshotID.exists()) {
for (DataSnapshot ds2 : dataSnapshotID.getChildren()) {
if (ds2.child("id").getValue().toString().equals(authorID)) {
System.out.println("AuthorID: " + authorID + " İsim: " + ds2.child("username").getValue().toString());
tweets.add(new Tweet(id, R.drawable.ic_adb_black_24dp, ds2.child("username").getValue().toString(),
content, likeNumber, isActive));
buildRecyclerView(); //add it here
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseErrorID) {
}
});
}
}
}
else{
Log.i("Database: ","Fail");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}