2017-01-01 71 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 ;  
} 
相关问题