json无法正常工作的远程图像

时间:2014-11-02 03:30:26

标签: android

使用listview时,我有一个很大的问题,加载更多数据和远程图像。我的项目从json读取数据,当没有调用ImageLoader成功工作时

但是当我使用它时会返回致命错误 我在///错误和///错误之间有一个文本标记块 我的代码在这里:

    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(); 
    }
    }
}

1 个答案:

答案 0 :(得分:0)

好的,过了一会儿,我有以下东西给你。由于这不是在评论中讨论的好方法,我将在这里发布。

首先:

你的代码中有这个:searchResultTemp.put(&#34; img&#34;,String.valueOf(R.drawable.s)); (你提供给我的代码),这将设置你的&#34; img&#34;值到ID字符串(不是有效的URL)。这将导致LoaderTask的doInBackground方法失败并返回null值。在你的onPostExecute中,你没有检查null返回,然后它导致你的应用程序失败。请更改此(put(&#34; img&#34;,img),例如,其中img是你从json获得的url)。

第二

你的json有&#34; img&#34;属性,但其值不是有效的http url(例如,&#34; dariran.com/ads/mobile/1.jpg"),因此,您的任务再次无法执行http请求,将给出null返回。请从您的服务器或任何将返回Json结果的内容中修复它。

第三

这是您启动listview的方式:您定义了一个getlList方法,添加了一个try / catch并将listview启动代码放入其中。一旦您的解析过程失败,例如,某些条目不存在,您的代码将抛出异常,您的列表视图将永远不会启动。这是一个糟糕的方法。我建议您在onCreate方法中启动所有基于视图/活动的实例。