我正在创建一个显示Tumblr
帐户中图片的应用。它加载前20个项目,然后在底部有一个“加载更多”按钮。当点击“加载更多”按钮时,我使用AsyncTask
来处理它。我已经按照我的想法设置了所有内容,但是我没有将接下来的20个图像追加到列表中。我已经看到其他一些项目使用自定义listAdapter
类,但我一直在寻找一种更简单的方法。
这是我的代码:
public class Example extends Activity {
Context context = null;
ListView listView = null;
TextView footer;
int offset = 0;
ProgressDialog pDialog;
private String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Tumblr> tumblrs;
try {
tumblrs = getTumblrs();
listView = (ListView) findViewById(R.id.list);
View v = getLayoutInflater().inflate(R.layout.footer_layout, null);
footer = (TextView) v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem,
tumblrs));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
footer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new loadMoreListView().execute();
}
});
}
public class UserItemAdapter extends ArrayAdapter<Tumblr> {
private ArrayList<Tumblr> tumblrs;
public UserItemAdapter(Context context, int imageViewResourceId,
ArrayList<Tumblr> tumblrs) {
super(context, imageViewResourceId, tumblrs);
this.tumblrs = tumblrs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tumblr tumblr = tumblrs.get(position);
if (tumblr != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(getBitmap(tumblr.image_url));
}
}
return v;
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (Exception ex) {
return null;
}
}
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
IOException, JSONException {
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response").getJSONArray(
"posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
.getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
return tumblrs;
}
public class Tumblr {
public String image_url;
public Tumblr(String url) {
this.image_url = url;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(Example.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// increment current page
offset += 20;
// Next page request
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset="
+ offset;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i)
.getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get listview current position - used to maintain scroll
// position
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to tumblrs ArrayList
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
}
});
return null;
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}
}
感谢任何帮助!
答案 0 :(得分:2)
ArrayList
设为static
。ArrayList
的{{1}}中,然后在tumblrs
上执行notifyDataSetChanged()
(此处为其UserItemAdapter)///////////////编辑部分////////////////////////////
我的这个项目非常大,所以只发布了两个从您的角度来看很重要的课程....
适配器类:
Adapter
活动将适配器设置为ListView:
public class ProductAdapter extends ArrayAdapter<ProductListPojo> {
Activity a;
Context context;
int layoutResourceId;
ArrayList<ProductListPojo> plp = null;
ImageLoader iLoader;
public YoutubeImageLoader imageLoader;
public ProductAdapter(Context context, int resource, ArrayList<ProductListPojo> listy) {
super(context, resource, listy);
this.layoutResourceId = resource;
this.context = context;
this.plp = listy;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
iLoader = new ImageLoader(context);
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
imageLoader = new YoutubeImageLoader(context);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imageView_PrefImage);
holder.imgIsPreffered = (ImageView)row.findViewById(R.id.imageView_isPreffered);
holder.txtTitle = (TextView)row.findViewById(R.id.textView_HeadingPref);
holder.txtprovider = (TextView)row.findViewById(R.id.textView_Provider);
holder.counterParty = (TextView)row.findViewById(R.id.textView_counterparty);
holder.closingDate = (TextView)row.findViewById(R.id.textView_ClosingDate);
holder.term = (TextView)row.findViewById(R.id.textView_Term);
holder.indexLink = (TextView)row.findViewById(R.id.textView_IndexLink);
holder.investmentType = (TextView)row.findViewById(R.id.textView_InvestmentType);
holder.productType = (TextView)row.findViewById(R.id.textView_ProductType);
holder.li = (LinearLayout)row.findViewById(R.id.linearLayout_IsPreferred);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
ProductListPojo product = plp.get(position);
try{
holder.imgIcon.setTag(product.getpId());
imageLoader.DisplayImage("http://www.xxxxxxxx.com/Resources/Covers/FullSize/"+product.getpId()+"."+"jpg", a, holder.imgIcon);
}catch(Exception ex){
holder.imgIcon.setImageResource(R.drawable.milkywhite);
}
holder.imgIsPreffered.setBackgroundResource(R.drawable.correct);
if (product.isPref()){
//holder.imgIsPreffered.setVisibility(View.VISIBLE);
holder.li.setVisibility(View.VISIBLE);
}else{
//holder.imgIsPreffered.setVisibility(View.INVISIBLE);
holder.li.setVisibility(View.INVISIBLE);
}
holder.txtTitle.setText(product.getOverview());
holder.txtprovider.setText(product.getProvider());
holder.counterParty.setText(product.getCounterparty());
holder.closingDate.setText(dateKoKaro(product.getClosingDate().toString()));
holder.term.setText(product.getTerm());
holder.indexLink.setText(product.getIndexLink());
holder.investmentType.setText(product.getInvestmentType());
holder.productType.setText(product.getProductType());
return row;
}
public String dateKoKaro(String datu){
/*Pattern pat = Pattern.compile("\\d.?.?.?.?-.?.?.?.?.?");
Matcher mat = pat.matcher(datu);
String dx = new String();
while(mat.find()){
dx = mat.group();
}
System.out.println(dx);*/
String l = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(datu)));
System.out.println("THE TIME: "+l);
String[] dxxx = l.split("-");
Calendar c = Calendar.getInstance();
System.out.println("Y: "+Integer.parseInt(dxxx[0])+" - "+"M: "+Integer.parseInt(dxxx[1])+" - "+"D: "+Integer.parseInt(dxxx[2]));
if(Integer.parseInt(dxxx[1])==0){
c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1]), Integer.parseInt(dxxx[2]));
}
else{
c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1])-1, Integer.parseInt(dxxx[2]));
}
Date d = c.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
String InDate = df.format(d);
return InDate;
}
static class WeatherHolder
{
ImageView imgIcon;
ImageView imgIsPreffered;
TextView txtTitle;
TextView txtprovider;
TextView counterParty;
TextView closingDate;
TextView term;
TextView indexLink;
TextView investmentType;
TextView productType;
LinearLayout li;
}
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
}
答案 1 :(得分:0)
嗯,你在do&b; doInBsckground()方法中有这段代码
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
删除此内容。只需要做tumblers.add(对象)。这足以填充相同的列表,而不是创建一个具有相同名称的新列表。
答案 2 :(得分:0)
public class Example extends Activity {
Context context = null;
ListView listView = null;
TextView footer;
int offset = 0;
ProgressDialog pDialog;
ArrayList<Tumblr> tumblrs;
private String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts? api_key=API_KEY&offset=0";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
tumblrs = getTumblrs();
listView = (ListView) findViewById(R.id.list);
View v = getLayoutInflater().inflate(R.layout.footer_layout, null);
footer = (TextView) v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
footer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new loadMoreListView().execute();
}
});
public class UserItemAdapter extends ArrayAdapter<Tumblr> {
public UserItemAdapter(Context context, int imageViewResourceId) {
super(context, imageViewResourceId, tumblrs);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tumblr tumblr = tumblrs.get(position);
if (tumblr != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(getBitmap(tumblr.image_url));
}
}
return v;
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (Exception ex) {
return null;
}
}
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
IOException, JSONException {
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response").getJSONArray(
"posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
.getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
return tumblrs;
}
}
public class Tumblr {
public String image_url;
public Tumblr(String url) {
this.image_url = url;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(Example.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// increment current page
offset += 20;
// Next page request
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts? api_key=API_KEY&limit=2&offset="
+ offset;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i)
.getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get listview current position - used to maintain scroll
// position
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to tumblrs ArrayList
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
}
});
return null;
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}
}
这就是我的建议。我已经从oncreate移动了tumblrs
列表的第一个声明,直到活动类本身。我已将asyctask
课程作为此活动的子课程,因此您不必将tumblrs
作为参数传递给new UserItemAdapter()
。我已经为你删除了这个论点。关于this.tumblrs=tumnlrs
你不再需要它了。如果您在其他地方使用tumblrs
,请参阅Activity类本身中声明的相同tumblrs
对象。您甚至可以使tumblrs
变为静态,如上面的答案中所述。实际上,将其设为静态是实现此目的的最佳方式。