2014-11-02 69 views
0

使用listview時,我有一個很大的問題,加載更多的數據和遠程圖像。我的項目讀取JSON數據,當不叫ImageLoader的作品成功json不工作的遠程圖像

但是當我使用它返回致命錯誤 我有文字的標記///錯誤和///誤差之間的塊 我的代碼是在這裏:

package com.prgguru.android; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AbsListView; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.widget.AbsListView.OnScrollListener; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 

import org.json.JSONArray; 
import org.json.JSONObject; 
import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.PropertyInfo; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapPrimitive; 
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 

import com.example.webserviceactivity.R; 

public class ListViewActivity extends Activity 
{ 
     ListView mListView; 
     String worldData = "", adsValues[], strProduce, adsResult = "" , maxId="", subject = "",description = "", guild = "", section = "", avenue = "", shoppingCenter = "", tel = "", mobile = "", img = ""; 
     JSONObject jsonOb; 
     JSONArray jsonArr; 
     JSONObject jsonOne; 
     List<HashMap<String, String>> searchResult = new ArrayList<HashMap<String,String>>(); 
     HashMap<String, String> searchResultTemp; 
     Integer intKind = 0, intGuild = 0, intSection = 0, intAvenue = 0, intShoppingCenter = 0; 

    public static final int progress_bar_type = 0; 
    private ProgressDialog pDialog; 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.searchresult); 
     Intent intent = getIntent(); 
     if(intent != null) worldData = intent.getStringExtra("adsResult"); 
     adsValues = worldData.split("Ý"); 
     String[] strValueTemp = adsValues[1].split("ï"); 

     intKind = Integer.parseInt(strValueTemp[0]); 
     intGuild = Integer.parseInt(strValueTemp[1]); 
     intSection = Integer.parseInt(strValueTemp[2]); 
     intAvenue = Integer.parseInt(strValueTemp[3]); 
     intShoppingCenter = Integer.parseInt(strValueTemp[4]); 
     strProduce = strValueTemp[5]; 
     if(strValueTemp[5].compareTo("n") == 0) strProduce = ""; 

     getlList(adsValues[0]); 

     /////////////////////////////////////////////////////////////// 
     mListView.setOnScrollListener(new OnScrollListener() { 

      public void onScrollStateChanged(AbsListView view, 
        int scrollState) { // TODO Auto-generated method stub 
       int threshold = 1; 
       int position = mListView.getLastVisiblePosition(); 
       int count = mListView.getCount(); 

       if (scrollState == SCROLL_STATE_IDLE) { 
        if (mListView.getLastVisiblePosition() >= count - threshold) { 
         getAdsResult(intKind, intGuild, intSection, intAvenue, intShoppingCenter, strProduce, Integer.parseInt(maxId)); 
         getlList(adsResult); 
         mListView.setSelection(position); 
        } 
       } 
      } 

      public void onScroll(AbsListView view, int firstVisibleItem, 
        int visibleItemCount, int totalItemCount) { 
       // TODO Auto-generated method stub 
      } 
     }); 
    } 
