当前位置: 首页 > 面试题库 >

在Android中设置ImageView

慕迪
2023-03-14
问题内容

我有一个JSON URL :: http://54.218.73.244:7006/DescriptionSortedRating/

JSON STRUCT ::

"restaurants": [
    {
      "restaurantID": 4,
      "restaurantNAME": "CopperChimney1",
      "restaurantIMAGE": "MarkBoulevard1.jpg",
      "restaurantDISTANCE": 15,
      "restaurantTYPE": "Indian",
      "restaurantRATING": 1,
      "restaurantPrice": 11,
      "restaurantTime": "9am t0 8pm"
    },

RestaurantDescPhotos.java

public class RestaurantDescPhotos extends Activity {
    // url to make request

    private static String url = "http://54.218.73.244:7006/DescriptionSortedRating/";

    String restaurant_name, cc_res;
    ProgressDialog progressDialog;
    JSONObject jsonObject;
    JSONArray first_array;
    TextView textView;
    TextView text;

    private SparseArray<String> imagesMap = new SparseArray<String>();

    ArrayList<HashMap<String, String>> list_of_images = new ArrayList<HashMap<String, String>>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.restaurant_desc_photos);

        progressDialog = new ProgressDialog(RestaurantDescPhotos.this);
        new ParsingAsync().execute();
    }

    private class ParsingAsync extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(RestaurantDescPhotos.this, "",
                    "Please Wait", true, false);

        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            String _response = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                httpclient.getParams().setParameter(
                        CoreProtocolPNames.PROTOCOL_VERSION,
                        HttpVersion.HTTP_1_1);



                HttpGet request = new HttpGet(url);
                HttpResponse response = httpclient.execute(request);
                HttpEntity resEntity = response.getEntity();
                _response = EntityUtils.toString(resEntity);

                jsonObject = new JSONObject(_response);
                first_array = jsonObject.getJSONArray("restaurants");

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            progressDialog.dismiss();

            // TextView timedisplay=(TextView)
            // findViewById(R.id.RestaurantTimeID);

            for (int i = 0; i < first_array.length(); i++) {
                try {
                    JSONObject detail_obj = first_array.getJSONObject(i);

                    HashMap<String, String> map_for_images = new HashMap<String, String>();

                    int id = detail_obj.getInt("_id");
                    String IMAGES = detail_obj.getString("restaurantIMAGE");

                    map_for_images.put("Starters", IMAGES);

                    list_of_images.add(map_for_images);


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


            ImageView imageView = (ImageView) findViewById(R.id.DISP_IMG);


        }
    }
}

RestaurantDescPhotos.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableRow
        android:id="@+id/tableRow6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="2sp" >
    </TableRow>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp" >
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp" >
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TableRow
            android:id="@+id/DescriptionTitleRow"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="2sp" >

            <HorizontalScrollView
                android:id="@+id/horizontalScrollView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="horizontal" >

                        <ImageView
                            android:id="@+id/DISP_IMG"
                            android:layout_width="167dp"
                            android:layout_height="167dp"
                            android:src="@drawable/ic_launcher" />
                    </LinearLayout>
                </LinearLayout>
            </HorizontalScrollView>
        </TableRow>
    </LinearLayout>

</LinearLayout>

ImageLoader.java

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.temp_img;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // Decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            // Recommended Size 512
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}
  • 我在XML中有一个imageview
  • 如何设置JSONURL的图像视图
  • 我已经编码了该类的某些部分,但是试图知道如何设置imageview

有任何想法吗


问题答案:

您可以使用ImageLoader设置图像…

创建像全局的ImageLoader实例。

  ImageLoader imageLoader;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
           ......
           imageLoader=new  ImageLoader(ClassName.this);


            ImageView imageView = (ImageView) findViewById(R.id.DISP_IMG);
           ......
            imageLoader.DisplayImage(YourImageURLHere,imageView);


 类似资料:
  • 问题内容: 我正在开发一个简单的应用程序,可以根据用户输入设置墙纸。我缺少设置墙纸的代码。我一直在徒劳的许多网站中寻找它。谁能张贴一个示例代码,将其设置为墙纸并保存在该文件夹中,作为墙纸? 问题答案: 适用于Android 1.5及更高版本

  • 我希望从服务器加载数据并显示到我的应用程序中(

  • 问题内容: 我想在更改背景之间的命令之间设置延迟。我尝试使用线程计时器,并尝试使用运行和捕获。但这不起作用。我试过了 但这只是变成黑色。 问题答案: 试试这个代码:

  • 问题内容: 我正在尝试使onClickListener在Spinner上触发,但是出现以下错误: Java.lang.RuntimeException是“不要为AdapterView调用setOnClickListener。您可能需要setOnItemClickListener,” 我确定我要调用onClickListener而不是onItemClickListener。我发现了其他人提出的问题,

  • 我一直在这里跟随这个教程: Android Studio-导入外部库/JAR

  • 我已经在中取消了这一行的注释,但是Proguard没有启用。 我的代码有什么问题/我遗漏了什么? 代码如下所示,请注意,我已经将该应用程序命名为ProGuard。 proguard-project.txt: