本文介绍了从远程URL下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在开发包含其中显示YouTube视频链接列表视图中的Andr​​oid应用程序。该应用程序从服务器作为JSON中获取数据。现在,我想为这些视频从这个子域显示缩略图 - http://img.youtube.com/vi/

但图像没有在列表视图中显示出来。

下面是code项目:

1 - canticlesActivity.java

 包com.shadatv.shada;进口的java.io.File;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.net.HttpURLConnection中;
进口的java.net.URL;
进口的java.util.ArrayList;
进口的java.util.HashMap;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.util.EntityUtils;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.ListActivity;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.os.Environment;
进口android.util.Log;
进口android.widget.ListAdapter;
进口android.widget.SimpleAdapter;
进口android.widget.TextView;
进口android.widget.Toast;公共类canticlesActivity扩展ListActivity {    TextView的httpStuff;
    HttpClient的客户端;
    JSONArray canticles;
    字符串picpath =htt​​p://img.youtube.com/vi/;    文件SD卡= Environment.getExternalStorageDirectory();    文件shadaRoot =新的文件(sdcard.getAbsolutePath()+/ shada_Folder);    私有静态最后弦乐CA_NAME =CA_NAME;
    私有静态最后弦乐CA_LINK =ca_link;
    私有静态最后弦乐CA_IMG =ca_img;
    私有静态最终字符串URL =htt​​p://dt-works.com/ags/shadatv/canticles/android_data;    ArrayList的<&HashMap的LT;字符串,字符串>> canticlesList;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.canticles);        httpStuff =(的TextView)findViewById(R.id.textView1);
        客户端=新DefaultHttpClient();
        新阅读()执行();
    }    公共JSONArray allCanticles()抛出ClientProtocolException,IOException异常,JSONException {
        StringBuilder的URL =新的StringBuilder(URL);        HTTPGET GET =新HTTPGET(url.toString());
        HTT presponse R = client.execute(获取);
        。INT状态= r.getStatusLine()的getStatus code();        如果(状态== 200){
            HttpEntity E = r.getEntity();
            字符串数据= EntityUtils.toString(E);
            JSONArray canticles =新JSONArray(数据);
            返回canticles;        }其他{
            Toast.makeText(getBaseContext(),错误,Toast.LENGTH_SHORT).show();
            返回null;
        }
    }    公共无效downloadImage(字符串fileURL){
        尝试{
// Toast.makeText(getBaseContext(),baaad,Toast.LENGTH_SHORT).show();
            串finlpth =;
            finlpth = picpath + fileURL +/2.jpg
            shadaRoot.mkdirs();            URL U =新的URL(finlpth);
            HttpURLConnection的C =(HttpURLConnection类)u.openConnection();
            c.setRequestMethod(GET);
            c.setDoOutput(真);
            c.connect();            文件DownloadedFile =新的文件(shadaRoot,fileURL +.JPG);
            //如果(!outfile.exists())
            FileOutputStream中F =新的FileOutputStream(DownloadedFile);            在的InputStream = c.getInputStream();            字节[]缓冲区=新的字节[1024];
            INT LEN1 = 0;
            而((LEN1 = in.read(缓冲液))大于0){
                f.write(缓冲液,0,LEN1);
            }            f.close();        }赶上(例外五){
            Log.d(下载,e.getMessage());
        }
    }    公共类读取扩展的AsyncTask<字符串,字符串,字符串> {        @覆盖
        保护字符串doInBackground(字符串... PARAMS){            canticlesList =新的ArrayList<&HashMap的LT;字符串,字符串>>();
            尝试{
                canticles = allCanticles();
                的for(int i = 0; I< canticles.length();我++){
                    JSONObject的颂歌= canticles.getJSONObject(I)
                    字符串CA_NAME = canticle.getString(CA_NAME);
                    字符串ca_link = canticle.getString(CA_LINK);                    downloadImage(ca_link);                    HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                    map.put(CA_NAME,CA_NAME);
                    map.put(CA_LINK,ca_link);
                    map.put(CA_IMG,ca_link +.JPG);
                    canticlesList.add(地图);
                }            }赶上(ClientProtocolException E){
                e.printStackTrace();
            }赶上(IOException异常五){
                e.printStackTrace();
            }赶上(JSONException E){
                e.printStackTrace();
            }
            返回null;
        }        @覆盖
        保护无效onPostExecute(字符串结果){            ListAdapter适配器=新SimpleAdapter(canticlesActivity.this,
                                                    canticlesList,R.layout.list_item,
                                                    新的String [] {CA_NAME,CA_LINK,CA_IMG},
                                                    新的INT [] {R.id.ca_name,R.id.ca_link,R.id.ca_img});
            setListAdapter(适配器);        }
    }
}

