首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 新聞客戶端:Logcat 能解析 JSON 但 ListView 無顯示的完整排查指南

     編輯:程式設計綜合問答

問題現象

網絡請求返回 JSON,Logcat 打印顯示解析正常,但 ListView 仍然空白無數據。

常見原因與解決

  1. Adapter 未通知更新:解析完成後需在主線程呼叫 adapter.notifyDataSetChanged()。原代碼中該行被註釋。
    // 在 handleMessage 最後添加
    runOnUiThread(() -> adapter.notifyDataSetChanged());
    
  2. 圖片加載邏輯錯誤:NewsAdapter.getView() 中呼叫 HttpUtils.setPicBitmap(thumb_value, null),第二參數傳 null 導致圖片下載地址為空。應傳入 news.getCustom_fields() 或具體圖片 URL 字段。
    String imgUrl = news.getCustom_fields(); // 或解析出的 thumb_value
    HttpUtils.setPicBitmap(thumb_value, imgUrl);
    
  3. 網絡請求在主線程:HttpUtils.setPicBitmap 內部開啟新線程下載圖片,但直接在子線程更新 UI (thumb_value.setImageBitmap) 會拋出異常且無顯示。需使用 runOnUiThread 或 Handler 回主線程設置圖片。
    // 修正 setPicBitmap
    new Handler(Looper.getMainLooper()).post(() -> thumb_value.setImageBitmap(bitmap));
    
  4. JSON 結構與解析不匹配:示例 JSON 顯示數據在 posts 數組中,且圖片地址在 custom_fields.thumb_value[0],原代碼直接讀 custom_fields 字符串,導致圖片 URL 解析錯誤。建議使用 Gson 或 Moshi 自動映射實體類。
    // 使用 Gson 範例
    Gson gson = new Gson();
    NewsResponse response = gson.fromJson(jsonData, NewsResponse.class);
    newsList.addAll(response.posts);
    adapter.notifyDataSetChanged();
    

最佳實踐建議

  • 採用 Retrofit + OkHttp + Gson 替換手寫 HttpURLConnection,簡化網絡層。
  • 圖片加載使用 Glide / Picasso / Coil,自動處理緩存、線程、生命週期。
  • 列表展示改用 RecyclerView + ViewBinding,性能與維護性更優。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved