0

我試圖做一個圖像應用程序,我使用Firebase作爲我的後端,我正在填充我的Recyclerview onCreate()我只是想當用戶向上滾動^時,它會每次加載10個以上。如何通過Firebase在Android應用上添加分頁?

我得到了所有的工作,問題在於Firebase每次都加載所有數據。

例如:它在啓動時加載10張圖像,當向上滾動時會加載20條消息,然後加載30條消息,而不是每次只加載10條消息。

這是代碼:

private RecyclerView recyclerView; 

//adapter object 
private RecyclerView.Adapter adapter; 

//database reference 
private DatabaseReference mDatabase; 

//progress dialog 
private ProgressDialog progressDialog; 

//list to hold all the uploaded images 
private List<Upload> uploads; 

private static final int TOTAL_ITEM_EACH_LOAD = 10; 



private int currentPage = 0; 

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

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


    progressDialog = new ProgressDialog(this); 

    uploads = new ArrayList<>(); 

    //displaying progress dialog while fetching images 
    progressDialog.setMessage("Please wait..."); 
    progressDialog.show(); 
    mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS); 

    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); 


    recyclerView.setAdapter(adapter); 

    //adding an event listener to fetch values 
    mDatabase.addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot snapshot) { 
      //dismissing the progress dialog 
      progressDialog.dismiss(); 

      //iterating through all the values in database 
      for (DataSnapshot postSnapshot : snapshot.getChildren()) { 
       Upload upload = postSnapshot.getValue(Upload.class); 
       uploads.add(0,upload); 
       //uploads.add(upload); 
      } 
      //creating adapter 
      adapter = new MyAdapter(getApplicationContext(), uploads); 
      //adding adapter to recyclerview 
      recyclerView.setAdapter(adapter); 
     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 
      progressDialog.dismiss(); 
     } 
    }); 
} 
+0

您的代碼格式不正確,您是否也可以擴展您的問題? –

+0

我已經編輯過我的帖子,請檢查一下。 –

回答

0

爲了解決這個問題,只需移動List<Upload> uploads = new ArrayList<>();的聲明onDataChange()方法內而不是在for循環。您需要在progressDialog.dismiss();之前放置它。通過這種方式,您可以在此異步方法內保留聲明和列表的使用。

希望它有幫助。

+0

不,我曾嘗試使用上面提到的代碼,但不幸的是仍然無法正常工作。 –

+0

什麼是錯誤? –

+0

分頁不起作用。 –

相關問題