How can I save data when offline in my Android app?

I'm creating an app for Android in Java. I can send info to a webservice but when i'm offline i want to store the info and when the phone gets connected to the internet i want to send it to the webservice. Can anyone help me? Thanks

Upvotes: 1

Views: 8001

Answers (4)

AviRosenblum
AviRosenblum

Reputation: 41

  1. Store your data in SQLite data-base. You can read here.

  2. Check in BroadcastReceiver if connectivity changed and update online DB and delete the content from Sqlite DB.

    public void onReceive(Context context, Intent intent) {
        String s = intent.getAction();
        if (s.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
            if (IsNetworkAvailable(context)) {
                // update your online data-base and delete all rows from SQlite
            }
        return;
       }
    }
    

Method isNetworkAvailable:

public static boolean isNetworkAvailable(Context mContext) {
    Context context = mContext.getApplicationContext();
    ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED){
                    return true;
                }
             }
        }
    }
   return false;
}

You also need permissions:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Upvotes: 3

IsaacCisneros
IsaacCisneros

Reputation: 1953

Offline storage and sync seem simple at first sight but you need to be careful and consider the following:

First get familiar with the storage options available in the platform and chose the most convenient for your app scenario.

Second, design your sync mechanism in an efficient way so your app won't drain the battery life.

This is a good resource to check the entire structure of an android app that cares about working offline and properly sync with the server as network becomes available.

Upvotes: 2

Josef Korbel
Josef Korbel

Reputation: 1208

In the event, where you upload your data, check if Internet connection is available or not, if not, store the data as textfile or object and name it like needToUpload1, 2, 3.

Then, whenever the device is online, check if the there is any file named like that. If so, upload it via service and delete the file.

That's just my opinion how i'll do it but really depends on data. You can find how to do every step on this site so i hope it will help.

Upvotes: 1

SaNtoRiaN
SaNtoRiaN

Reputation: 2202

Save your info to a SQLite database and use a BroadcastReceiver to listen when network connection is available. When connection is available, start a Service that sends the saved data to your webservice.

Upvotes: 1

Related Questions