////////////////////////////////////////////////////////////////////////////////////////////////////// 
    public void getlList(String json) 
    { 
     try 
     { 
      jsonOb = new JSONObject(json); 
      jsonArr = jsonOb.getJSONArray("adsResults"); 
      for(int i = 0; i < jsonArr.length(); i++) 
      { 
       jsonOne = jsonArr.getJSONObject(i); 
       /////////////////////////////////////////////// 
       maxId = jsonOne.getString("id"); 
       subject = jsonOne.getString("subject"); 
       description = jsonOne.getString("desc"); 
       guild = jsonOne.getString("guildStr"); 
       tel = jsonOne.getString("tel"); 
       if(tel.compareTo("") != 0) tel = tel + " -- "; 
       mobile = jsonOne.getString("mobile"); 
       if(shoppingCenter.compareTo("0") == 0) 
       { 
        section = jsonOne.getString("sectionStr"); 
        avenue = jsonOne.getString("avenueStr"); 
        description = "\n" + description + "\n" + "صنف : " + guild + " -- پاساژ : " + shoppingCenter + " -- " + tel + mobile; 
      } 
      else 
      { 
       shoppingCenter = jsonOne.getString("shoppingCenterStr"); 
       description = "\n" + description + "\n" + "صنف : " + guild + " -- منطقه : " + section + "(" + avenue + ")" + " -- " + tel + mobile; 
      } 
      description += "\n"; 
      img = jsonOne.getString("img"); 
      searchResultTemp = new HashMap<String, String>(); 
      searchResultTemp.put("subject", subject); 
      searchResultTemp.put("description", description); 
      searchResultTemp.put("img", String.valueOf(R.drawable.s)); 
      /////////////////////////////////////////// 
      searchResult.add(searchResultTemp); 
     } 
     String[] from = {"subject","img","description"}; 
     int[] to = {R.id.tv_subject,R.id.iv_pic, R.id.tv_details}; 
     ///////////////////////////////////////////////////////////////////// 
     mListView = (ListView) findViewById(R.id.lv_Result); 
     mListView.setOnItemClickListener(new OnItemClickListener() 
     { 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
       { 
        int pos = mListView.getSelectedItemPosition(); 
        Toast.makeText(ListViewActivity.this, String.valueOf(pos), Toast.LENGTH_LONG).show(); 
       } 
     }); 
     ///////////////////////////////////////////////////////// 
     SimpleAdapter adapter = new SimpleAdapter(ListViewActivity.this,searchResult,R.layout.listview, from, to); 
     mListView.setAdapter(adapter); 
     ///////////////////////////////////////////////////////////////////////////////////////////// 

      ///error 
     for(int i=0;i<adapter.getCount();i++){ 
      HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i); 
      String imgUrl = (String) hm.get("img"); 
      ImageLoaderTask imageLoaderTask = new ImageLoaderTask(); 

      hm.put("img",imgUrl); 
      hm.put("position", i); 

      // Starting ImageLoaderTask to download and populate image in the listview 
      imageLoaderTask.execute(hm); 
     } 
       ///error 
    } 
    catch(Exception ex) 
    { 
     Toast.makeText(ListViewActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show(); 
    } 
    ////////////////////////////////////////////////////////////////////////////////////////////////// 

} 
////////////////////////////////////////////////////////////////////////////////////////////////////// 
public void getAdsResult(int intKind, int intGuild, int intSection, int intAveune,int intShoppingCenter, String produce, int idClause) 
{ 
    //Create request 
    SoapObject request = new SoapObject("http://admin.arabbros.com/", "searchAdsList"); 
    //Create envelope 
    PropertyInfo requestPI = new PropertyInfo(); 
    requestPI.setName("kind"); 
    requestPI.setValue(intKind); 
    requestPI.setType(int.class); 
    request.addProperty(requestPI); 
    requestPI = new PropertyInfo(); 
    ///////////////////////////////////////// 
    requestPI.setName("guild"); 
    requestPI.setValue(intGuild); 
    requestPI.setType(int.class); 
    request.addProperty(requestPI); 
    requestPI = new PropertyInfo(); 
    ///////////////////////////////////////// 
    requestPI.setName("section"); 
    requestPI.setValue(intSection); 
    requestPI.setType(int.class); 
    request.addProperty(requestPI); 
    requestPI = new PropertyInfo(); 
    ///////////////////////////////////////// 
    requestPI.setName("avenue"); 
    requestPI.setValue(intAveune); 
    requestPI.setType(int.class); 
    request.addProperty(requestPI); 
    requestPI = new PropertyInfo(); 
    ///////////////////////////////////////// 
    requestPI.setName("shoppingCenter"); 
    requestPI.setValue(intShoppingCenter); 
    requestPI.setType(int.class); 
    request.addProperty(requestPI); 
    requestPI = new PropertyInfo(); 
    ///////////////////////////////////////// 
    requestPI.setName("produce"); 
    requestPI.setValue(produce); 
    requestPI.setType(String.class); 
    request.addProperty(requestPI); 
    requestPI = new PropertyInfo(); 
    ///////////////////////////////////////// 
    requestPI.setName("idClause"); 
    requestPI.setValue(idClause); 
    requestPI.setType(int.class); 
    request.addProperty(requestPI); 
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
    envelope.dotNet = true; 
    //Set output SOAP object 
    envelope.setOutputSoapObject(request); 
    //Create HTTP call object 
    HttpTransportSE androidHttpTransport = new HttpTransportSE("http://admin.arabbros.com/MobileWs.asmx"); 

    try { 
     //Invole web service 
     androidHttpTransport.call("http://admin.arabbros.com/searchAdsList", envelope); 
     //Get the response 
     SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); 

     adsResult = response.toString(); 

    } catch (Exception e) { 
     adsResult = "0"; 
    } 
} 
/////////////////////////////////////////////////////////////////////////////////////////////// 
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{ 

    @Override 
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) { 

     InputStream iStream=null; 
     String imgUrl = (String) hm[0].get("img"); 
     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() + "/wpta_"+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("img",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("img");   

     // 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("img",path); 

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

你可能想嘗試提出您的問題作爲SSCCE :http://sscce.org。如果你願意,你更有可能獲得幫助。 – EJK 2014-11-02 03:36:35

+0

你可以嘗試只發布拋出錯誤的代碼區域,或者是關聯的嗎?拋出什麼特定的錯誤? – 2014-11-02 03:40:53

回答

0

好吧,過了一段時間,我有以下東西給你。既然這不是討論評論的好方法,我會在這裏發表。

第一:

你有這樣的代碼:searchResultTemp.put( 「IMG」,將String.valueOf(R.drawable.s)); (你提供給我的代碼),它會將你的「img」值設置爲一個ID字符串(不是有效的url)。這會導致LoaderTask的doInBackground方法失敗並返回空值。在你的onPostExecute中,你沒有檢查空返回,那麼它會導致你的應用程序失敗。請更改此(例如,放(「img」,img),其中img是您從json獲得的url)。

二:

您的JSON中是否有「IMG」屬性的條目,但它的價值是不是一個有效的HTTP URL(它是「dariran.com/ads/mobile/1.jpg」來說吧),因此,您的任務再次執行失敗,會導致返回空值。請修正它從你的服務器或任何將返回JSON結果。

三:

這是你如何開始你的列表視圖:您定義的getlList方法,添加一個try/catch,把你的列表視圖啓動碼內。例如,一旦您的解析過程失敗,某些條目不存在,您的代碼將拋出一個異常,並且您的列表視圖將永遠不會啓動。這是一個不好的方法。我建議你在onCreate方法中啓動所有基於視圖/活動的實例。

以下是我固定的代碼(有一些小的修改/註釋掉...),請把它添加到你的代碼,看看它的工作原理:http://paste.ofcode.org/AJA8twt2aJF6AGWHK3ZNRg

+0

非常感謝我的朋友:) – user3404171 2014-11-02 08:04:55

+0

不客氣。我也建議你不要這樣使用HashMap:D。至於你的目的,你可能想要創建一個對象來存儲關於img的必要信息,例如一個ImgInfo對象包含關於imgUrl的字符串,imgPath和一個整數定義它在listview中的位置。但只要按照最好的方式,讓你滿意。快樂的編碼! – 2014-11-03 05:02:39

+0

謝謝,但我是新來的java,不知道什麼是最好的方法;) – user3404171 2014-11-03 07:12:00

