Java 毕加索在listview中向上滚动时不断重新加载图像,加载速度较慢
我一直在寻找答案,但无法从之前的讨论中找出我的问题。我有一个listview,它加载了大约50个图像(以前大约是100个,但这几乎没有加载任何图像)。在通过适配器从api端点获取JSON内容(包括图像URL)后,我的代码将其放入listview中 目前,有50幅图像,毕加索将在我向下滚动提要时一次加载一幅图像。我觉得如果将滚动条固定在listview中的一个项目上,会使图像加载更快。但是,当我向上滚动时,它会将占位符放回并重新加载图像。有没有办法解决这个问题Java 毕加索在listview中向上滚动时不断重新加载图像,加载速度较慢,java,android,picasso,Java,Android,Picasso,我一直在寻找答案,但无法从之前的讨论中找出我的问题。我有一个listview,它加载了大约50个图像(以前大约是100个,但这几乎没有加载任何图像)。在通过适配器从api端点获取JSON内容(包括图像URL)后,我的代码将其放入listview中 目前,有50幅图像,毕加索将在我向下滚动提要时一次加载一幅图像。我觉得如果将滚动条固定在listview中的一个项目上,会使图像加载更快。但是,当我向上滚动时,它会将占位符放回并重新加载图像。有没有办法解决这个问题 public class MainA
public class MainActivity extends Activity {
private List<Post> myPosts = new ArrayList<Post>();
protected String[] mBlogPostTitles;
public static final String TAG = MainActivity.class.getSimpleName();//prints name of class without package name
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkAvailable()) {
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask(); // new thread
getBlogPostsTask.execute();// don't call do in background directly
}else{
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void populateListView() {
ArrayAdapter<Post> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.postsListView);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Post>{
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, myPosts);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// make sure we have a view to work with
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent,false);
}
//find the post to work with
Post currentPost = myPosts.get(position);
Context context = itemView.getContext();
String imageURL = currentPost.getImage();
if(imageURL == null || imageURL.isEmpty()){
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_image);
imageView.setVisibility(View.GONE);
}else{
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_image);
Picasso.with(context)
.load(imageURL)
.tag(context)
.placeholder(R.drawable.kanye8080s)
.error(R.drawable.stadiumarcadium)
.into(imageView);
imageView.setVisibility(View.VISIBLE);
}
//Username
TextView userText = (TextView) itemView.findViewById(R.id.item_txtUser);
userText.setText(currentPost.getUser());
//Time of post
TextView timeText = (TextView) itemView.findViewById(R.id.item_txtTime);
timeText.setText("" + currentPost.getTime());
//The actual post
TextView postText = (TextView) itemView.findViewById(R.id.item_txtPost);
postText.setText("" + currentPost.getPost());
//The actual post
TextView likesText = (TextView) itemView.findViewById(R.id.item_txtLikes);
likesText.setText("" + currentPost.getLikes());
return itemView;
}
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, List> {
@Override
protected List doInBackground(Object[] params) {
int responseCode = -1;//need to have this variable outside scope of try/catch block
JSONObject jsonResponse = null;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(""); /// api endpoint redacted
try {
HttpResponse response = client.execute(httpget);
StatusLine statusLine = response.getStatusLine();
responseCode = statusLine.getStatusCode();
if(responseCode == HttpURLConnection.HTTP_OK){ //could have used just 200 value
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while((line = reader.readLine()) != null){
builder.append(line);
}
jsonResponse = new JSONObject(builder.toString());
JSONArray jsonPosts = jsonResponse.getJSONArray("posts");
for(int i=0; i < jsonPosts.length(); i++ ){
JSONObject jsonPost = jsonPosts.getJSONObject(i);
int post_id = Integer.parseInt(jsonPost.getString("id"));
String post_user = jsonPost.getString("user");
String post_account = jsonPost.getString("account");
int post_time = Integer.parseInt(jsonPost.getString("time"));
String post_post = jsonPost.getString("post");
String post_image = jsonPost.getString("image");
int post_likes = Integer.parseInt(jsonPost.getString("likes"));
myPosts.add(new Post(post_id, post_user, post_account, post_time, post_post, post_image, "profile picture here", post_likes));
}
}else{
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(TAG, "Exception caught");
}
catch (IOException e){
Log.e(TAG, "Exception caught");
}
catch (Exception e){//must be in this order, this is the last, general catch
Log.e(TAG, "Exception caught", e);
}
return null;
}
@Override
protected void onPostExecute(List result) {
// call populateListView method here
populateListView();
super.onPostExecute(result);
}
}
@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;
}
return super.onOptionsItemSelected(item);
}
}
公共类MainActivity扩展活动{
private List myPosts=new ArrayList();
受保护字符串[]mBlogPostTitles;
public static final String TAG=MainActivity.class.getSimpleName();//打印不带包名的类名
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkAvailable()){
GetBlogPostsTask GetBlogPostsTask=new GetBlogPostsTask();//新线程
getBlogPostsTask.execute();//不要直接在后台调用do
}否则{
Toast.makeText(此“网络不可用”,Toast.LENGTH_LONG.show();
}
}
公共布尔值isNetworkAvailable(){
ConnectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=manager.getActiveNetworkInfo();
布尔值isAvailable=false;
if(networkInfo!=null&&networkInfo.isConnected()){
isAvailable=真;
}
可获得的回报;
}
私有void populateListView(){
ArrayAdapter=新的MyListAdapter();
ListView列表=(ListView)findViewById(R.id.postsListView);
list.setAdapter(适配器);
}
私有类MyListAdapter扩展了ArrayAdapter{
公共MyListAdapter(){
超级(MainActivity.this、R.layout.item_视图、myPosts);
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
//确保我们有一个合作的视角
视图项视图=转换视图;
如果(itemView==null){
itemView=GetLayoutFlater()。充气(R.layout.item_视图,父视图,false);
}
//找到要与之合作的帖子
Post currentPost=myPosts.get(位置);
Context=itemView.getContext();
字符串imageURL=currentPost.getImage();
if(imageURL==null | | imageURL.isEmpty()){
ImageView ImageView=(ImageView)itemView.findViewById(R.id.item_image);
设置可见性(View.GONE);
}否则{
ImageView ImageView=(ImageView)itemView.findViewById(R.id.item_image);
毕加索。与(上下文)
.load(图像URL)
.tag(上下文)
.占位符(R.drawable.Kanye808080s)
.错误(R.可绘制的.葡萄球菌)
.进入(图像视图);
设置可见性(View.VISIBLE);
}
//用户名
TextView userText=(TextView)itemView.findViewById(R.id.item\u txtUser);
userText.setText(currentPost.getUser());
//投递时间
TextView timeText=(TextView)itemView.findViewById(R.id.item\u txtTime);
timeText.setText(“+currentPost.getTime());
//实际职位
TextView postText=(TextView)itemView.findViewById(R.id.item\u txtPost);
postText.setText(“+currentPost.getPost());
//实际职位
TextView likeText=(TextView)itemView.findViewById(R.id.item_txtLikes);
likeText.setText(“+currentPost.getLikes());
返回项目视图;
}
}
私有类GetBlogPostsTask扩展异步任务{
@凌驾
受保护列表doInBackground(对象[]参数){
int responseCode=-1;//需要将此变量置于try/catch块的作用域之外
JSONObject jsonResponse=null;
StringBuilder=新的StringBuilder();
HttpClient=new DefaultHttpClient();
HttpGet HttpGet=新HttpGet(“”;///api端点已编辑
试一试{
HttpResponse response=client.execute(httpget);
StatusLine StatusLine=response.getStatusLine();
responseCode=statusLine.getStatusCode();
如果(responseCode==HttpURLConnection.HTTP_OK){//可能只使用了200个值
HttpEntity=response.getEntity();
InputStream内容=entity.getContent();
BufferedReader=新的BufferedReader(新的InputStreamReader(内容));
弦线;
而((line=reader.readLine())!=null){
builder.append(行);
}
jsonResponse=newJSONObject(builder.toString());
JSONArray jsonPosts=jsonResponse.getJSONArray(“posts”);
for(int i=0;ipublic class MainActivity extends Activity {
private List<Post> myPosts = new ArrayList<Post>();
protected String[] mBlogPostTitles;
public static final String TAG = MainActivity.class.getSimpleName();//prints name of class without package name
...
private void populateListView() {
Activity activity = MainActivity.this;
ArrayAdapter<Post> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.postsListView);
list.setAdapter(adapter);
list.setOnScrollListener(new SampleScrollListener(activity));
}
private class MyListAdapter extends ArrayAdapter<Post>{
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, myPosts);
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
String imageURL = myPosts.get(position).getImage();
if(imageURL == null || imageURL.isEmpty()){
return 1; // text based
}else{
return 0; // image based
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PostViewHolder holder;
int type = getItemViewType(position);
View itemView = convertView;
// make sure we have a view to work with
if (itemView == null) {
holder = new PostViewHolder();
if(type == 1) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
} else {
itemView = getLayoutInflater().inflate(R.layout.image_post_view, parent, false);
holder.image = (ImageView) itemView.findViewById(R.id.item_image);
}
holder.user = (TextView) itemView.findViewById(R.id.item_txtUser);
holder.time = (TextView) itemView.findViewById(R.id.item_txtTime);
holder.post = (TextView) itemView.findViewById(R.id.item_txtPost);
holder.likes = (TextView) itemView.findViewById(R.id.item_txtLikes);
itemView.setTag(holder);
} else {
holder = (PostViewHolder) itemView.getTag();
}
//find the post to work with
Post currentPost = myPosts.get(position);
if(type != 1) {
Context context = itemView.getContext();
String imageURL = currentPost.getImage();
Picasso.with(context).setIndicatorsEnabled(true);
//Picasso.with(context).setLoggingEnabled(true);
Picasso.with(context)
.load(imageURL)
.tag(context)
.placeholder(R.drawable.kanye8080s)
//.skipMemoryCache()
.error(R.drawable.stadiumarcadium)
.fit()
.into(holder.image);
}
//Username
holder.user.setText(currentPost.getUser());
//Time of post
holder.time.setText("" + currentPost.getTime());
//The actual post
holder.post.setText(currentPost.getPost());
//Likes for the post
holder.likes.setText("" + currentPost.getLikes());
return itemView;
}
}
public class SampleScrollListener implements AbsListView.OnScrollListener {
private final Context context;
public SampleScrollListener(Context context) {
this.context = context;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
final Picasso picasso = Picasso.with(context);
if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_TOUCH_SCROLL) {
picasso.resumeTag(context);
} else {
picasso.pauseTag(context);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
// Do nothing.
}
}
...
}
Picasso.with(context)
.load(imageURL)
.tag(context)
.placeholder(R.drawable.kanye8080s)
.error(R.drawable.stadiumarcadium)
.into(imageView)
.resize(x,y);
recyclerview.getRecycledViewPool().setMaxRecycledViews(0, 0);