2016-11-08 78 views
-1

我在我的應用程序中有一個asyncTask,如下所示。我必須從領域(這是成功存儲在另一個活動)獲取數據到這個AsyncTask。下面是我的AsyncTask代碼: - 「境界接入不正確的線程境界對象只能創建它們的線程上進行訪問。」Android,如何在AsyncTask中啓動領域?

public class MakeAsyncRequest extends AsyncTask<Object, String, MakeAsyncRequest.ResponseDataType>{ 

public Context asyncContext; 
    private MakeAsyncRequest(Context context){ 
     asyncContext = context; 
    } 

private static final OkHttpClient client = new OkHttpClient(); 
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); 

private MakeRequest.ResponseHandler handler; 
private String method; 
private User user; 
private Realm realm; 


class ResponseDataType 
{ 
    InputStream inputStream; 
    String string; 
    String cookie; 
} 
MakeAsyncRequest(MakeRequest.ResponseHandler responseHandler, String type) 
{ 
    method = type; 
    handler = responseHandler; 
} 


@Override 

protected ResponseDataType doInBackground(Object... params) { 
    try { 
     Requests requests = new Requests((Context) params[0]); 
     String url = params[1].toString(); 
     String bodyJson = null; 
     if(method.equals("PUT") || method.equals("POST")) { 
      bodyJson = params[2].toString(); 
     } 
     final Request.Builder builder; 
     Response response; 
     RequestBody body; 
     switch (method) { 

      case "GET": builder = new Request.Builder().url(url); 
       break; 

      case "DOWNLOAD": builder = new Request.Builder().url(url); 
       break; 

      case "POST": body = RequestBody.create(JSON, bodyJson); 
       builder = new Request.Builder() 
         .url(url) 
         .post(body) 
         .addHeader("Cookie", "key=value"); 
       break; 

      case "PUT": body = RequestBody.create(JSON, bodyJson); 
       builder = new Request.Builder() 
         .url(url) 
         .put(body); 
       break; 

      default: builder = new Request.Builder().url(url); 
     } 
     builder.addHeader("Accept", "application/json"); 
     realm = RealmController.initialize(this).getRealm(); 
     final RealmResults<User> users = realm.where(User.class).findAllAsync(); 
     user = users.first(); 
     if(user.getCookie() !== null && !user.getCookie().isEmpty()){ 
      builder.addHeader("cookie", "user.getCookie()"); 
     } 
     response = client.newCall(builder.build()).execute(); 
     ResponseDataType responseDataType = new ResponseDataType(); 
     if(method.equals("DOWNLOAD")) { responseDataType.inputStream = response.body().byteStream(); } 
     else { 
      responseDataType.string = response.body().string(); 
      responseDataType.cookie = response.headers().get("set-cookie"); 
      CookieManager cManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL); 
      cManager.getCookieStore().getCookies(); 
     } 
     return responseDataType; 

    } catch (IOException e) { 
     return null; 
    } 
} 

@Override 
protected void onPostExecute(ResponseDataType response) { 
    try { 
     if (method.equals("DOWNLOAD")) { 
      handler.onFinishCallback(response.inputStream); 
     }else { 
      handler.onFinishCallback(response.string, response.cookie); 
      CookieManager cManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL); 
      cManager.getCookieStore().getCookies(); 
     } 
    }catch (Exception e){ 
     Log.d("hExceptionError", e.toString()); 
     handler.onFinishCallback("{\n" + 
       " \"error\": \"error\"\n" + 
       "}",""); 
    } 
} 

我收到了訪問錯誤每當控件嘗試執行Realm結果或從Realm獲取第一個對象時。

下面是我RealmController我創建控制領域實例:

public class RealmController {`public static RealmController initialize(Activity activity) { 

    if (instance == null) { 
     instance = new RealmController(activity.getApplication()); 
    } 
    return instance; 
} 
public static RealmController initialize(MakeAsyncRequest activity) { 

    if (instance == null) { 
     instance = new RealmController(activity.); 
    } 
    return instance; 
} 
}` 

我有一個getter和setter方法我的用戶模型(領域對象)。

+0

您的代碼不完整,請發送MVCE –

+0

@TimCastelijns我可以知道什麼是MVCE?我是編碼的初學者。 –

+0

@ThillaiK MVCE是最小,完整和可驗證的示例 - http://stackoverflow.com/help/mcve – jakubbialkowski

回答

0

問題是 - 您不能在不同的線程上創建和訪問Realm,即在Activity中創建Realm實例並在.doInBackground()方法中使用它。在交易前後立即創建並釋放Realm。 可能還有另一個問題 - 不要在AsyncTask的後臺線程中註冊查詢觀察者 - 它沒有Looper初始化 - 使用主線程或HandlerThread。 釋放領域後不再需要(你沒有在你的代碼中),因爲Realm的實例數量有限。