我从电影数据库API中获取数据,有时图像不会加载,有时会加载缓慢。我正在将图像url解码为位图,然后使用适配器将它们设置为图像视图。请告诉我哪里出错。我正在从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];
}
答案 0 :(得分:0)
您正在使用InputStreamReader,我认为这不是必需的,这也可能是它变慢的原因。我不能将此作为评论发布,因此我必须将其作为答案发布。
尝试使用doInBackground代码而不是使用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;
}
}
您需要导入此类
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;
答案 1 :(得分:0)
使用Glide或Picasso等图书馆。
@Override
public void onBindViewHolder(Holder holder, int position) {
// holder.imageView.setImageBitmap(Data.bImage[position]);
Glide.with(ctx)
.load(imageDownloadUrl)
.into(holder.imageView);
Picasso.with(context).load("").placeholder(Data.bImage[position]).into(holder.imageView);
or
//R.drawable.drawableName
Picasso.with(context).load(Data.bImage[position]).into(holder.imageView);
}
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.android.support:support-v4:25.1.0'