无法在Android的ImageView中显示具有所需尺寸的json图像

时间:2015-06-19 07:56:23

标签: android json image

我想以这种格式在Android的ImageView中显示图像。 enter image description here

我正在尝试从我在服务器上托管的json(通过网址)中读取我的图像。来自json的图像如下所示: - enter image description here

但是当我尝试从我的服务器(通过json)读取网址时,我的布局看起来像这样 enter image description here

如果我尝试从设备本地加载图像,我会得到所需的格式(此问题的第一张图片),但如果我尝试通过json的网址加载图像,我会收到缩小的图像。

这是我的json: -

{"events": [{
            "Name": "Chicken Manchuri",
            "Time": "30 mins",
            "Serves": "4",
            "ingredients": "http://i.dmtinc.cl/i/2015/06/19/salogo2ec23.png",
            "prize2": "Worth Rs.2000",
            "Description": "How do you decide whether or not to try a new recipe? Ohh yes, there are different ways to make your decision. You can decide based on your experience, say you tried something new at a restaurant or at a friend’s place, you liked it, so you want to try it. You heard one of your friends raving about a new recipe she tried and she strongly recommends you to try it. You visit blogs like this, see the pics, read the comments and make the decision. Sometimes  you read about something, but you’ve no idea what it is, you havent heard anybody recommending it, but you’ve a good feeling about it, so you give it a try. Phew, I’m exhausted explaining the decision making process!How do you decide whether or not to try a new recipe? Ohh yes, there are different ways to make your decision. You can decide based on your experience, say you tried something new at a restaurant or at a friend’s place, you liked it, so you want to try it. You heard one of your friends raving about a new recipe she tried and she strongly recommends you to try it. You visit blogs like this, see the pics, read the comments and make the decision. Sometimes  you read about something, but you’ve no idea what it is, you havent heard anybody recommending it, but you’ve a good feeling about it, so you give it a try. Phew, I’m exhausted explaining the decision making process!How do you decide whether or not to try a new recipe? Ohh yes, there are different ways to make your decision. You can decide based on your experience, say you tried something new at a restaurant or at a friend’s place, you liked it, so you want to try it. You heard one of your friends raving about a new recipe she tried and she strongly recommends you to try it. You visit blogs like this, see the pics, read the comments and make the decision. Sometimes  you read about something, but you’ve no idea what it is, you havent heard anybody recommending it, but you’ve a good feeling about it, so you give it a try. Phew, I’m exhausted explaining the decision making process!",
            "date": "Coming soon"
        },

            "Name": "Chicken Manchuri",
            "Time": "30 mins",
            "Serves": "4",
            "ingredients": "http://i.dmtinc.cl/i/2015/06/19/salogo2ec23.png",
            "prize2": "Worth Rs.2000",
            "Description": "How do you decide whether or not to try a new recipe? Ohh yes, there are different ways to make your decision. You can decide based on your experience, say you tried something new at a restaurant or at a friend’s place, you liked it, so you want to try it. You heard one of your friends raving about a new recipe she tried and she strongly recommends you to try it. You visit blogs like this, see the pics, read the comments and make the decision. Sometimes  you read about something, but you’ve no idea what it is, you havent heard anybody recommending it, but you’ve a good feeling about it, so you give it a try. Phew, I’m exhausted explaining the decision making process!",
            "date": "Coming soon"
        },
    {
            "Name": "Chicken Manchuri",
            "Time": "30 mins",
            "Serves": "4",
            "ingredients": "http://i.dmtinc.cl/i/2015/06/19/salogo2ec23.png",
            "prize2": "Worth Rs.2000",
            "Description": "How do you decide whether or not to try a new recipe? Ohh yes, there are different ways to make your decision. You can decide based on your experience, say you tried something new at a restaurant or at a friend’s place, you liked it, so you want to try it. You heard one of your friends raving about a new recipe she tried and she strongly recommends you to try it. You visit blogs like this, see the pics, read the comments and make the decision. Sometimes  you read about something, but you’ve no idea what it is, you havent heard anybody recommending it, but you’ve a good feeling about it, so you give it a try. Phew, I’m exhausted explaining the decision making process!",
            "date": "Coming soon"
        }

这是我的xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:background="#81345a"

    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <ImageView
        android:id="@+id/flag"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/rsz_maxresdefault" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#7000"
        android:orientation="vertical"
        android:paddingBottom="15dp"
        android:paddingTop="15dp" >

        <TextView
            android:id="@+id/rank"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:shadowColor="#000"
            android:shadowDx="3"
            android:shadowDy="3"
            android:shadowRadius="6"
            android:text="Styling Android"
            android:textColor="#FFF"
            android:textSize="36sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/country"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="A guide to applying styles and themes to Android apps"
            android:textColor="#CCC"
            android:textSize="12sp"/>
    </LinearLayout>
</RelativeLayout>

Json.java

public class MainActivity extends ActionBarActivity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String FLAG = "flag";

     static final String NAME = "Name";
     static final String TIME = "Time";
     static final String VENUE = "Serves";
     static final String ingredients = "ingredients";
     static final String PRIZE_MONEY2 = "prize2";
     static final String REGISTRATION_FEE = "date";
     static final String DESCRIPTION = "Description";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();


    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Android JSON Parse Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();

           /* TitanicTextView tv=(TitanicTextView)findViewById(R.id.titanic_tv);
            Titanic tt=new Titanic();
            tt.start(tv);*/
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("https://lit-hamlet-6856.herokuapp.com/eventsList/TECHNICAL");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("events");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("Name", jsonobject.getString("Name"));
                    map.put("Time", jsonobject.getString("Time"));
                    map.put("Serves", jsonobject.getString("Serves"));
                    map.put("ingredients", jsonobject.getString("ingredients"));
                    map.put("Description",jsonobject.getString("Description"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            //setContentView(R.layout.listview_main);
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

Imageloader.java

package com.example.hasan.jsoncountries;

/**
 * Created by hasan on 13/6/15.
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

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.ic_launcher;

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

}

我希望最终输出是这样的。

enter image description here 那么我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

尝试将此添加到您的ImageView:

android:scaleType="centerInside"
android:adjustViewBounds="true"

答案 1 :(得分:0)

scalType FIT_XY和一个大的imageview(高:X,宽度:wrap_content)将完成这项工作,但不是最好的解决方案。 X在dp中,您可以通过res / values / dimens.xml为其添加不同的值。

关于多维度: How can I specify different dimension of layout for different density

如果必须使用可能根据设备的密度类别而改变的不同DP值,则需要根据小,大,xlarge创建不同的尺寸文件 http://developer.android.com/guide/topics/resources/more-resources.html#Dimension

好的,我会尽我所能:首先我想从URL推荐这个库来进行ImageDownloading: http://square.github.io/picasso/ 它是一个写得很好的图书馆,我总是尽可能地使用它。