2014-11-02 71 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