我在Android中创建了一个JSON Feed Reader。作品。但是,缩略图,图像更改是在屏幕滚动之后。
“齐心协力推进”
更新了代码。插入Custom ListAdapter。 - >
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(newsItem.getTitle());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachments());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
/////////////////////////////////////////////// ///////////////////////
MY FeedListActivity - &gt;
public class FeedListActivity extends Activity {
private ArrayList<FeedItem> feedList = null;
private ProgressBar progressbar = null;
private ListView feedListView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts_list);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
String url = "MY_URL_IN_JSON";
new DownloadFilesTask().execute(url);
}
/*
public void lol() { VER SINAL DE INTERNET
boolean redeOK = AndroidUtil.verificaInternet(this);
if (redeOK) {
//AndroidUtil.alertDialog(this, "Conexão encontrada");
Toast.makeText(this, "Sinal encontrado", Toast.LENGTH_LONG).show();
} else {
//AndroidUtil.alertDialog(this, "Conexão não encontrada");
Toast.makeText(this, "Sinal não encontrado", Toast.LENGTH_LONG).show();
finish();
}
}*/
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
feedListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
FeedItem newsData = (FeedItem) o;
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
AsyncTask使您可以实现MultiThreading,而不会弄脏线程。 AsyncTask可以正确,方便地使用UI线程。它允许执行后台操作并在UI线程上传递结果。如果我们正在做与UI相关的隔离事务,例如下载数据并准备列表,则建议使用AsyncTask。
private class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
@Override
protected void onPostExecute(Void result) {
if (null != feedList) {
Toast.makeText(FeedListActivity.this, R.string.action_settings,Toast.LENGTH_SHORT).show();
updateList();
}
}
@Override
protected Void doInBackground(String... params) {
String url = params[0];
try {
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
JSONArray posts_2 = json.getJSONArray("post_2");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("date"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setAttachments(post.getString("thumb"));
item.setContent(post.getString("content"));
item.setAttachmentUrl(post.getString("attachments"));
feedList.add(item);
}
/*
for (int i = 0; i < posts_2.length(); i++) {
JSONObject post2 = (JSONObject) posts_2.getJSONObject(i);
FeedItem item2 = new FeedItem();
item2.setTitle(post2.getString("title"));
item2.setDate(post2.getString("date"));
item2.setId(post2.getString("id"));
item2.setUrl(post2.getString("url"));
item2.setAttachments(post2.getString("thumb"));
item2.setContent(post2.getString("content"));
item2.setAttachmentUrl(post2.getString("attachments"));
feedList.add(item2);
}*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
我的下载图片类别 - &gt;
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return downloadBitmap(params[0]);
}
@Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageDrawable(imageView.getContext().getResources().getDrawable(R.drawable.list_placeholder));
}
}
}
}
答案 0 :(得分:0)
使用Google建议的ViewHolder模式:http://developer.android.com/training/improving-layouts/smooth-scrolling.html