Android - FirebaseUI有时不会显示RecyclerView

时间:2018-05-26 17:11:25

标签: android firebase android-recyclerview

我在名为MainActivity的活动中有一个名为HomeFragment的片段,它使用RecyclerView从Firebase加载数据。当我点击RecyclerView时,它将打开一个名为ItemActivity的新活动。 问题是有时RecyclerView在打开新活动时不会加载任何内容。 例如,我在HomeFragment中单击了RecyclerView,新的ItemActivity将启动,但没有任何RecyclerView,在我关闭它并再次重新打开后,RecyclerView正在显示。这种情况偶然发生,有时它会加载,有时它不会加载RecyclerView。 每当我放上adapter.stopListening()时,RecyclerView都不会出现在ItemActivity中。

HomeFragment

public class HomeFragment extends Fragment {
private OnFragmentInteractionListener mListener;

FirebaseDatabase database;
DatabaseReference category;
FirebaseRecyclerAdapter adapter;

TextView txtUsername;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;

public HomeFragment() {
    // Required empty public constructor
}


public static HomeFragment newInstance(String param1, String param2) {
    HomeFragment fragment = new HomeFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    database = FirebaseDatabase.getInstance();
    category = database.getReference("Category");

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_home, container,false);

    // set name for user
    String username = Common.currentUser.getEmail();
    StringTokenizer tokens = new StringTokenizer(username, "@");
    String first = tokens.nextToken();// this will contain string before @
    // set name for user
    txtUsername = (TextView) view.findViewById(R.id.textUsername);
    txtUsername.setText(first);

    // load category
    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewCategory);
    recyclerView.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(layoutManager);
    loadMenu();

    return view;
}

private void loadMenu(){

    Query query = FirebaseDatabase
            .getInstance()
            .getReference()
            .child("Category");

    FirebaseRecyclerOptions<Category> options =
            new FirebaseRecyclerOptions.Builder<Category>()
                    .setQuery(query, Category.class)
                    .build();
    adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(options) {
        @Override
        public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity())
                    .inflate(R.layout.category_item, parent, false);

            return new CategoryViewHolder(view);
        }

        @Override
        protected void onBindViewHolder(@NonNull CategoryViewHolder holder, int position, @NonNull Category model) {
            holder.txtMenuName.setText(model.getName());
            Picasso.with(getActivity()).load(model.getImage())
                    .into(holder.imageView);
            final Category clickItem = model;
            holder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    // get category id and send to new activity
                    Intent intent = new Intent(getActivity(), ItemActivity.class);
                    // get category id to filter
                    intent.putExtra("CategoryId",adapter.getRef(position).getKey());
                    startActivity(intent);
                }
            });
        }

    };

    recyclerView.setAdapter(adapter);

}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onStop() {
    super.onStop();
    //adapter.stopListening();
}

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

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        //Toast.makeText(context, "Home Fragment Attached", Toast.LENGTH_SHORT).show();
    }
}


public interface OnFragmentInteractionListener {
    void onFragmentInteraction(Uri uri);
}

ItemActivity

public class ItemActivity extends AppCompatActivity {

ImageView imageView;

RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;

FirebaseDatabase database;
DatabaseReference itemList;

String categoryId;

public FirebaseRecyclerAdapter adapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    // Firebase
    database= FirebaseDatabase.getInstance();
    itemList = database.getReference("Item");

    recyclerView = (RecyclerView) findViewById(R.id.recyclerViewItem);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    // get intent
    if (getIntent() != null) {
        categoryId = getIntent().getStringExtra("CategoryId");
    }
    if(!categoryId.isEmpty() && categoryId != null) {
        loadListItem(categoryId);
    }
}

private void loadListItem(String categoryId) {
    Query query = itemList.orderByChild("CategoryId").equalTo(categoryId);

    FirebaseRecyclerOptions<Item> options =
            new FirebaseRecyclerOptions.Builder<Item>()
                    .setQuery(query, Item.class)
                    .build();
    adapter = new FirebaseRecyclerAdapter<Item, ItemViewHolder>(options) {
        @Override
        public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.product_item, parent, false);

            return new ItemViewHolder(view);
        }

        @Override
        protected void onBindViewHolder(@NonNull ItemViewHolder holder, int position, @NonNull Item model) {
            holder.itemTitle.setText(model.getName());
            holder.itemUsername.setText(model.getUsername());
            holder.itemPrice.setText(model.getPrice());
            holder.itemDescription.setText(model.getDescription());
            holder.itemPhone.setText(model.getPhone());
            holder.itemDate.setText(model.getDate());
            holder.itemQuality.setText(model.getQuality());
            Picasso.with(getBaseContext()).load(model.getPicture())
                    .into(holder.itemImage);
            final Item clickItem = model;
            holder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    //
                }
            });
        }

    };
    adapter.startListening();
    recyclerView.setAdapter(adapter);
    Toast.makeText(this, "" + categoryId, Toast.LENGTH_SHORT).show();
}

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

@Override
public void onStop() {
    super.onStop();
    //adapter.stopListening();
}

1 个答案:

答案 0 :(得分:0)

我发现了问题。 只需删除recyclerView.setHasFixedSize(true);

即可