图片载入速度很慢 [英] Images loading very slowly
问题描述
我从电影数据库API获取的数据和图像,有时不加载,有时加载缓慢。我解码图像的URL位图,然后用adapter.Please告诉我在哪里弄错使我得到的图像的URL直接从API将它们设置为图像视图。
MainActivity.java:
包com.example.sahilshokeen.movie;公共类MainActivity延伸活动{
私人RecyclerView recyclerView;
私人GridLayoutManager经理;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
//检查网络
ConnectivityManager connMgr =(ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
的NetworkInfo NETWORKINFO = connMgr.getActiveNetworkInfo();
如果(NETWORKINFO = NULL&放大器;!&安培; networkInfo.isConnected()){
//获取数据
新FetchData()执行();
新的转换()执行();
}其他{
//显示错误
吐司面包= Toast.makeText(这一点,没有网络,Toast.LENGTH_LONG);
toast.show();
}
//设置适配器
recyclerView =(RecyclerView)findViewById(R.id.recyclers);
经理=新GridLayoutManager(MainActivity.this,2);
recyclerView.setAdapter(新适配器());
recyclerView.setHasFixedSize(真);
recyclerView.setLayoutManager(经理);
}公共类FetchData扩展的AsyncTask<太虚,太虚,太虚> {
私人HttpURLConnection的连接= NULL;
私人BufferedReader中读者= NULL;
私人JSON字符串;
私人字符串urlString = \"http://api.themoviedb.org/3/movie/popular?api_key=b6f6fcfbb225d8c500e4404655ccadcc&certification=G\";
私人字符串形象=http://image.tmdb.org/t/p/w92/; @覆盖
保护无效doInBackground(虚空...... PARAMS){
//连接到网络
尝试{
网址URL =新的URL(urlString);
连接=(HttpURLConnection类)url.openConnection();
connection.setRequestMethod(GET);
connection.connect();
StringBuffer的缓冲区=新的StringBuffer();
InputStream的流= connection.getInputStream();
读者=新的BufferedReader(新的InputStreamReader(流));
串线;
而((行= reader.readLine())!= NULL){
buffer.append(线);
}
JSON = buffer.toString();
//获取JSON数据
尝试{
的JSONObject对象=新的JSONObject(JSON);
JSONArray阵列= object.getJSONArray(结果);
的for(int i = 0;我6;;我++){
Data.objects [I] = array.getJSONObject(ⅰ);
Data.title [I] = Data.objects [I] .getString(ORIGINAL_TITLE);
Data.overview [I] = Data.objects [I] .getString(概览);
Data.date [I] = Data.objects [I] .getString(RELEASE_DATE);
Data.image [I] = Data.objects [I] .getString(poster_path);
Data.vote [I] = Data.objects [I] .getDouble(vote_average);
Data.image [I] =图像+ Data.image [I]
}
}赶上(JSONException E){
e.printStackTrace();
}
}赶上(例外五){
e.printStackTrace();
} {最后
connection.disconnect();
}
尝试{
如果(读者!= NULL){
reader.close();
}
}赶上(IOException异常五){
e.printStackTrace();
}
返回null;
}}公共类转换扩展的AsyncTask<太虚,太虚,太虚> { @覆盖
保护无效doInBackground(虚空...... PARAMS){
的for(int i = 0;我6;;我++){
尝试{
网址URL =新的URL(Data.image [I]);
HttpURLConnection的连接=(HttpURLConnection类)url.openConnection();
connection.setDoInput(真);
connection.connect();
输入的InputStream = connection.getInputStream();
位图MYBITMAP = BitmapFactory.de codeStream(输入);
Data.bImage [I] = MYBITMAP;
}赶上(IOException异常五){
e.printStackTrace();
}
}
返回null;
}} @覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.menu_main,菜单);
返回true;
} @覆盖
公共布尔onOptionsItemSelected(菜单项项){
//处理动作栏项目点击这里。操作栏会
//自动处理上点击主页/向上按钮,只要
//你在AndroidManifest.xml中指定一个父活动。
INT ID = item.getItemId(); // noinspection SimplifiableIfStatement
如果(ID == R.id.action_settings){
返回true;
}
如果(ID == R.id.action_refresh){ 返回true;
} 返回super.onOptionsItemSelected(项目);
}
}
Adapter.java:
包com.example.sahilshokeen.movie;公共类适配器扩展RecyclerView.Adapter< Adapter.Holder> {公共静态类持有人扩展RecyclerView.ViewHolder {
公共CardView cardView;
公共ImageView的ImageView的; 公众持有人(查看ItemView控件){
超(ItemView控件);
cardView =(CardView)itemView.findViewById(R.id.card);
ImageView的=(ImageView的)itemView.findViewById(R.id.images);
}
}@覆盖
公众持有人onCreateViewHolder(ViewGroup中的父母,INT viewType){
查看查看= LayoutInflater.from(parent.getContext())膨胀(R.layout.grid_item,父母,假的)。
持有人持有人=新的持有人(视图);
回到持有人;
}@覆盖
公共无效onBindViewHolder(持有人持有人,INT位置){
holder.imageView.setImageBitmap(Data.bImage [位置]);
}@覆盖
公共无效onAttachedToRecyclerView(RecyclerView recyclerView){
super.onAttachedToRecyclerView(recyclerView);
}@覆盖
公众诠释getItemCount(){
返回Data.bImage.length;
} }
Data.java:
包com.example.sahilshokeen.movie;公共类数据{
公共静态的JSONObject []对象=新的JSONObject [6];
公共静态的String []标题=新的String [6];
公共静态的String [] =概述新的String [6];
公共静态的String [] =日期新的String [6];
公共静态的String [] =影像新的String [6];
公共静态位图[] = bImage新的位图[6];
公共静态双[] =投新双[6];
}
您正在使用InputStreamReader的,我认为是没有必要的,它可能也可以解释为什么它是缓慢的原因。所以我要出任答案,我不能发表这是一个注释。
试试这个code为doInBackground而不是使用InputStreamReader中的。
//调用你的方法
新FetchData().execute(\"http://api.themoviedb.org/3/movie/popular?api_key=b6f6fcfbb225d8c500e4404655ccadcc&certification=G\");
公共类FetchData扩展的AsyncTask<弦乐,太虚,太虚> { @覆盖
保护布尔doInBackground(字符串的URL ...){
尝试{
的HttpParams httpParameters =新BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,5000);
HttpConnectionParams.setSoTimeout(httpParameters,5000); // ------------------>>
HTTPGET httppost =新HTTPGET(网址[0]);
HttpClient的HttpClient的=新DefaultHttpClient(httpParameters);
HTT presponse响应= httpclient.execute(httppost); //状态行STAT = response.getStatusLine();
。INT状态= response.getStatusLine()的getStatus code(); 如果(状态== 200){
HttpEntity实体= response.getEntity();
字符串数据= EntityUtils.toString(实体);
JSONObject的jsono =新的JSONObject(数据);
JSONArray jarray = jsono.getJSONArray(结果); 的for(int i = 0; I< jarray.length();我++){
的JSONObject对象= jarray.getJSONObject(I) //获取你的数据在这里举例:poster_path
object.getString(poster_path); } 返回true;
} // ------------------>> }赶上(ConnectTimeoutException E){
Log.e(超时异常:e.toString());
}赶上(SocketTimeoutException STE){
Log.e(超时异常:ste.toString());
}赶上(ParseException的E1){
e1.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
}赶上(JSONException E){
e.printStackTrace();
}
返回false;
}
}
和需要导入这个类
进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.conn.ConnectTimeoutException;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.params.BasicHttpParams;
进口org.apache.http.params.HttpConnectionParams;
进口org.apache.http.params.HttpParams;
进口org.apache.http.util.EntityUtils;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口java.io.IOException异常;
进口java.net.SocketTimeoutException;
进口的java.util.ArrayList;
I am fetching data from movie database API and sometimes images do not load and sometimes it loads slowly. I am decoding images url to bitmap and then setting them to image view using adapter.Please tell where i am making mistake.I am getting images url right from API. MainActivity.java:
package com.example.sahilshokeen.movie;
public class MainActivity extends Activity {
private RecyclerView recyclerView;
private GridLayoutManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//checking network
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
new FetchData().execute();
new Convert().execute();
} else {
// display error
Toast toast = Toast.makeText(this, "No Network", Toast.LENGTH_LONG);
toast.show();
}
//setting adapter
recyclerView = (RecyclerView) findViewById(R.id.recyclers);
manager = new GridLayoutManager(MainActivity.this, 2);
recyclerView.setAdapter(new Adapter());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(manager);
}
public class FetchData extends AsyncTask<Void, Void, Void> {
private HttpURLConnection connection = null;
private BufferedReader reader = null;
private String json;
private String urlString = "http://api.themoviedb.org/3/movie/popular?api_key=b6f6fcfbb225d8c500e4404655ccadcc&certification=G";
private String image = " http://image.tmdb.org/t/p/w92/";
@Override
protected Void doInBackground(Void... params) {
//connecting to network
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
StringBuffer buffer = new StringBuffer();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
json = buffer.toString();
//getting json data
try {
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
for (int i = 0; i < 6; i++) {
Data.objects[i] = array.getJSONObject(i);
Data.title[i] = Data.objects[i].getString("original_title");
Data.overview[i] = Data.objects[i].getString("overview");
Data.date[i] = Data.objects[i].getString("release_date");
Data.image[i] = Data.objects[i].getString("poster_path");
Data.vote[i] = Data.objects[i].getDouble("vote_average");
Data.image[i] = image + Data.image[i];
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class Convert extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
for(int i=0;i<6;i++) {
try {
URL url = new URL(Data.image[i]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Data.bImage[i] = myBitmap;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_refresh) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter.java:
package com.example.sahilshokeen.movie;
public class Adapter extends RecyclerView.Adapter<Adapter.Holder> {
public static class Holder extends RecyclerView.ViewHolder {
public CardView cardView;
public ImageView imageView;
public Holder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.card);
imageView = (ImageView) itemView.findViewById(R.id.images);
}
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
Holder holder = new Holder(view);
return holder;
}
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.imageView.setImageBitmap(Data.bImage[position]);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
return Data.bImage.length;
}
}
Data.java:
package com.example.sahilshokeen.movie;
public class Data {
public static JSONObject[] objects = new JSONObject[6];
public static String[] title = new String[6];
public static String[] overview = new String[6];
public static String[] date = new String[6];
public static String[] image = new String[6];
public static Bitmap[] bImage = new Bitmap[6];
public static Double[] vote = new Double[6];
}
You are using InputStreamReader, which i think isn't necessary, It may as well be the reason why it is slow. I can't post this as a comment so I have to post as answer.
Try this code for doInBackground instead of using InputStreamReader.
//Call your method
new FetchData().execute("http://api.themoviedb.org/3/movie/popular?api_key=b6f6fcfbb225d8c500e4404655ccadcc&certification=G");
public class FetchData extends AsyncTask<String, Void, Void> {
@Override
protected Boolean doInBackground(String... urls) {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
//Get your data here Example : poster_path
object.getString("poster_path");
}
return true;
}
//------------------>>
} catch (ConnectTimeoutException e) {
Log.e("Timeout Exception: ", e.toString());
} catch (SocketTimeoutException ste) {
Log.e("Timeout Exception: ", ste.toString());
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
And you need to import this classes
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
这篇关于图片载入速度很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!