1 回答

TA貢獻1821條經驗 獲得超6個贊
你的內部RequestYouTubeAPI ASyncTask有這個錯誤代碼:
} catch (IOException e) {
e.printStackTrace();
return null;
}
然后onPostExecute你有以下內容:
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response != null){
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
因此,如果您收到錯誤,return null并且onPostExecute收到響應, null則不會執行任何操作。
所以這個地方可能會出現錯誤,因此會出現空白片段。
在修復此問題之前,您可以證明這種情況正在發生,如下所示:
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response == null){
Log.e("TUT", "We did not get a response, not updating the UI.");
} else {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
您可以通過兩種方式解決此問題:
將doInBackground捕獲更改為:
} catch (IOException e) {
Log.e("TUT", "error", e);
// Change this JSON to match what the parse expects, so you can show an error on the UI
return "{\"yourJson\":\"error!\"}";
}
或者onPostExecute:
if(response == null){
List errorList = new ArrayList();
// Change this data model to show an error case to the UI
errorList.add(new YouTubeDataModel("Error");
mListData = errorList;
initList(mListData);
} else {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
希望有所幫助,代碼中可能還有其他錯誤,但如果 API、Json、授權、互聯網等存在問題,則可能會發生這種情況。
添加回答
舉報