1

我正在使用Firebase開發我的第一個Android應用程序。這也是我的第一個android應用程序,所以我沒有經驗,但已經通過Java或PHP等編程語言獲得了一些經驗。我正在尋找專業建議,因爲我遇到了我的代碼組織的一些問題。我已經做了一些研究,但無法爲此找到一個好的解決方案。Android Firebase代碼組織(概念)

我的應用使用Firebase身份驗證和Firebase實時數據庫。

我將解釋我的問題的所有相關部分。


的主要活動......如果一個用戶登錄,如果沒有,啓動認證活動

  • 包含一個對象DatabaseHandler,這是負責數據庫

    • 檢查訪問時,此對象需要實例化一個UserInfo對象
    • 包含FirebaseAuth對象附加了AuthStateListener
    • AuthStateListener檢查如果用戶已登錄,如果是的話,將與當前用戶
    • 應能顯示從DatabaseHandler

    檢索的某些數據重新實例化DatabaseHandler對象我的問題

    我已經需要訪問的onCreate()方法中的DatabaseHandler對象2882​​顯示一些數據,但自DatabaseHandler的方法onAuthStateChanged()被實例化,以確保已經有登錄的用戶,這是行不通的,因爲onCreate()之前onAuthStateChanged()


    我的想法

    我不完全確定如何解決這個問題,但我的第一個想法是重組我的項目的方式,我的主要活動只檢查要調用的活動,而不是自己顯示數據。我仍然處於項目的早期階段,所以這應該不是什麼大問題。 只是想知道這是否會工作,或者如果有更好的解決方案。

    讓我知道你在想什麼

  • +0

    據我瞭解,你不**有**在'onCreate'中獲取並顯示你的數據。您可以從您的活動中的另一個自定義方法更新UI。你需要在這個方法中'查找'UI元素,或者將它們聲明爲Activity類的字段,並在'onCreate'中'查找'它們。如果你願意,我可以發表一個我的意思的例子。 – Barthy

    +0

    正如我所說的,我並不熟悉android概念。我使用的是recylcer視圖,大部分都是從教程中獲得的代碼,並且在本教程中,我必須在'onCreate()'方法中聲明recylcerview的內容 –

    回答

    0

    下面的代碼要顯示書籍的列表,假定活動的一個例子:

    public class MainActivity extends AppCompatActivity { 
        private List<Book> bookList = new ArrayList<>(); 
        private RecyclerView recyclerView; 
        private BookAdapter adapter; 
    
        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
         setContentView(R.layout.activity_main); 
    
         recyclerView = (RecyclerView) findViewById(R.id.recycler_view); 
         adapter = new BookAdapter(bookList); 
    
         RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); 
         recyclerView.setLayoutManager(mLayoutManager); 
         recyclerView.setItemAnimator(new DefaultItemAnimator()); 
         recyclerView.setAdapter(mAdapter); 
    
         FirebaseAuth auth = FirebaseAuth.getInstance(); 
         FirebaseUser user = auth.getCurrentUser(); 
         if (user != null) { 
          // User is still logged in 
          // Get UserInfo and instantiate DatabaseHandler 
          populateList(); 
         } else { 
          // No user is logged in, go to auth activity 
         } 
        } 
    
        private void populateList() { 
         // Get Books from Firebase and add them to the adapter 
         Book book = new Book(); 
         bookList.add(book); 
    
         // Notify the adapter, so that it updates the UI 
         adapter.notifyDataSetChanged(); 
        } 
    } 
    

    有了這個,你做了以下內容:

    • 創建並實例化onCreate中的所有對象
    • 檢查onCreate中的用戶並行爲一致ingly
    • 獲取數據,並從populateList,它允許重新填充列表,而不通過所有的onCreate東西去顯示它(記得clear列表/適配器
    +0

    這看起來很有希望。當我回到我的電腦時,我會詳細回顧一下。 –

    +0

    @IanFako嗨伊恩,這有什麼進展?我的回答對你有幫助嗎? – Barthy