0

我的方法解析JSON是在這裏:

 public void getlList(String json) 
    { 
    try 
    { 
     jsonOb = new JSONObject(json); 
     jsonArr = jsonOb.getJSONArray("adsResults"); 
     for(int i = 0; i < jsonArr.length(); i++) 
     { 
      jsonOne = jsonArr.getJSONObject(i); 
      /////////////////////////////////////////////// 
      maxId = jsonOne.getString("id"); 
      subject = jsonOne.getString("subject"); 
      description = jsonOne.getString("desc"); 
      guild = jsonOne.getString("guildStr"); 
      tel = jsonOne.getString("tel"); 
      if(tel.compareTo("") != 0) tel = tel + " -- "; 
      mobile = jsonOne.getString("mobile"); 
      if(shoppingCenter.compareTo("0") == 0) 
      { 
       section = jsonOne.getString("sectionStr"); 
       avenue = jsonOne.getString("avenueStr"); 
       description = "\n" + description + "\n" + "صنف : " + guild + " -- پاساژ : " + shoppingCenter + " -- " + tel + mobile; 
     } 
     else 
     { 
      shoppingCenter = jsonOne.getString("shoppingCenterStr"); 
      description = "\n" + description + "\n" + "صنف : " + guild + " -- منطقه : " + section + "(" + avenue + ")" + " -- " + tel + mobile; 
     } 
     description += "\n"; 
     img = jsonOne.getString("img"); 
     searchResultTemp = new HashMap<String, String>(); 
     searchResultTemp.put("subject", subject); 
     searchResultTemp.put("description", description); 
     searchResultTemp.put("img", String.valueOf(R.drawable.s)); 
     /////////////////////////////////////////// 
     searchResult.add(searchResultTemp); 
    } 
    String[] from = {"subject","img","description"}; 
    int[] to = {R.id.tv_subject,R.id.iv_pic, R.id.tv_details}; 
    ///////////////////////////////////////////////////////////////////// 
    mListView = (ListView) findViewById(R.id.lv_Result); 
    mListView.setOnItemClickListener(new OnItemClickListener() 
    { 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
      { 
       int pos = mListView.getSelectedItemPosition(); 
       Toast.makeText(ListViewActivity.this, String.valueOf(pos), Toast.LENGTH_LONG).show(); 
      } 
    }); 
    ///////////////////////////////////////////////////////// 
    SimpleAdapter adapter = new SimpleAdapter(ListViewActivity.this,searchResult,R.layout.listview, from, to); 
    mListView.setAdapter(adapter); 
    ///////////////////////////////////////////////////////////////////////////////////////////// 

     ///error 
    for(int i=0;i<adapter.getCount();i++){ 
     HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i); 
     String imgUrl = (String) hm.get("img"); 
     ImageLoaderTask imageLoaderTask = new ImageLoaderTask(); 

     hm.put("img",imgUrl); 
     hm.put("position", i); 

     // Starting ImageLoaderTask to download and populate image in the listview 
     imageLoaderTask.execute(hm); 
    } 
      ///error 
} 
catch(Exception ex) 
{ 
    Toast.makeText(ListViewActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show(); 
} 
////////////////////////////////////////////////////////////////////////////////////////////////// 

} 

