Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.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的ImageView中显示具有所需维度的json图像_Android_Json_Image - Fatal编程技术网

无法在android的ImageView中显示具有所需维度的json图像

无法在android的ImageView中显示具有所需维度的json图像,android,json,image,Android,Json,Image,我想在android的ImageView中以这种格式显示图像。 我正在尝试从服务器上托管的json(通过url)读取我的图像。json中的图像如下所示:- 但是当我尝试从我的服务器(通过json)读取url时,我的布局如下所示 如果我尝试从设备本地加载图像,我会得到所需的格式(这个问题的第一个图像),但是如果我尝试通过json的url加载图像,我会得到一个缩小的图像 这是我的json:- {"events": [{ "Name": "Chicken Manchuri",

我想在android的ImageView中以这种格式显示图像。

我正在尝试从服务器上托管的json(通过url)读取我的图像。json中的图像如下所示:-

但是当我尝试从我的服务器(通过json)读取url时,我的布局如下所示

如果我尝试从设备本地加载图像,我会得到所需的格式(这个问题的第一个图像),但是如果我尝试通过json的url加载图像,我会得到一个缩小的图像

这是我的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();
        }
    }
}
公共类MainActivity扩展了ActionBarActivity{
//声明变量
JSONObject JSONObject;
JSONArray JSONArray;
列表视图列表视图;
ListViewAdapter适配器;
进程对话框;
ArrayList ArrayList;
静态字符串RANK=“RANK”;
静态字符串COUNTRY=“COUNTRY”;
静态字符串POPULATION=“POPULATION”;
静态字符串FLAG=“FLAG”;
静态最终字符串NAME=“NAME”;
静态最终字符串时间=“时间”;
静态最终字符串vention=“services”;
静态最终字符串成分=“成分”;
静态最终字符串奖\u MONEY2=“prize2”;
静态最终字符串注册\u FEE=“日期”;
静态最终字符串DESCRIPTION=“DESCRIPTION”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//从listview_main.xml获取视图
setContentView(R.layout.listview_main);
//执行下载JSON异步任务
新建下载JSON().execute();
}
//下载JSON异步任务
私有类下载JSON扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//创建一个progressdialog
mProgressDialog=新建ProgressDialog(MainActivity.this);
//设置进程对话框标题
setTitle(“Android JSON解析教程”);
//设置进程对话框消息
设置消息(“加载…”);
mProgressDialog.setUndeterminate(false);
//显示进度对话框
mProgressDialog.show();
/*TitanicTextView电视=(TitanicTextView)findViewById(R.id.titanic_电视);
泰坦尼克号tt=新泰坦尼克号();
tt.start(电视)*/
}
@凌驾
受保护的Void doInBackground(Void…参数){
//创建一个数组
arraylist=新的arraylist();
//从给定的URL地址检索JSON对象
jsonobject=JSONfunctions.getJSONfromURL(“https://lit-hamlet-6856.herokuapp.com/eventsList/TECHNICAL");
试一试{
//在JSON中找到数组名称
jsonarray=jsonobject.getJSONArray(“事件”);
for(int i=0;i
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();
    }

}
package com.example.hasan.jsoncountries;
/**
*哈桑于2015年6月13日创作。
*/
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.Collections;
导入java.util.Map;
导入java.util.WeakHashMap;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Executors;
导入android.os.Handler;
导入android.content.Context;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.widget.ImageView;
公共类图像加载器{
MemoryCache MemoryCache=新的MemoryCache();
文件缓存文件缓存;
private Map ImageView=Collections.synchronizedMap(新的WeakHashMap());
执行服务执行服务;
//在UI线程中显示图像的处理程序
Handler=newhandler();
公共图像加载器(上下文){
fileCache=新的fileCache(上下文);
executorService=Executors.newFixedThreadPool(5);
}
最终int stub_id=R.drawable.ic_启动器;
public void DisplayImage(字符串url,ImageView){
put(imageView,url);
位图位图=memoryCache.get(url);
if(位图!=null)
设置图像位图(位图);
否则{
队列照片(url、imageView);
setImageResource(存根id);
}
}
私有void队列照片(字符串url,ImageView){
光电负载p=新的Pho
android:scaleType="centerInside"
android:adjustViewBounds="true"