Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/204.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
在listview中设置图像在android中不起作用_Android_Listview_Bitmap_Filenotfoundexception - Fatal编程技术网

在listview中设置图像在android中不起作用

在listview中设置图像在android中不起作用,android,listview,bitmap,filenotfoundexception,Android,Listview,Bitmap,Filenotfoundexception,我想在listview中显示restaurent名称及其图像。我已成功获取restaurent name,但未获取图像。这是我的代码。我已访问我的输出屏幕。您可以看到restaurent name正在显示,但图像不显示。它们应位于左侧 public class RestaurantSelect extends Activity { ProgressDialog mProgressDialog; ListView listview; private String key,ResCategory,u

我想在listview中显示restaurent名称及其图像。我已成功获取restaurent name,但未获取图像。这是我的代码。我已访问我的输出屏幕。您可以看到restaurent name正在显示,但图像不显示。它们应位于左侧

public class RestaurantSelect extends Activity {
ProgressDialog mProgressDialog;
ListView listview;
private String key,ResCategory,url;
private SimpleAdapter listadapter;
JsonArray jobj= new JsonArray();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_restaurant_select);

    new AreaPOP().execute();
    listview = (ListView) findViewById(R.id.listResturent);
    Intent in = getIntent();

    try
    {
        if(!in.getStringExtra("AreaID").isEmpty())
        {
            //url="http://192.168.0.2/cityapp/GETresturentByArea.php";
            url="http://www.mycityapp.co.in/api/GETresturentByArea.php";
            key=in.getStringExtra("AreaID");
        }
    }
    catch (Exception e)
    {
        //url="http://192.168.0.2/cityapp/GETresturentByCategory.php";
        url="http://www.mycityapp.co.in/api/GETresturentByCategory.php";
        key=in.getStringExtra("ResCategory");
    }
    listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
            //http://saigeethamn.blogspot.in/2010/04/custom-listview-android-developer.html
            //http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
            //http://digitallibraryworld.com/?p=195
            HashMap fullObject = (HashMap)arg0.getItemAtPosition(position);
            Intent in = new Intent(getApplicationContext(), RestaurantDetail.class);
            in.putExtra("ResID", fullObject.get("rowid").toString());
            startActivity(in);
        }
    });

}

private class AreaPOP extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(RestaurantSelect.this);
        mProgressDialog.setTitle("getting data");

        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }


    @Override
    protected Void doInBackground(Void... params) {
       // String url_create_product="http://www.mycityapp.co.in/api/GETresturent.php";

        List<NameValuePair> paramsRes = new ArrayList<NameValuePair>();
        paramsRes.add(new BasicNameValuePair("key", key));
        JSONArray json = jobj.makeHttpRequest(url,"POST", paramsRes);
        List<HashMap<String, Object>> listdata = new ArrayList<HashMap<String, Object>>();
        JSONObject c;
        for (int i=0;i<json.length();i++){
            try {
                HashMap<String,Object> temp = new HashMap<String,Object>();
                c = json.getJSONObject(i);
                temp.put("rowid",c.getString("rowid"));
                temp.put("restaurantname", c.getString("restaurantname").toUpperCase());
                temp.put("resMainImg", c.getString("resMainImg"));
                temp.put("img",R.drawable.ic_launcher);
                listdata.add(temp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        listadapter = new SimpleAdapter(RestaurantSelect.this,listdata,R.layout.custom_row_view,new String[] {"restaurantname","resMainImg"},new int[] {R.id.txtListRest,R.id.imgListRestMainPic});

        return null;
    }
    @Override
    protected void onPostExecute(Void args) {
        listview.setAdapter(listadapter);
        for(int i=0;i<listadapter.getCount();i++){

            HashMap<String, Object> hm = (HashMap<String, Object>) listadapter.getItem(i);
            String imgUrl = (String) hm.get("resMainImg");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("resMainImg",imgUrl);
            hm.put("position", i);

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

        }
        mProgressDialog.dismiss();
    }

}

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("resMainImg");
        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("flag",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("flag");
        // Getting the position of the downloaded image
        int position = (Integer) result.get("position");
        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) listview.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("flag", path);
        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged();
    }


}
使用。
它非常容易使用,而且不使用图像加载器,它将很容易加载。

在android中,图像操作可能很难,我建议使用现有的库,例如Aquery也用于图像加载的库,下载Aquery jar并将其导入到您的项目中,然后尝试这种方法

 public class MainActivity extends Activity {

    private ImageView img;
    private AQuery aq;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        aq = new AQuery(this);
        img=(ImageView)findViewById(R.id.simpleLoadImg);
        aq.id(R.id.simpleLoadImg).image("http://sexocomcafe1-teste.tempsite.ws/imagensUsuario13/avata/Atra%C3%A7%C3%A3o%20PerigosaRJ_44690132.jpg",false,false);

    }


}


我想你也可以用。您还可以使用毕加索、UniversalImageLoader或类似的工具下载图像。我希望它能对您有所帮助。

您可以使用毕加索图书馆来显示图像。在build.gradle依赖项中添加此库:

compile 'com.squareup.picasso:picasso:2.4.0'
现在用这个来显示图像

File file = new File(imagePath);
 if(file.exists()) {
        Picasso.with(context).load(file).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView);
    } 

请记住在可绘图文件夹中保留图像的占位符。

使用通用图像加载程序库处理图像
File file = new File(imagePath);
 if(file.exists()) {
        Picasso.with(context).load(file).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView);
    }