我使用AsyncTask解析JSON并在ListView中加载(文本,图像和其他),但加载后的某些元素位置错误或重复。如何解决?
例如:
1
2
2
3
4
4
Code AsyncTask:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
@Override
protected void onPreExecute() {}
@Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(URL);
// get the array of users
dataJsonArr = json.getJSONArray("data");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String nickname = c.getString("nickname");
products.add(new Product(nickname));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String strFromDoInBg) { SetAdapter(); }
}
我使用简单的BaseAdapter,代码:
public class BoxAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
String name, rating, desc, date;
long date_time;
Integer rate;
ImageView imageID;
TextView textDesc;
BoxAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
textDesc = (TextView) view.findViewById(R.id.desc);
if (p.username.contains("null"))
{
name = "Автор: Неизвестен";
}
else
{
name = "Автор: " + p.username;
}
if(!p.description.contains("null"))
{
desc = p.description.replaceAll("<br />", "");
desc = desc.replaceAll(""", "");
}
date_time = Long.parseLong(p.created_at);
Date dates = new Date(date_time*1000L);
SimpleDateFormat time = new SimpleDateFormat("dd.MM в HH:mm");
time.setTimeZone(TimeZone.getTimeZone("UTC+4"));
date = time.format(dates);
((TextView) view.findViewById(R.id.name)).setText(name);
((TextView) view.findViewById(R.id.rating)).setText(p.rating);
((TextView) view.findViewById(R.id.desc)).setText(desc);
((TextView) view.findViewById(R.id.date)).setText(date);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
}