已经使用的AsyncTask doInBackground但新的数据显示不出来 [英] already use AsyncTask doInBackground but the new data not show up
问题描述
我做一个聊天室的AsyncTask的接收信息,所以它总是检查即将到来的消息,并展示给客户,但code似乎没有什么工作,我希望。
在客户端只显示所有旧DATAS,新DATAS显示不出来。
因为当我尝试从服务器发送消息,新的数据并没有在客户端显示出来。
我很困惑这个问题,真的需要帮助。请人帮我,谢谢你。
AsyncTask的用于接收
公共类ReceivedTask扩展的AsyncTask<字符串,字符串,字符串> {
@覆盖
在preExecute保护无效(){
}
@覆盖
保护字符串doInBackground(字符串...为arg0){
// TODO自动生成方法存根
尝试{
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httpPost =新HttpPost(SERVER_URL);
ArrayList的<的NameValuePair>参数=新的ArrayList<的NameValuePair>();
//添加参数
httpPost.setEntity(新UrlEn codedFormEntity(参数));
HTT presponse HTT prespose = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT prespose.getEntity();
//读取内容
InputStream的时间= httpEntity.getContent();
的BufferedReader读=新的BufferedReader(新的InputStreamReader(在));
字符串的内容=;
串线=;
而((行= read.readLine())!= NULL){
内容+ =行;
}
Log.d(ADBUG,内容:+内容);
// JSON
如果(!content.equals(空)){
尝试{
JSONArray jArr =新JSONArray(内容);
//字符串消息=;
的for(int i = 0; I< jArr.length();我++){
的JSONObject jObj = jArr.getJSONObject(ⅰ);
字符串消息= jObj.getString(信息);
showMessage(消息,FALSE);
}
}赶上(JSONException E){
// TODO自动生成的catch块
e.printStackTrace();
}
}
其他{
Toast.makeText(ChatRoom.this,错误,Toast.LENGTH_LONG).show();
}
}赶上(ClientProtocolException E){
// TODO自动生成的catch块
e.printStackTrace();}
赶上(IOException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}
返回null;
}
}
全code
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.chatpage);
messagesContainer =(ViewGroup中)findViewById(R.id.messagesContainer);
scrollContainer =(滚动型)findViewById(R.id.scrollContainer);
按钮sendMessageButton =(按钮)findViewById(R.id.sendButton);
束束= this.getIntent()getExtras()。
/ *最后弦乐paramnama = bundle.getString(非农产品市场准入); * /
=的MessageText(的EditText)findViewById(R.id.messageEdit);
meLabel =(TextView中)findViewById(R.id.meLabel);
friendLabel =(TextView中)findViewById(R.id.friendLabel);
meLabel.setText(我);
最后的字符串参数1 = bundle.getString(keyCourseId);
最后的字符串参数2 = bundle.getString(keyUserId);
最后的字符串参数3 = bundle.getString(keyChatsId);
串param4 = bundle.getString(keyMessagesId);
sendMessageButton.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根
//用于发送一部分已经工作正常
});
HttpURLConnection的连接;
网址URL = NULL;
尝试{
linkurl =新Koneksi(本);
SERVER_URL = linkurl.getUrl();
SERVER_URL + =/mobile/ChatRoom.php?idu="+param2+"&idch="+param3;
URL =新的URL(SERVER_URL);
连接=(HttpURLConnection类)url.openConnection();
connection.setDoOutput(真正的);
connection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
connection.setRequestMethod(POST);
新ReceivedTask()执行()。
}
赶上(IOException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}
}
公共类ReceivedTask扩展的AsyncTask<字符串,字符串,字符串> {
@覆盖
在preExecute保护无效(){
}
@覆盖
保护字符串doInBackground(字符串...为arg0){
// TODO自动生成方法存根
尝试{
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httpPost =新HttpPost(SERVER_URL);
ArrayList的<的NameValuePair>参数=新的ArrayList<的NameValuePair>();
//添加参数
httpPost.setEntity(新UrlEn codedFormEntity(参数));
HTT presponse HTT prespose = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT prespose.getEntity();
//读取内容
InputStream的时间= httpEntity.getContent();
的BufferedReader读=新的BufferedReader(新的InputStreamReader(在));
字符串的内容=;
串线=;
而((行= read.readLine())!= NULL){
内容+ =行;
}
Log.d(ADBUG,内容:+内容);
// JSON
如果(!content.equals(空)){
尝试{
JSONArray jArr =新JSONArray(内容);
//字符串消息=;
的for(int i = 0; I< jArr.length();我++){
的JSONObject jObj = jArr.getJSONObject(ⅰ);
字符串消息= jObj.getString(信息);
showMessage(消息,FALSE);
}
}赶上(JSONException E){
// TODO自动生成的catch块
e.printStackTrace();
}
}
其他{
Toast.makeText(ChatRoom.this,错误,Toast.LENGTH_LONG).show();
}
}赶上(ClientProtocolException E){
// TODO自动生成的catch块
e.printStackTrace();}
赶上(IOException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}
返回null;
}
}
公共无效showMessage(字符串消息,布尔leftSide){
最后的TextView TextView的=新的TextView(ChatRoom.this);
textView.setTextColor(Color.BLACK);
textView.setText(消息);
INT bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams PARAMS =新LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
如果(!leftSide){
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(PARAMS);
textView.setBackgroundResource(bgRes);
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
messagesContainer.addView(TextView的);
//滚动到底
如果(scrollContainer.getChildAt(0)!= NULL){
scrollContainer.scrollTo(scrollContainer.getScrollX(),scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
的AsyncTask将执行一次,你必须使用定时器在一段时间内完成它,你应该使用处理器的postDelayed函数用于这一目的。它将运行您的code与主UI线程上指定的延迟,因此您将能够更新UI控件。 看到与时间延迟重复任务
I make a chat room with AsyncTask for receive messages, so it always checking the coming messages and show it to client, but the code seems not works what i hope.
in client only show all old datas, for the new datas not show up.
because when I try to send messages from server, the new data didn't show in client.
I got confused with this problem, and really need help. anyone please help me, thank you.
AsyncTask for receive
public class ReceivedTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
//add parameter
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpRespose = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespose.getEntity();
//read content
InputStream in = httpEntity.getContent();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String content = "";
String line = "";
while((line = read.readLine())!=null){
content += line;
}
Log.d("ADBUG", "content: "+content);
//json
if(!content.equals("null")){
try{
JSONArray jArr = new JSONArray(content);
//String messages="";
for(int i=0; i < jArr.length() ; i++){
JSONObject jObj = jArr.getJSONObject(i);
String message = jObj.getString("message");
showMessage(message, false);
}
}catch(JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(ChatRoom.this, "Error", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
the whole code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatpage);
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
Bundle bundle = this.getIntent().getExtras();
/*final String paramnama = bundle.getString("nama");*/
messageText = (EditText) findViewById(R.id.messageEdit);
meLabel = (TextView) findViewById(R.id.meLabel);
friendLabel = (TextView) findViewById(R.id.friendLabel);
meLabel.setText("me");
final String param1 = bundle.getString("keyCourseId");
final String param2 = bundle.getString("keyUserId");
final String param3 = bundle.getString("keyChatsId");
String param4 = bundle.getString("keyMessagesId");
sendMessageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//for send part already works fine
});
HttpURLConnection connection;
URL url = null;
try{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3;
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
new ReceivedTask().execute();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class ReceivedTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
//add parameter
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpRespose = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespose.getEntity();
//read content
InputStream in = httpEntity.getContent();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String content = "";
String line = "";
while((line = read.readLine())!=null){
content += line;
}
Log.d("ADBUG", "content: "+content);
//json
if(!content.equals("null")){
try{
JSONArray jArr = new JSONArray(content);
// String messages="";
for(int i=0; i < jArr.length() ; i++){
JSONObject jObj = jArr.getJSONObject(i);
String message = jObj.getString("message");
showMessage(message, false);
}
}catch(JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(ChatRoom.this, "Error", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(ChatRoom.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
@Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
AsyncTask will performed once , you have to use timer to perform it in period time ,You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls. see repeat a task with a time delay
这篇关于已经使用的AsyncTask doInBackground但新的数据显示不出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!