2017-01-01 103 views
0

我在Ionic2應用程序中使用Firebase3。要求加載大約2000個對象的數據,並且每次切換頁面(使用導航)時都需要加載數據。但每次加載數據看起來都不好。如何獲取數據一次,每次從本地加載

那麼,是否有任何解決方案來獲取數據一次 - 像聯繫人列表。

然後加載的數據將從本地顯示。

謝謝!

回答

1

試試這個代碼: -

private List<Contact> contactList; 
private SharedPreferences shared ; 


public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

    View view = inflater.inflate(R.layout.fragment_contacts, container, false); 

    shared = getSharedPreferences("AppPref", MODE_PRIVATE); 
    //**Get the data from local storage** 
    List<Contacts> contactList = new Gson().fromJson((shared.getString("contacts", "")),new TypeToke<List<Contact>>(){}.getType()); 

    if(contactList ==null) { // if no data found then call firebase service 

     contactList=new ArrayList(); 

    //Use addListenerForSingleValueEvent instead of ValueEventListener.So this will listen only once. 
     mDataBaseRef.child("Your_Node").addListenerForSingleValueEvent(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 

      for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){ 
       contactList.add(postSnapshot.getValue(Contact.class); 
      } 

       //Save the data in Shared Preferences 
       SharedPreferences.Editor editor = shared.edit(); 
       editor.putString("contacts", new Gson().toJson(contactList)); 
       editor.commit(); 
     } 

     @Override 
     public void onCancelled(FirebaseError firebaseError) { 
      contactList = null ; 
     } 
    }); 
    } 

return view ;  
} 
相關問題