我正在开发一个从服务器获取数据的项目,并在列表视图上显示数据,供用户查看 他的工作正常,但在介绍了一个Timer任务来刷新listview的内容后,我得到了很长的无限重复的内容。这是一个屏幕截图,代码正在使用:
package com.example.pius;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class viewChat extends Activity {
// ArrayList of type "Person". We are making not a list of string, sondern eine list of persons
ArrayList<Person> arrayOfWebData = new ArrayList<Person>();
class Person{
public String message;
public String name;
public String time;
//public String last_m;
}
//update stuffs
Timer autoUpdate;
// This is our new Adapter:
FancyAdapter aa = null;
// For each row we returned until we use the array to create our person obj
static ArrayList<String> resultRow;
Intent i;
String rName,recId,myName;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
new getChat().execute();
}
//getting your getting chat with a user from server
// Params,Progress,Result
private class getChat extends AsyncTask<Void,Void,Void>
{
@Override
protected Void doInBackground(Void... arg0) {
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://myurl.com/someparams");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
// Convert response to String:
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line+"\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
// Parse JSON:
try{
JSONArray jArray = new JSONArray(result);
for(int i = 0;i < jArray.length();i++)
{
// Get our object, this is on persons data:
JSONObject json_data = jArray.getJSONObject(i);
// Create a new person:
Person resultRow = new Person();
// Set thats persons attributes:
resultRow.message = json_data.getString("mmm");
resultRow.name = json_data.getString("sss");
resultRow.time = json_data.getString("ttt");
//resultRow.birthday = json_data.getString("pix");
arrayOfWebData.add(resultRow);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
populateListView();
}
}
public void populateListView()
{
final ListView myListView = (ListView)findViewById(R.id.onepm);
// initialite FancyAdapter object:
aa = new FancyAdapter();
myListView.setAdapter(aa);
//click action for each list
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
//Person p = (Person) myListView.getItemAtPosition(position);
// Log the fields to check if we got the info we want
//Log.i("SomeTag", "Persons name: " + p.person_id);
// Do something with the data. For example, passing them to a new Activity
//when message is tapped
}
});
}
class FancyAdapter extends ArrayAdapter<Person>
{
FancyAdapter(){
super(viewChat.this,android.R.layout.simple_list_item_1,arrayOfWebData);
//imageLoader = new ImageLoader(MainActivity.this);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.row4, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arrayOfWebData.get(position));
arrayOfWebData.clear();
return convertView;
}
}
class ViewHolder
{
public TextView name = null;
public TextView message = null;
//public TextView time = null;
//public TextView favorite_color = null;
ViewHolder(View row){
name = (TextView)row.findViewById(R.id.opname);
message = (TextView)row.findViewById(R.id.dmessage);
//last_m = (TextView)row.findViewById(R.id.lmess);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(Person r){
if("you".equals(r.name)){
//message.setGravity(Gravity.RIGHT);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)message.getLayoutParams();
params.setMargins(80, 0, 0, 0);
message.setLayoutParams(params);
message.setBackgroundColor(Color.parseColor("#98ccff"));
}else{
//message.setGravity(Gravity.LEFT);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)message.getLayoutParams();
params.setMargins(0, 0, 80, 0);
message.setLayoutParams(params);
message.setBackgroundColor(Color.parseColor("#ffcc98"));
}
//attempt to bring html to life
String hdtext = r.message;
Spanned ftext = Html.fromHtml(hdtext);
// name.setText(r.name);
message.setText(ftext);
//last_m.setText(r.last_m);
//favorite_color.setText(r.favorite_color);
}
}
//auto refresh
@Override
public void onResume(){
super.onResume();
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask(){
@Override
public void run(){
runOnUiThread(new Runnable(){
public void run(){
new getChat().execute();
}
});
}
}, 0,300);
}
}
答案 0 :(得分:0)
- 这里是另一个在每个所需时间更新listview的解决方案
创建处理程序和private Handler yourhandler=new Handler();
Runnable yourrunnable = new Runnable() {
@Override
public void run() {
new YourASynctask.execute();
}
};
yourhandler.post(yourrunnable);
- 在 Asynctask 的 Postexecute 方法中
粘贴代码yourhandler.postDelayed(yourrunnable, 2000);
- 2000 是您所需的时间 - 只需将上面的代码放入 onresume 方法和。 - 在您的代码中,在添加数组之前清除数组。
try{
arrayweb.clear();
for(...)
{
arrayweb.add(obj);
}
}
谢谢如果你发现它有用而且如果你仍然卡住了我的回答请告诉我!