2 - list_item.xml

 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:背景=@绘制/ list_selector
    机器人:方向=横向>    <! - 产品ID(PID) - 会被隐藏 - 用于传递给其他活动 - >    < ImageView的
        机器人:ID =@ + ID / ca_img
        机器人:layout_width =50dip
        机器人:layout_height =50dip
        机器人:contentDescription =@字符串/ DESC
         />    <的TextView
        机器人:ID =@ + ID / CA_NAME
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
         />    <! - 名称标签 - >
    <的TextView
        机器人:ID =@ + ID / ca_link
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:paddingTop =6DIP
        机器人:paddingLeft =6DIP
        机器人:TEXTSIZE =17sp
        机器人:文字样式=大胆
        机器人:知名度=水涨船高/>< / LinearLayout中>


解决方案

您可以使用
它使用非常简单 - imageLoader.displayImage(imageUri,ImageView的);

Currently I am developing an Android app containing a list view which displays links for Youtube videos. The application gets its data from the server as JSON. Now I am trying to display thumbnails for these video from this subdomain - http://img.youtube.com/vi/.

But the images don't show up in the list view.

Here is the code for the project :

1 - canticlesActivity.java

package com.shadatv.shada;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class canticlesActivity extends ListActivity {

    TextView httpStuff;
    HttpClient client;
    JSONArray canticles;
    String picpath = "http://img.youtube.com/vi/";

    File sdcard = Environment.getExternalStorageDirectory();

    File shadaRoot = new File(sdcard.getAbsolutePath() + "/shada_Folder");

    private static final String CA_NAME = "ca_name";
    private static final String CA_LINK = "ca_link";
    private static final String CA_IMG = "ca_img";
    private static final String URL = "http://dt-works.com/ags/shadatv/canticles/android_data";

    ArrayList<HashMap<String, String>> canticlesList;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.canticles);

        httpStuff = (TextView) findViewById(R.id.textView1);
        client = new DefaultHttpClient();
        new Read().execute();
    }

    public JSONArray allCanticles() throws ClientProtocolException, IOException, JSONException {
        StringBuilder url = new StringBuilder(URL);

        HttpGet get = new HttpGet(url.toString());
        HttpResponse r = client.execute(get);
        int status = r.getStatusLine().getStatusCode();

        if (status == 200) {
            HttpEntity e = r.getEntity();
            String data = EntityUtils.toString(e);
            JSONArray canticles = new JSONArray(data);
            return canticles;

        } else {
            Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    public void downloadImage(String fileURL) {
        try {
//          Toast.makeText(getBaseContext(), "baaad", Toast.LENGTH_SHORT).show();
            String finlpth = "";
            finlpth = picpath + fileURL + "/2.jpg";
            shadaRoot.mkdirs();

            URL u = new URL(finlpth);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            File DownloadedFile = new File(shadaRoot, fileURL + ".jpg");
            // if(!outfile.exists())
            FileOutputStream f = new FileOutputStream(DownloadedFile);

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }

            f.close();

        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }
    }

    public class Read extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... params) {

            canticlesList = new ArrayList<HashMap<String, String>>();
            try {
                canticles = allCanticles();
                for (int i = 0; i < canticles.length(); i++) {
                    JSONObject canticle = canticles.getJSONObject(i);
                    String ca_name = canticle.getString(CA_NAME);
                    String ca_link = canticle.getString(CA_LINK);

                    downloadImage(ca_link);

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(CA_NAME, ca_name);
                    map.put(CA_LINK, ca_link);
                    map.put(CA_IMG, ca_link + ".jpg");
                    canticlesList.add(map);
                }

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

        @Override
        protected void onPostExecute(String result) {

            ListAdapter adapter = new SimpleAdapter(canticlesActivity.this,
                                                    canticlesList,R.layout.list_item,
                                                    new String[] {CA_NAME, CA_LINK, CA_IMG},
                                                    new int[] {R.id.ca_name, R.id.ca_link, R.id.ca_img});
            setListAdapter(adapter);

        }
    }
}

2 - list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:orientation="horizontal" >

    <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->

    <ImageView
        android:id="@+id/ca_img"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:contentDescription="@string/desc"
         />

    <TextView
        android:id="@+id/ca_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         />

    <!-- Name Label -->
    <TextView
        android:id="@+id/ca_link"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="17sp"
        android:textStyle="bold"
        android:visibility="gone" />

</LinearLayout>
解决方案

You can use UniversalImageLoaderit very simple for using -imageLoader.displayImage(imageUri, imageView);

这篇关于从远程URL下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:35