0

我建立一個應用程序,它顯示了與描述,品牌,價格和圖像列表視圖項目。通過下載JSON文件填充listView。下載圖像後,進度對話框不會消失,應用程序會凍結。我需要ProgressDialog以避免用戶在圖像下載之前點擊單元格。我搜索了一個解決方案,但沒有找到答案。 編輯: 我有沒有錯誤或excepction和TOAST出現在屏幕上。 代碼,我實現進度對話框:編輯:ProgressDialog解僱()被忽略

public class ListViewCategory extends Activity { 

    private int jsonLength = 0; 
    private int control = 0; 
    private ProgressDialog waitingDialog; 
    ListView mListView; 
    String strUrl; 
     @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listview_category_layout);  

     // URL to the JSON data 
     Intent iN = getIntent(); 
     Bundle b = iN.getExtras(); 
     if (b!=null){ 
      strUrl=(String)b.get("urlJSON"); 
     } 

     // Creating a new non-ui thread task to download json data 
     DownloadTask downloadTask = new DownloadTask(); 

     // Starting the download process 
     downloadTask.execute(strUrl); 

     // Getting a reference to ListView of activity_main 
     mListView = (ListView) findViewById(R.id.list); 

    mListView.setOnItemClickListener(new OnItemClickListener(){ 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id){ 
       … 
      } 
     }); 


    } 



    /** A method to download json data from url */ 
    private String downloadUrl(String strUrl) throws IOException{ 
     String data = ""; 
     InputStream iStream = null; 
     try{ 
       URL url = new URL(strUrl); 

       // Creating an http connection to communicate with url 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

       // Connecting to url 
       urlConnection.connect(); 

       // Reading data from url 
       iStream = urlConnection.getInputStream(); 

       BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 

       StringBuffer sb = new StringBuffer(); 

       String line = ""; 
       while((line = br.readLine()) != null){ 
        sb.append(line); 
       } 

       data = sb.toString(); 

       br.close(); 

     }catch(Exception e){ 
       Log.d("Exception while downloading url", e.toString()); 
     }finally{ 
       iStream.close(); 
     } 

     return data; 
    } 



    /** AsyncTask to download json data */ 
    private class DownloadTask extends AsyncTask<String, Integer, String>{ 
     String data = null; 

       @Override 
       protected String doInBackground(String... url) { 
         try{ 
          data = downloadUrl(url[0]); 

         }catch(Exception e){ 
          Log.d("Background Task",e.toString()); 
         } 
         return data; 
       } 

       @Override 
       protected void onPostExecute(String result) { 

         // The parsing of the xml data is done in a non-ui thread 
         ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask(); 

         // Start parsing xml data 
         listViewLoaderTask.execute(result);       

       } 
    } 

    /** AsyncTask to parse json data and load ListView */ 
    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{ 



     JSONObject jObject; 

     // Doing the parsing of xml data in a non-ui thread 
     @Override 
     protected SimpleAdapter doInBackground(String... strJson) { 
      try{ 
       jObject = new JSONObject(strJson[0]); 
       JSONParser jsonParser = new JSONParser(); 
        jsonParser.parse(jObject); 
      }catch(Exception e){ 
       Log.d("JSON Exception1",e.toString()); 
      } 

      // Instantiating json parser class 
      JSONParser jsonParser = new JSONParser(); 

      // A list object to store the parsed countries list 
      List<HashMap<String, Object>> brands = null; 

      try{ 
       // Getting the parsed data as a List construct 
       brands = jsonParser.parse(jObject); 
      }catch(Exception e){ 
       Log.d("Exception",e.toString()); 
      }   

      // Keys used in Hashmap 
      String[] from = { "foto","marca","modelo","precio","foto"}; 

      // Ids of views in list_v layout 
      int[] to = { R.id.fotos,R.id.marcas,R.id.modelos,R.id.precios,R.id.tvUrl}; 

      // Instantiating an adapter to store each items 
      // R.layout.list_v defines the layout of each item   
      SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), brands, R.layout.list_v, from, to); 

      return adapter; 
     } 

     /** Invoked by the Android on "doInBackground" is executed */ 


     @Override 
     protected void onPostExecute(SimpleAdapter adapter) { 

      // Setting adapter for the listview 
      mListView.setAdapter(adapter); 
      jsonLength = adapter.getCount(); 
      for(int i=0;i<adapter.getCount();i++){ 
       HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i); 
       String imgUrl = (String) hm.get("photoUrl"); 
       //Log.i(TAG, imgUrl); 
       ImageLoaderTask imageLoaderTask = new ImageLoaderTask(); 

       HashMap<String, Object> hmDownload = new HashMap<String, Object>(); 
       hm.put("photoUrl",imgUrl); 
       hm.put("position", i); 

       // Starting ImageLoaderTask to download and populate image in the listview 
       imageLoaderTask.execute(hm); 

      } 

     }  
    } 

    /** AsyncTask to download and load an image in ListView */ 
    private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{ 

     //Adding preExecute 
     @Override 
     protected void onPreExecute(){ 
     waitingDialog = ProgressDialog.show(ListViewCategory.this, 「Wait..」, "Downloading」);     waitingDialog.setCancelable(true); 
     waitingDialog.show(); 
     } 

     @Override 
     protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) { 
      InputStream iStream=null; 
      String imgUrl = (String) hm[0].get("photoUrl"); 
      int position = (Integer) hm[0].get("position"); 

      URL url; 
      try { 
       url = new URL(imgUrl); 

       // Creating an http connection to communicate with url 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

       // Connecting to url     
       urlConnection.connect(); 

       // Reading data from url 
       iStream = urlConnection.getInputStream(); 

       // Getting Caching directory 
       File cacheDirectory = getBaseContext().getCacheDir(); 

       // Temporary file to store the downloaded image 
       File tmpFile = new File(cacheDirectory.getPath() + "/lakari_"+position+".png");    

       // The FileOutputStream to the temporary file 
       FileOutputStream fOutStream = new FileOutputStream(tmpFile); 

       // Creating a bitmap from the downloaded inputstream 
       Bitmap b = BitmapFactory.decodeStream(iStream);    

       // Writing the bitmap to the temporary file as png file 
       b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);    

       // Flush the FileOutputStream 
       fOutStream.flush(); 

       //Close the FileOutputStream 
       fOutStream.close();    

       // Create a hashmap object to store image path and its position in the listview 
       HashMap<String, Object> hmBitmap = new HashMap<String, Object>(); 

       // Storing the path to the temporary image file 
       hmBitmap.put("foto",tmpFile.getPath()); 

       // Storing the position of the image in the listview 
       hmBitmap.put("position",position);    

       // Returning the HashMap object containing the image path and position 

       return hmBitmap;     

      }catch (Exception e) {    
       e.printStackTrace(); 
       return null; 
      } 



     } 

     @Override 
     protected void onPostExecute(HashMap<String, Object> result) { 


      // Getting the path to the downloaded image 
      String path = (String) result.get("foto");   

      // Getting the position of the downloaded image 
      int position = (Integer) result.get("position"); 

      // Getting adapter of the listview 
      SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter(); 

      // Getting the hashmap object at the specified position of the listview 
      HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position); 

      // Overwriting the existing path in the adapter 
      hm.put("foto",path); 

      //Count number of images downloaded and sent to listview 
      control++; 
      Log.i(TAG_2, String.valueOf(control)); 

      // Noticing listview about the dataset changes 
      adapter.notifyDataSetChanged(); 

      if (control/jsonLength == 0){ 
       waitingDialog.dismiss(); 
       Toast.makeText(ListViewCategory.this, "Toast Appears. Yes...", Toast.LENGTH_SHORT).show(); 

      } 
     }  
    } 

} 

你能幫助我嗎?

回答

0

要返回null到postExecute

這就是爲什麼你的,如果條件得到假這裏

if(waitingDialog != null && waitingDialog.isShowing()) 
      { 
       waitingDialog.dismiss(); 
      } 

刪除返回在`doInBackground(NULL);

}catch (Exception e) {    
        e.printStackTrace(); 
       } 
     ->  return null; 
+0

對,但我不能刪除'return null;',我有一個錯誤。該方法「返回」一個HashMap。 – Luis

0

我建議您嘗試使用Picasso來處理從url加載圖片。 或Volley它處理網絡連接以及圖像加載/緩存。

這是非常簡單和更好的選擇。