我使用 listview 来显示聊天,因为我使用 asynctask 从数据库中检索消息,然后我使用适配器和 arraylist 在项目中填充消息。然后如何更新每条新消息的列表视图以及如何保持滚动位置以及如何在 android 的标题中显示新消息的通知。
这是我的聊天活动
public class ChatActivity extends Activity implements OnScrollListener {
ListView listview;
MessageTask task;
Handler handler;
ArrayList<String> tExp=new ArrayList<String>();
Boolean loadingMore = true;
List list = new ArrayList();
Boolean stopLoadingData = false;
EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
txt=(TextView)findViewById(R.id.roomname);
listview =(ListView)findViewById(R.id.messagelist);
edit=(EditText)findViewById(R.id.editText1);
txt.setText(message);
task = new MessageTask();
task.execute(new String[]{URL});
}
class MessageTask extends AsyncTask<String, Void, List<String>> {
private final HttpClient Client = new DefaultHttpClient();
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected List<String> doInBackground(String... params) {
String output = "";
for(String out:params){
try{
HttpGet httpget = new HttpGet(out);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
output = Client.execute(httpget, responseHandler);
try {
JSONObject jObject= new JSONObject(output);
JSONArray menuObject = new JSONArray(jObject.getString("response"));
//HashMap<String,ArrayList> map = new HashMap<String,ArrayList>();
for (int i = 0; i<menuObject.length(); i++)
{
list.add(menuObject.getJSONObject(i).getString("fk_username_c").toString()+" "+menuObject.getJSONObject(i).getString("message_c").toString());
}
adapter=new ArrayAdapter<String>(ChatActivity.this,android.R.layout.simple_list_item_1);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data ");
}
}catch(Exception e){
Log.i("Animation", "Thread exception " );
}
}
return list;
}
@Override
protected void onPostExecute(List<String> list) {
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
adapter.clear();
listview.clearTextFilter();
adapter.addAll(list);
loading=false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, menu);
return true;
}
}
请帮助我如何仅在每条新消息到达数据库时更新列表视图。