如何从本地加载一次和每次加载数据

时间:2017-01-01 14:57:02

标签: firebase ionic-framework firebase-realtime-database ionic2

我在Ionic2 App中使用Firebase3。要求是加载大约2000个对象的数据,每次页面切换(使用导航)时都需要加载数据。但是每次数据加载都不好看。

那么,是否有任何解决方案来获取数据 - 如联系人列表。

然后加载的数据将从本地显示。

谢谢!

1 个答案:

答案 0 :(得分: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 ;    
}