已经使用 AsyncTask doInBackground 但新数据没有显示 [英] already use AsyncTask doInBackground but the new data not show up

查看:33
本文介绍了已经使用 AsyncTask doInBackground 但新数据没有显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 AsyncTask 建立了一个聊天室来接收消息,所以它总是检查即将到来的消息并将其显示给客户端,但代码似乎并不像我希望的那样工作.
在客户端只显示所有旧数据,新数据不显示.因为当我尝试从服务器发送消息时,新数据没有显示在客户端.
我对这个问题感到困惑,真的需要帮助.任何人请帮助我,谢谢.

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.

用于接收的异步任务

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;

                }
        }

完整代码

@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 将执行一次,您必须使用计时器在一段时间内执行它,为此您应该使用 Handler 的 postDelayed 函数.它将在主 UI 线程上以指定的延迟运行您的代码,因此您将能够更新 UI 控件.参见重复一个有时间延迟的任务

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