Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android json不起作用的远程图像_Android - Fatal编程技术网

Android json不起作用的远程图像

Android json不起作用的远程图像,android,Android,我在使用listview、加载更多数据和远程图像时遇到了一个很大的问题。我的项目从json读取数据,当不调用ImageLoader成功时 但当我使用它时,返回致命错误 我有一个介于///error和///error之间的文本标记块 我的代码在这里: package com.prgguru.android; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import ja

我在使用listview、加载更多数据和远程图像时遇到了一个很大的问题。我的项目从json读取数据,当不调用ImageLoader成功时

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

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

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

第一:

代码中包含以下内容:searchResultTemp.putimg、String.valueOfR.drawable.s;您提供给我的代码,它将您的img值设置为ID字符串,而不是有效的url。这将导致LoaderTask的doInBackground方法失败并返回空值。在onPostExecute中,您没有检查null是否返回,这会导致应用程序失败。请更改这个putimg,例如img,其中img是您从json表单获得的url

第二:

您的json有一个img属性条目,但其值不是有效的http url。例如,它是dariran.com/ads/mobile/1.jpg,因此,您的任务再次未能执行http请求,这将返回null。请从您的服务器修复它,否则将返回Json结果

第三:


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

您可能希望尝试将问题表示为SSCCE:。如果你这样做,你更可能得到帮助。你能试着只发布抛出错误或关联的代码区域吗?抛出了什么具体错误?不客气。我还建议您不要这样使用HashMap:D。出于您的目的,您可能希望创建一个对象来存储有关img的必要信息,例如一个ImgInfo对象,其中包含关于imgUrl、imgPath的字符串和一个定义其在listview中位置的整数。但只要遵循你未来的最佳方式。快乐编码!谢谢,但我是java新手,不知道什么是最好的方法;