保存从Firebase解析的信息以供离线查看

时间:2016-12-27 05:06:27

标签: android firebase firebase-realtime-database

我想在我的应用程序中添加一项功能,以确保如果用户连接到互联网甚至一次,那么从Firebase解析的信息(在这种情况下,每个对象有3个字符串变量的ArrayList对象)可以以某种方式保存(使用sharedPreferences或文件或任何其他方法),以便下次用户在没有互联网连接的情况下打开应用程序,然后应显示此已经解析的数据,如果有互联网连接,则它应该正常工作。

为此,我开始了解磁盘持久性,但它无法正常工作。这是我的代码

package in.protechlabz.www.yavatmalindicatorserver;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.ads.AdView;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.StorageReference;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Nikesh on 23/12/2016.
 */
public class ContactListActivity extends AppCompatActivity {

    private List<ContactData> generalList = new ArrayList<ContactData>();

    Intent intent;
    private int listItemSelector=0; // This variable will be used to store information obtained from
    // intent regarding which listview to be loaded
    private AdView mAdView2;
    Firebase myFirebaseRef;
    private ArrayAdapter<ContactData> listItemAdapter;
    private StorageReference mStorageRef;

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

        /* Admob related important code*/
        mAdView2 = (AdView) findViewById(R.id.adView2);
        com.google.android.gms.ads.AdRequest adRequest = new com.google.android.gms.ads.AdRequest.Builder().build();
        mAdView2.loadAd(adRequest);

        Firebase.setAndroidContext(this);


        // Extract information from intent for listItemSelector
        Bundle extras = getIntent().getExtras();

        if(extras != null) {
            listItemSelector = extras.getInt("ListPosition");
        }

        //if(isNetworkAvailable()) {
            final ProgressDialog dialog = new ProgressDialog(ContactListActivity.this);
            dialog.setMessage("Loading Data...");
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();

            //Adding information to individual lists
        /*Firebase related code*/
            myFirebaseRef = new Firebase("https://yavatmalindicatorserver.firebaseio.com");
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);


            myFirebaseRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {

                    generalList.clear();
                    switch (listItemSelector) {

                        case 1:
                            for (DataSnapshot eachContact : snapshot.child("Hotels and Lodges").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 2:
                            for (DataSnapshot eachContact : snapshot.child("Banks").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 3:
                            for (DataSnapshot eachContact : snapshot.child("Tours and Travels").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 4:
                            for (DataSnapshot eachContact : snapshot.child("Function Halls").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 5:
                            for (DataSnapshot eachContact : snapshot.child("Hospitals").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 6:
                            for (DataSnapshot eachContact : snapshot.child("Educational Institutes").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 7:
                            for (DataSnapshot eachContact : snapshot.child("Medicals").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 8:
                            for (DataSnapshot eachContact : snapshot.child("Government Offices").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 9:
                            for (DataSnapshot eachContact : snapshot.child("Press").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                    }
                            break;
                        case 10:
                            for (DataSnapshot eachContact : snapshot.child("Railways (Dhamangaon)").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;

                        // From here emergency list
                        case 11:
                            for (DataSnapshot eachContact : snapshot.child("Police Station").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 12:
                            for (DataSnapshot eachContact : snapshot.child("Fire Brigade").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 13:
                            for (DataSnapshot eachContact : snapshot.child("Ambulance").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 14:
                            for (DataSnapshot eachContact : snapshot.child("Blood Banks").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;
                        case 15:
                            for (DataSnapshot eachContact : snapshot.child("Snake Friends").getChildren()) {
                                ContactData tempData = eachContact.getValue(ContactData.class);
                                generalList.add(tempData);
                            }
                            break;


                    }


                    listItemAdapter.notifyDataSetChanged();
                    dialog.hide();

                }

                @Override
                public void onCancelled(FirebaseError error) {
                }
            });
        //}else {

           // Toast.makeText(this, "Sorry No Internet Connection",
             //       Toast.LENGTH_SHORT).show();
            //finish();
        //}

        listItemAdapter = new ContactDataAdapter(this,R.layout.eachcontact_row,generalList);
        ListView myContactList = (ListView) findViewById(R.id.directoryList);

        //For card view
        myContactList.addHeaderView(new View(this));
        myContactList.addFooterView(new View(this));

        myContactList.setAdapter(listItemAdapter);

        myContactList.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        ContactData singleItem = (ContactData) parent.getItemAtPosition(position);
                        String number = singleItem.getTelephone();

                        // Parse only one number if multiple numbers present
                        int indexOfComma = number.indexOf(",");

                        if(indexOfComma != -1) {
                            number = number.substring(0,indexOfComma);
                        }

                        intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + number));
                        startActivity(intent);
                    }
                }
        );




    }

    /*public boolean isNetworkAvailable(final Context context) {
        final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
        return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
    }*/
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

请帮忙。

1 个答案:

答案 0 :(得分:1)

为此目的,有一个简单但非常方便的库。它被称为TinyDB。将其添加到项目后,您只需在TinyDB实例上调用putListObject()即可保存数据。

祝你好运