【问题标题】:How to Load the RecyclerView upon starting to the application automatically?如何在自动启动应用程序时加载 RecyclerView?
【发布时间】:2019-09-03 06:43:10
【问题描述】:

我使用 recyclerview 创建了一个片段,当我执行应用程序时,它不会自动加载数据,因为我必须移动到另一个视图,然后返回到这个特定的视图来加载数据,我想要什么时候应用程序在 recyclerview 中启动列表会自动从 firestore 数据库中检索数据。

如果需要我的代码,请告知。

提前感谢您的帮助。

HomeFragment 类

public class HomeFragment extends Fragment {


    RelativeLayout mParent;
    //FloatingActionButton addButton;

    private static final String TAG = "DocSnippets";

    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private CollectionReference PostsRef = db.collection("posts");

    private CollectionReference likesRef;
    private PostsAdapter adapter;
    private FirestoreRecyclerOptions options;
    private FirebaseAuth mAuth;
    private String mUserId, id;

    private Button commentsbutton;

    RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //just change the fragment_dashboard
        //with the fragment you want to inflate
        //like if the class is HomeFragment it should have R.layout.home_fragment
        //if it is DashboardFragment it should have R.layout.fragment_dashboard

        mAuth = FirebaseAuth.getInstance();
        mUserId = mAuth.getUid();

        likesRef = db.collection("users").document(mUserId).collection("likes");


        final View view = inflater.inflate(R.layout.fragment_home, container, false);
        final FragmentActivity c = getActivity();
        LinearLayoutManager layoutManager = new LinearLayoutManager(c);

        Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
        FirestoreRecyclerOptions<PostsModel> options = new FirestoreRecyclerOptions.Builder<PostsModel>()
                .setQuery(query, PostsModel.class)
                .build();
        adapter = new PostsAdapter(options);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
       // recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(c));
        recyclerView.setAdapter(adapter);
            commentsbutton = (Button) view.findViewById(R.id.commenting_button);

         mParent =view.findViewById(R.id.relative_home);
      //  return inflater.inflate(R.layout.fragment_home, null);




        adapter.setOnItemClickListener(new PostsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
                PostsModel note = documentSnapshot.toObject(PostsModel.class);
                 id = documentSnapshot.getId();
                String path = documentSnapshot.getReference().getPath();
                Log.d(TAG, "String post Id is: " + id);

                Intent gotoClickPostDetailActivity = new Intent (view.getContext(), ClickPost.class);
                gotoClickPostDetailActivity.putExtra("PostKey",id);
                startActivity(gotoClickPostDetailActivity);


                //
               // Toast.makeText(c, "Position: " + position + " ID: " + id, Toast.LENGTH_SHORT).show();
                //Toast.makeText(HomeFragment.this, "Position: " + position + " ID: " + id, Toast.LENGTH_SHORT).show();
            }
        });







        return view;



    }



    private String getTime(long timestamp){
        long ts = timestamp*1000;
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
        String time = sdf.format(new Date(ts));
        return time;

    }

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

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

}

MainActivity 类

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private FirebaseAuth mauth;
    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private CollectionReference UsersRef = db.collection("Users");
    private DocumentReference noteRef = db.document("Notebook/My First Note");
    private MySharedPreferences sp;






    String currentUserID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sp = MySharedPreferences.getInstance(this);


        setContentView(R.layout.activity_main);

        mauth = FirebaseAuth.getInstance();
// currentUserID = mauth.getCurrentUser().getUid();
        UsersRef =FirebaseFirestore.getInstance().collection("Users");

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = 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();
            }
        });

    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment fragment;
            fragment = null;
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    fragment = new HomeFragment();
                    break;
                case R.id.navigation_dashboard:
                    fragment = new DashboardFragment();
                    break;
                case R.id.navigation_notifications:
                    Intent intent = new Intent(MainActivity.this, AddPostActivity.class);
                    startActivity(intent);
                   // fragment = new NotificationsFragment();
                    break;
                case R.id.navigation_post:
                    fragment = new ProfileFragment();
                    break;
                case R.id.navigation_postlist:
                    fragment = new ProfileFragment();
                    break;

            }
            return loadFragment(fragment);
        }
    };


    private boolean loadFragment(Fragment fragment) {
        //switching fragment
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .commit();
            return true;
        }
        return false;
    }


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

        FirebaseUser currentUser = mauth.getCurrentUser();

        if(currentUser == null)
        {
            SendUserToSignInActivity();
        }
        else
        {
            checkUserExistence();
        }

    }







}

【问题讨论】:

  • 请添加您正在使用的代码。
  • 嗨,Alex,代码已添加,请进一步协助。谢谢
  • 您共享的代码行数过多。请编辑您的问题并隔离问题,并添加您的数据库结构。
  • 我已根据需要编辑了问题中的代码,用户和用户帖子有不同的集合,我可以分享数据结构的屏幕截图,但它有点聚合一个
  • @AlexMamo 嘿,请帮忙

标签: java android firebase google-cloud-firestore adapter


【解决方案1】:

你的问题出在这行代码

 Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
    FirestoreRecyclerOptions<PostsModel> options = new 
FirestoreRecyclerOptions.Builder<PostsModel>()
            .setQuery(query, PostsModel.class)
            .build();
    adapter = new PostsAdapter(options);

PostsRef.orderBy 需要一些时间从 firebase 获取结果,但您可以立即设置导致问题的结果

【讨论】:

  • 不,不是这样,基本上有一个底部标签导航,当我启动应用程序时,它不会从firestore加载任何数据,但是当我切换到另一个标签然后再切换回来时到同一个选项卡,它会在 2 秒内加载数据。 ....请提供建议,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多