2016-11-04 65 views
-1

我知道有一些相同的問題,但我無法弄清楚我做錯了什麼。NetworkOnMainThreadException - Android/Java

public class MainActivity extends AppCompatActivity { 
... 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     ... 
     new JsonHandler().execute(this, collection, gridArray, customGridAdapter); 
     ... 
    } 
} 

所以在我的主要活動中,我需要查詢一個API,它給出了返回JSON,我必須處理它來構建我的數據庫。

然後在doInBackground()中調用getAllCards()來獲取第一個JSON。由於JSON包含更多JSON請求的URL,因此我有幾個方法可以查詢更詳細的JSON。

public final class JsonHandler extends AsyncTask { 
private final String urlCards = "https://api.gwentapi.com/v0/cards/"; 
private final String urlSpecificCard = "https://api.gwentapi.com/v0/cards/:id"; 

private Context context; 
private Collection collection; 
private ArrayList<Card> gridArray; 
private CustomGridViewAdapter customGridAdapter; 

public JsonHandler(Context context, Collection collection, ArrayList<Card> gridArray, CustomGridViewAdapter customGridAdapter){ 
    this.context = context; 
    this.collection = collection; 
    this.gridArray = gridArray; 
    this.customGridAdapter = customGridAdapter; 
} 

public JsonHandler(){ 
    this.context = null; 
    this.collection = null; 
    this.gridArray = null; 
    this.customGridAdapter = null; 
} 

private void getAllCards() throws RuntimeException { 
    JsonObjectRequest arrayRequest = new JsonObjectRequest(Request.Method.GET, urlCards, null, new Response.Listener<JSONObject>() { 

     @Override 
     public void onResponse(JSONObject response) { 
      generateCollection(response); 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError e) { 
      throw new RuntimeException(e.getMessage()); 
     } 
    }); 

    Volley.newRequestQueue(context).add(arrayRequest); 
} 

private void getSpecificCard(final String cardURL) throws RuntimeException { 
    JsonObjectRequest arrayRequest = new JsonObjectRequest(Request.Method.GET, cardURL, null, new Response.Listener<JSONObject>() { 

     @Override 
     public void onResponse(JSONObject response) { 
      processCard(response, collection); 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError e) { 
      throw new RuntimeException(e.getMessage()); 
     } 
    }); 

    Volley.newRequestQueue(context).add(arrayRequest); 
} 

private void generateCollection(JSONObject response) throws RuntimeException { 
    try { 
     JSONArray array = response.getJSONArray("results"); 
     for(int i = 0; i < array.length();i++){ 
      JSONObject object = array.getJSONObject(i); 
      String cardURL = object.getString("href"); 
      getSpecificCard(cardURL); 
     } 
    } catch (Exception e) { 
     throw new RuntimeException(e.getMessage()); 
    } 
} 

private void processCard(JSONObject response, Collection collection){ 
    try { 
     String id = response.getString("id"); 
     EnumFaction faction = EnumFaction.valueOf(response.getJSONObject("faction").getString("name").toUpperCase()); 
     EnumType type = null; 
     EnumRarity rarity = null; 
     EnumLane lane = null; 
     EnumLoyalty loyalty = null; 
     String name = response.getString("name"); 
     String text = response.getString("text"); 
     String imagePath = "https://api.gwentapi.com/media/\" + id + \"_small.png"; 

     URL url = new URL(imagePath); 
     InputStream inputStream = url.openConnection().getInputStream(); 
     Bitmap image = BitmapFactory.decodeStream(inputStream); 

     Card card = new Card(id, faction, type, rarity, lane, loyalty, name, text, null, imagePath, 0); 
     collection.addCard(card); 
     gridArray.add(card); 
     customGridAdapter.notifyDataSetChanged(); 
    } catch (Exception e){ 
     throw new RuntimeException(e.getMessage()); 
    } 
} 

@Override 
protected Object doInBackground(Object[] params) { 
    context = (Context) params[0]; 
    collection = (Collection) params[1]; 
    gridArray = (ArrayList<Card>) params[2]; 
    customGridAdapter = (CustomGridViewAdapter) params[3]; 
    getAllCards(); 
    return null; 
} 

}

所以現在的問題:

當PROGRAMM達到processCard()時,我已經收集了足夠的信息,我得到一個NetworkOnMainThreadException當我創建InputStream的。

我已經嘗試了很多不同的方法來從我的URL和不同的方法獲取位圖來執行異步任務 - 所有這些都導致相同的結果。

如果你能告訴我如何解決這個問題,我會非常高興。

編輯:由於它被標記爲重複:我使用ASYNCTASK!我看了很多問題,並嘗試了他們在那裏做了什麼,這是行不通的!

+0

您正在使用亂射。你不需要AsyncTask ... –

+0

嗯,我啓動了AsyncTask,因爲它給了我這個例外。所以我搜索了互聯網,每個人都說它需要成爲一個AsyncTasc。錯誤仍然是有或沒有AsyncTask相同... – Darkmessage

+0

您的錯誤是因爲Volleys onResponse發生在主UI上......您在AsyncTask之外調用'processCard'。這篇文章**是**重複。在後臺完成的唯一部分「getAllCards」將添加到Volley隊列中。 –

回答

0

沒有真正熟悉如何凌空作品,但onResponse但要在主線程,所以你需要開始一個新的線程來打這通電話也

+0

但是,從一個新線程的doInBackground調用Json方法? – Darkmessage

+0

@Darkmessage在後臺調用的唯一東西就是你的'getAllCards'回調'onResponse'回調在主線程中 – tyczj

相關問題