我的代碼不能將就,因爲ImageLoaderTask類返回錯誤的工作。我在另一個項目中測試了ImageLoaderTask類,並且此代碼可以成功運行,但在這裏返回錯誤。

我ImageLoaderTask CLAS是:

 private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{ 

@Override 
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) { 

    InputStream iStream=null; 
    String imgUrl = (String) hm[0].get("img"); 
    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() + "/wpta_"+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("img",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("img");   

    // 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("img",path); 

    // Noticing listview about the dataset changes 
    adapter.notifyDataSetChanged(); 
    } 
} 
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{ 

@Override 
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) { 

    InputStream iStream=null; 
    String imgUrl = (String) hm[0].get("img"); 
    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() + "/wpta_"+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("img",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("img");   

    // 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("img",path); 

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

我調試它和行 字符串路徑=(字符串)result.get( 「IMG」); onPollAlarm期間

問題:返回的錯誤java.lang.IllegalStateException:問題分析統計:java.io.FileNotFoundException:的/ proc /淨/ xt_qtaguid/iface_stat_all:打開失敗:ENOENT(沒有這樣的文件或目錄)

+0

嘗試調試您的ImageLoaderTask以查看哪條線導致您的錯誤? – 2014-11-02 04:21:05

+0

我無法調試它顯示不幸您的應用程序已停止 – user3404171 2014-11-02 04:29:01

+0

嗯,我現在正在閱讀您的代碼。我想問你的應用程序停止時你的IDE是否返回錯誤日誌?我也想評論說你的代碼的設計很複雜。但我會試圖找出問題所在。請在您的應用程序(強制)關閉後立即告訴/發佈任何您的IDE日誌。 – 2014-11-02 04:46:27