Search code examples
jsonparsinggsonrealmandroid-volley

can anyone explain how to initialize realm instance outside the Activity? for example while parsing json with volley and gson?


This is my Api class where json parsing is being done. But wherever I call Realm.getDefaultInstance(), at that line app stops running..Please help ...m stuck..Thanks in advance..

package com.portea.internal.api.realm_api;

import android.content.Context;
import android.util.Base64;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.portea.internal.app.App;
import com.portea.internal.constants.Constants;
import com.portea.internal.constants.PrintLog;
import com.portea.internal.enums.Transaction;
import com.portea.internal.network.Network;
import com.portea.internal.realm_pojo_container.AppointmentPojos.Appointments;
import com.portea.internal.realm_pojo_container.AppointmentPojos.AppointmmentMainObject;
import com.portea.internal.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import io.realm.Realm;
import io.realm.RealmList;

/**
 * Created by Dipti on 26/3/17.
 */

public class ApiAppointment extends Request<JSONObject> {

    private Response.Listener<JSONObject> listener;
    private boolean isSubordinateAppointment = false;
    private boolean forceReload = false;
    String Tag = "ApiAppointment";
    // RealmList<AppointmmentMainObject> realmObjList =null;
    RealmList<AppointmmentMainObject> inpList = null;
    Collection<AppointmmentMainObject> realmApts;
    private Context context;
    private Realm my_realm;//where to initialize this realm instance and where to close it


    AppointmmentMainObject obj1, obj2;

    public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url) {
        super(Request.Method.GET, getApiUrl(url), errorListener);
        this.listener = listener;
        setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, boolean forceReload) {
        super(Request.Method.GET, getApiUrl(url), errorListener);
        this.listener = listener;
        this.forceReload = forceReload;

        setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        Log.v(Tag + "dip", "" + getApiUrl(url));
    }

    public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, String append) {
        super(Request.Method.GET, getApiUrl(url) + append, errorListener);
        this.listener = listener;
        isSubordinateAppointment = true;
        setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        Log.v(Tag, "" + getApiUrl(url) + append);
    }

    public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, String append, boolean forceReload) {
        super(Request.Method.GET, getApiUrl(url) + append, errorListener);
        this.listener = listener;
        this.forceReload = forceReload;
        isSubordinateAppointment = true;

        setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        Log.e(Tag, " " + getApiUrl(url) + append);
    }

    static String getApiUrl(String url_append) {
        String lastSynced = App.getPref().get(Constants.STORAGE_KEY_LAST_APPOINTMENT_SYNCED);
        if (lastSynced == null) {
            lastSynced = "0";
        }

        if (url_append.length() > 0) {
            lastSynced = "0";
        }
        return Network.getTxnPath(Transaction.APPOINTMENTS, "/get?user_id="
                + App.getUser().getUserId() + "&key=" + App.getUser().getKey()
                + "&version=" + App.version + "&last_synced=" + lastSynced + url_append);
    }


    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        Log.v(Tag, "========================================>>");
        //Utils.sendLogoutBroadCast(App.getAppContext(), response.statusCode);
        Gson gson = new GsonBuilder().create();
//        Realm.init(App.getAppContext());
//        my_realm = Realm.getDefaultInstance();
        try {

            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            Log.i(Tag, jsonString);
            JSONObject MainObject = new JSONObject(jsonString);
            JSONArray dataObj = MainObject.getJSONArray("data");
            for (int i = 0; i < dataObj.length(); i++) {
                JSONObject singleUserObj = dataObj.getJSONObject(i);

                JSONArray apointment = singleUserObj.getJSONArray("appointments");
                for (int j = 0; j < apointment.length(); j++) {

                    JSONObject appointmentObj = apointment.getJSONObject(j);
//                    Appointments appointments=realm.createObjectFromJson(Appointments.class,appointmentObj);
//                    Log.v("Realmcheck",appointments.toString());
                    Type type = new TypeToken<RealmList<Appointments>>() {}.getType();
                    RealmList<Appointments> appointmentsObjList = gson.fromJson(apointment.toString(), type);
//                    List<Appointments> realm_copy_of_list=my_realm.copyToRealm(appointmentsObjList);                     Log.v("size", String.valueOf(appointmentsObjList.toString()));
                    RealmList<Appointments> apo = new RealmList<Appointments>();
                    Log.v("dipti", appointmentsObjList.get(j).toString());
                   // apo = (RealmList<Appointments>) my_realm.copyToRealm(appointmentsObjList);

                }
            }


            // Log.v(Tag + "xx", AppointmmentMainObject.getClinicianName());
            // Log.i("packageFee", String.valueOf(AppointmmentMainObject.getPackageFee()));
            return Response.success(MainObject, HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingException e) {
            PrintLog.d("e: " + e);
            e.printStackTrace();
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            PrintLog.d("je: " + je);
            je.printStackTrace();
            return Response.error(new ParseError(je));
        } catch (NullPointerException ne) {
            PrintLog.d("ne: " + ne);
            return Response.error(new ParseError(ne));

        }
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> params = new HashMap<>();
        String creds = String.format("%s:%s", "stage", "d7kVzNZDqn");
        String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
        params.put("Authorization", auth);
        params.put("DEVICE_ID", App.deviceId);
        return params;
    }

    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        try {
            Utils.sendLogoutBroadCast(App.getAppContext(),
                    volleyError.networkResponse.statusCode);
            Log.e("onErrorResponse", ""
                    + volleyError.networkResponse.statusCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return volleyError;
    }


    @Override
    protected void deliverResponse(JSONObject response) {

    }
}

Solution

  • I think your main problem is in the Realm initialization. You should have an application class and initialize your Realm in there. Like this:

    public class BaseApplication extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            Realm.init(this);
            RealmConfiguration config = new RealmConfiguration.Builder().build();
            Realm.setDefaultConfiguration(config);
        }
    }    
    

    And then you can call my_realm = Realm.getDefaultInstance();

    I hope this solves your problem.