2016-08-04 119 views
1

im當用戶登錄並將其保存爲共享的特權時嘗試創建用戶對象。用戶對象具有名稱和姓氏,它從json對象中取回,並且我試圖用piccaso(圖片的行也在json對象中)獲取位圖配置文件圖片。我嘗試了排球,並在兩種情況下與asynctask我得到的extent。java.lang.IllegalStateException:方法調用不應該從piccaso的主線程發生

我的用戶模型:

public class User{ 

    private String name,lastName; 
    private Bitmap profilePicture; 
    Context context; 

    public User(JSONObject object , Context context){ 
     this.context = context; 

     try { 
      this.name = object.getString("firstName"); 
      this.lastName = object.getString("lastName"); 
      this.profilePicture = Picasso.with(context).load(object.getString("image")).get(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

和我的截擊要求:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, 
       new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
         try { 

          Intent intent = new Intent(LoginActivityScreen.this, HomeActivityScreen.class); 

          SharedPreferences.Editor editor = preferences.edit(); 

          RoomateModel model = new RoomateModel(response, context); 


          Gson gson = new Gson(); 
          String json = gson.toJson(model); 
          editor.putString("USER", json); 
          editor.commit(); 


          startActivity(intent); 


         } 

        } 

回答

2

基本上它的NetworkOnMainThreadException封裝。

你需要檢查你在哪裏打電話User(...)構造,因爲他們有這樣一行:

this.profilePicture = Picasso.with(context).load(object.getString("image")).get(); 

有效地做一個遠程調用,以從object.getString("image")網址檢索圖片。確保調用在非UI線程上執行。這是使用Picasso的主要優勢,因爲它確保網絡處理和數據緩衝在一個線程內完成,並且在UI線程內完成對Android UI元素(ImageView)內的資源(圖像)的擴充,而不需要額外的努力圖書館的用戶。

或者,你可以嘗試使用畢加索的Target接口:

Picasso.with(context).load(object.getString("image").into(new Target() { 
    @Override 
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { 
     //This gets called when your application has the requested resource in the bitmap object 
     User.this.profilePicture = bitmap; 
    } 

    @Override 
    public void onBitmapFailed(Drawable errorDrawable) { 
     //This gets called if the library failed to load the resource 
    } 

    @Override 
    public void onPrepareLoad(Drawable placeHolderDrawable) { 
     //This gets called when the request is started 
    } 
}); 
+1

我試圖doInBackground()在的AsyncTask我有叫它同樣的例外。 @NitroNbg –

+1

檢查編輯以查看替代方案。不過,我不建議發出異步調用,即使在對象的構造函數中有回調。你可以在你的'User'對象中只存儲個人資料圖片的'String'(URL),然後發佈'Piccasso.with(context).load(user.getProfilePicture())。到(imageView)'中即將在應用程序中顯示該用戶的圖片。 – NitroNbg

+1

非常感謝!它工作@ NitroNbg –

-1

嘗試添加該部分之前的代碼加載圖像

if (android.os.Build.VERSION.SDK_INT > 9) { 
      StrictMode.ThreadPolicy policy = 
        new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
       StrictMode.setThreadPolicy(policy); 
} 
+0

它沒有工作。 –

相關問題