0

I am using Volley in application. I am sending data using REST Api to server. This is the JSON POST request to Server.

private void add() {
        String NetworkStatus = biz.fyra.bookapp.utils.NetworkStatus.checkConnection(getContext());
        if (NetworkStatus.equals("false")) {
            alert.noInternetAlert(getActivity());
        } else {
            JSONObject info = new JSONObject();
            try {
                info.put("name", full_name);
                info.put("phone", foodie_contact);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, ApiUrls.ADD, info, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }) {
            };
            AppController.getInstance().addToRequestQueue(request);
        }
    }  

If Internet is available I am able to POST data to server. But If Internet is not available I need to temporarily store this JSON object somewhere and when Internet is available I need to POST all JSON objects to server that were stored locally. How to achieve this ?

Ümañg ßürmån
  • 9,695
  • 4
  • 24
  • 41
Satyam Gondhale
  • 1,415
  • 1
  • 16
  • 43

1 Answers1

2

For Achieving this you have to follow these steps.

  1. Check if the internet is connected.
  2. If the internet is connected send the call.
  3. If the internet is not connected you you can convert the Json to string and save it in Shared preferences or DataBase.
  4. Then you have to create a broadcast reciver for checking the internet connections and
  5. when ever you get the message for active internet you need to send the pending data to server.

UPDATE For creating a broadcast reciever

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable() || mobile.isAvailable()) {
        Log.d("Network Available ", "Flag No 1");
    }
}

}

And then in your Application tag within Menifest file Add Intent Filter

<receiver android:name=".NetworkChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
Adnan khalil
  • 134
  • 1
  • 9