0

我们知道每个 YouTube 视频都有一张图片。我们可以使用 jsonc 文件获取该图像的来源。我编写了一个代码来获取该图像的来源,然后将其存储在一个字符串中,以便使用位图将其放入我的服装列表视图中的图像视图中。在解析中我没有问题我可以存储图像的来源。但是当我的服装视图显示时,图像并没有出现在其中。我被告知从网络获取图像是非常非常糟糕的事情,不要在 UI 线程上进行网络调用。我应该而且必须使用一些库来管理和缓存位图。我能做些什么来解决这个问题?

这是我从 jsonc 文件进行解析的主要活动:

import java.util.ArrayList;
import java.util.Collection;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;


import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {



    Button search; ; 
    TextView name ; 
    ListView listview ; 
    ArrayList<videos > videolist; 
    ArrayAdapter< videos > adapter ; 
    AlertDialog.Builder alert ; 
    ProgressDialog progressdialog ; 
    EditText name;

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

        videolist = new ArrayList<videos>(); 
        adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist); 
        name=(EditText) findViewById(R.id.editText1);
        alert = new Builder(this); 
        alert.setTitle("Warnning" ) ; 
        alert.setMessage("You want to connect to the internet ..? " ); 


        alert.setNegativeButton("No ", null); 
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                String username=name.getText().toString();
                            new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");   

            }
        });



        progressdialog = new ProgressDialog(this); 

        progressdialog.setMessage("Wait Loading .... "); 
        progressdialog.setCancelable(false); 





        search = (Button) findViewById(R.id.button1); 
        name = (TextView) findViewById(R.id.textView1); 

        listview = (ListView) findViewById(R.id.listView1); 

        listview.setAdapter(adapter); 


        search.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
            alert.show();   


            }
        });
    }

    class connection extends AsyncTask<String, Integer, String>{


        @Override
        protected void onPreExecute() {
             progressdialog.show(); 
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String... arg0) {

            String s = GetUrlBody(arg0[0]); 




            return s;
        }

        @Override
        protected void onPostExecute(String result) {

        try{

            JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();

        JSONObject feed = jo.optJSONObject("data");
        JSONArray entry = feed.optJSONArray("items");


        for(int i = 0 ; i<entry.length() ; i++){

        String title = entry.getJSONObject(i).getString("title");

        String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
        Log.d("after get image", "ok")
        String   url;
        try {
            url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
        } catch (JSONException ignore) {
            url = entry.getJSONObject(i).getJSONObject("player").getString("default");
        }

        String description = entry.getJSONObject(i).getString("description");
        Log.d("after get description", "ok");
        videos videoobject=new videos();
        videoobject.setDecscrption(description);
        videoobject.setImageurl(thumbURL);
        videoobject.setVediourl(url);
        videoobject.setVideoname(title);

        videolist.add(videoobject);
        }
        listview.setAdapter(new custome(MainActivity.this,videolist));
        Log.d("AFTER set custome ", "before notify changes");


        adapter.notifyDataSetChanged(); 

        }catch(Exception exception) {
            Log.d("exception ", "nock nock nock....");
            Log.e("json ", exception.getMessage()); 
        }

            progressdialog.dismiss(); 
            super.onPostExecute(result); 

        } 




        String GetUrlBody (String Url ){

            HttpClient client = new DefaultHttpClient(); 

            HttpGet gethttp = new HttpGet(Url); 

            try{
            HttpResponse response = client.execute(gethttp); 

            if(response.getStatusLine().getStatusCode() == 200){

                String save =
            EntityUtils.toString(response.getEntity(), HTTP.UTF_8); 

                return save; 

            }else {
                return "Not Found"; 
            }

            }catch(Exception exception){}




            return null; 
        }



    }


}

这是我的服装列表视图:

public class custome extends BaseAdapter {



    ArrayList<videos> data=new ArrayList<videos>();
    android.content.Context context1;
    android.widget.TextView name;
    ImageView  picture;

    public custome(Context context,ArrayList<videos>arrayList) {
        // TODO Auto-generated constructor stub
        context1=context;
       data= arrayList;
    }




    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return data.get(arg0);
    }

    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    public View getView(int arg0, View arg1, ViewGroup arg2) {
        View view=arg1;

        if(view==null)
        {   
            LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            view=layoutInflater.inflate(R.layout.listvideo,null); 
        }
        name=(TextView) view.findViewById(R.id.textView1);
        picture=(ImageView) view.findViewById(R.id.imageView1);

        videos video = data.get(arg0);
        name.setText(video.getVideoname());


        URL url = null;
        try {
            url = new URL(video.getImageurl());
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        picture.setImageBitmap(bitmap);





        return view;
    }

}
4

2 回答 2

2

我建议您使用 Thread 从网络下载图像并获取 InputStream 然后解析为 Bitmap。完整项目在这里: E4U 项目

import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }

      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
}   
于 2013-08-04T09:36:02.420 回答
1

从网上下载图像进行显示,可能需要缓存是许多人已经解决的一个非常常见的问题,我强烈建议您使用这些经过验证且有效的解决方案之一,而不是滚动和调试您自己的解决方案:

  1. Ion ( https://github.com/koush/ion ) - 非常灵活且功能齐全,而且它不仅可以下载图像,还可以下载 JSON、字符串、文件和 Java 类型。我真正喜欢的部分是它可以在调用 Activity 完成时自动取消操作,因此用户不会浪费时间和带宽下载将不再显示的图像
  2. 通用图像加载器https://github.com/nostra13/Android-Universal-Image-Loader) - 同样适用于大多数用例,但仅用于下载/缓存图像
于 2013-08-04T09:45:28.760 回答