0

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);
            }
        });
    }
blackneko
  • 91
  • 1
  • 12
  • 1
    What kind of errors are you seeing? A couple things that I can see are definitely wrong with your code.
    1) In your Activity class you are trying to access the network, which is a big no-no. You're can't access the network from the main thread, so I'd almost bet that if you look in Logcat you'll see a NetworkOnMainThreadException, which might be killing off your app prematurely
    2) You're trying to show a Toast from doInBackground, which doesn't run on the UI thread, so you'll never see it. 3) Does your app have the proper permission declared in the manifest for internet access?
    – David C. Sainte-Claire Jun 22 '13 at 03:26
  • An AsyncTask will only run once, and then be destroyed after termination. If you want to get new messages than you would need to manage that, for example you could use a Timer to periodically start a new AsyncTask to look for new data that has arrived since the last time you polled the server. Or you could just spin up a new thread that keeps checking every so often and then goes to sleep for a predefined period of time so that it's not constantly killing the modem – David C. Sainte-Claire Jun 22 '13 at 03:51
  • @DavidC.Sainte-Claire, there is not an error in the logcat. I just have the problem to receive new messages. if I open the chatroom, the old messages can appear all, but when I tried to receive a new one from server, the new messages not appear automatically. so I thought maybe I have mistake in my AsyncTask, but I don't have idea where is it. can you help me? what am i suppose to do? thank you very much – blackneko Jun 22 '13 at 03:52
  • @DavidC.Sainte-Claire, the timer is place outside the asynctask, is it right? so I make timer to execute the AsyncTask? thank you – blackneko Jun 22 '13 at 03:59
  • 1
    Yup, you would start the timer from outside the AsyncTask. Android has a built-in TimerTask that you can search for. And your run method would periodically spin up a new AsyncTask as you currently have it – David C. Sainte-Claire Jun 22 '13 at 04:05

2 Answers2

0

You should be using onPostExcecute, this would automatically be placed back on the ui thread (if not started from inside another thread).

Refactor to something like this and it should get you closer if it wasn't the exact issue.

   private static final String TAG = "CHAT";

   public static class ReceivedTask extends AsyncTask<String, String, List<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(TAG, "content: " + content);

                // json
                List<String> messages = new ArrayList<String>();
                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);

                            messages.add(jObj.getString("message"));
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }

                    return messages;
                } else {
                    Log.e(TAG, "content was null!");
                }
            } catch (ClientProtocolException e) {
                Log.e(TAG, e.getMessage(), e);
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }

            return null;

        }

        @Override
        protected void onPostExecute(List<String> messages) {
            if (result == null) {
                Log.e(TAG, "Something failed!");
            } else {
                for (String message : messages) {
                    showMessage(result, true);
                }
            }
        }
    }

    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);

        messagesContainer.addView(textView);

        // Scroll to bottom
        if (scrollContainer.getChildAt(0) != null) {
            scrollContainer.scrollTo(scrollContainer.getScrollX(),
                    scrollContainer.getChildAt(0).getHeight());
        }
        scrollContainer.fullScroll(View.FOCUS_DOWN);
    }
JRomero
  • 4,878
  • 1
  • 27
  • 49
  • What is the TAG, because I got warning "TAG cannot be resolved to a variable" ? and if I put `showMessage(message, false);` in `onPostExecute` i got warning like this "message cannot be resolved to a variable" ? what am I suppose to do? O.o Thank you very much – blackneko Jun 22 '13 at 03:36
  • if I put `String TAG = null; String message = "";` the log enter to `something failed` .. O.o thank you – blackneko Jun 22 '13 at 03:45
  • Updated the answer, look at your logs for errors and post their stack trace. – JRomero Jun 22 '13 at 04:15
  • J.Romero, I already posted the logcat. only get one and first old data from database. not sow all the old data O.o... thank you and i tried to send messages from server it is not appear? O.o thank you very much – blackneko Jun 22 '13 at 04:26
  • oh, am i must use the timer so the asynctask will check the new messages repeatedly? O.o thank you – blackneko Jun 22 '13 at 04:32
  • updated answer but it seems like you need a lot of help trying to figure this out. Have you tried the chat? (http://chat.stackoverflow.com/rooms/15/android) – JRomero Jun 22 '13 at 04:44
  • J.Romero, I think I made mistake when make the question, sorry for that. What I wanna ask is why the new data that I send from server not show up. only show up old messages from database. what am I suppose to do? thank you very much and really sorry for my mistake not clear when make this question. – blackneko Jun 22 '13 at 04:52
0

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

Community
  • 1
  • 1
Hurab
  • 169
  • 1
  • 4