谁能解释一下如何在 Activity 之外初始化领域实例?例如,在用 volley 和 gson 解析 json 时?

Dipti Murlidhar Narwade

这是我正在完成 json 解析的 Api 类。但是无论我在哪里调用 Realm.getDefaultInstance(),在该行应用程序都会停止运行..请帮助...我卡住了..提前致谢..

包 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) {

    }
}
阿比尔哈桑

我认为您的主要问题在于Realm初始化。你应该有一个应用程序类并在那里初始化你的领域。像这样:

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

然后你可以打电话 my_realm = Realm.getDefaultInstance();

我希望这能解决你的问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档