Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8121993
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T05:41:24+00:00 2026-06-06T05:41:24+00:00

I’m trying to make a chat program, that will pull the server every 2

  • 0

I’m trying to make a chat program, that will pull the server every 2 seconds for new chts.

At first I simply created a thread and updated the ui on the thread, it crashed.

I added a runnable where the run method calls a methed called SendMessge. SendMessage gets the updated informtion over the internet then updated the ui.

I thoughtt the run method in the runnable will be running under my thread, it seems like it euns on the ui thread.

When my networking code in Send Message was buggey, the UI froze.

Then I set 2 break points. One before the runnable, the next after the runnable. Next I put a break point in my server so the network code would freez. Well on android the first break point went off, then it went to the break point after the runnable without waiting for me to free the brek point on the server, Thus I’m assumung the runnable was running on a different thread since the code did not wait and I’m assuming its the ui thread.

Ok so if I have this right. My network code will be in the thread before I create the runnable. will then update the ui in its run method. Problem when I get the new information to update the ui with, how do i send it to the run method in the runnable???

My code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);
    strComment=new String("na");
    mUsers=( TextView) findViewById(R.id.viewusers);;
    mComments=( TextView) findViewById(R.id.viewchats);
    mUserChat=( EditText) findViewById(R.id.viewedit);
    mScroll=( ScrollView) findViewById(R.id.scrollcomments);
    mHome=( Button) findViewById(R.id.butHome);
    mHome.setOnClickListener(this);
    mEnter=( Button) findViewById(R.id.butEnter);
    mEnter.setOnClickListener(this);

    Thread thread = new Thread(){
        @Override
        public void run() {
            try {
               int t=0;
               flagEnter=true;
               while(true){
                  handler.post(new Runnable() {
                  // I put a break point here
                      @Override
                      public void run() {
                          SendMessage();
                      }
                  });
                  // I put another break point here, it went right here without waiting for the sendmessage to finish
                  sleep(1000*10);
                  //while(true);
               }
           }catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   };

   thread.start();
}

public void onClick(View v) {
    Intent i;
    switch(v.getId()) {
        case R.id.butEnter:
            Editable e = mUserChat.getText();
            strComment=e.toString();
            flagAdd=true;
            break;
        case R.id.butHome:
            i = new Intent(this, TellaFortuneActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);    
            break;
    }
} // end function

// send a uypdate message to chat server 
// return reply in string
void SendMessage(){
    //////////////////////////////////
    // handle flags
    String de=new String("");
    String strUsers=new String("");
    String strComments=new String("");
    String comment=new String("NA");

    if (flagHome){
        Intent i;
        i = new Intent(this, TellaFortuneActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        return;
    }

    String flag="update";
    if (flagAdd){
        // get new text
        Editable  text=mUserChat.getText();
        comment=text.toString();
        mUserChat.setText("");
        flag="add";
    }

    if (flagEnter)
        flag="enter";

    if (flagExit){
        flag="exit";
        flagHome=true;
    }

    // clear all flags
    try {
        URL url = new URL("http://50.63.66.138:1044/"+flag);
        System.out.println("make connection");
        String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode("tedpottel", "UTF-8");
        data += "&" + URLEncoder.encode("comment", "UTF-8") + "=" + URLEncoder.encode( comment, "UTF-8");
        URLConnection conn = url.openConnection();
        // set timeouts to 5 seconds
        conn.setConnectTimeout(1000*5);
        conn.setReadTimeout(5*1000);
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        wr.close();

        //    if (flagAdd==false){

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line=new String();
        int state=0;

        while ((line= rd.readLine()  ) != null) {
            de=de+line;
            switch(state){
                case 0:
                    if ( line.contains("START USER"))
                        state=1;
                    if ( line.contains("START COMMENTS"))
                        state=2;
                    break;
                case 1:
                    if ( line.contains("END USER"))
                        state=0;
                    else{
                        strUsers+=line;
                        strUsers+="\n";
                    }
                    break;
                case 2:
                    // NOTE: end of comments is end, but......
                    // if we do not read in ALL the dat from server
                    // could cause connection errors
                    if ( line.contains("END COMMENTS"))
                        state=0;
                    else {
                        strComments+=line;
                        strComments+="\n";
                    }
                    break;
                } // end switch   
            } // end loop
            rd.close();
        }   
        // the next line will cause a exception
        // mUsers.setText(strUsers);
        // mComments.setText(strComments);
    } catch (Exception e) {
        i++; // use this to see if it goes here in debugger  
        System.out.println("exception");
        System.out.println(e.getMessage());
    }

    flagAdd=false;
    flagEnter=false;
    flagExit=false;
} // end methed

void Test(){
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T05:41:26+00:00Added an answer on June 6, 2026 at 5:41 am

    Try using AsyncTask for threading purpose.
    google for its simplest tutorial.

    And make sure you donot do any UI operations inside a Thread other then UI thread. Always do activity.runOnUiThread() for UI Operations. Like

    // get new text

    Editable text = mUserChat.getText();
    comment = text.toString();
    mUserChat.setText("");
    

    this code must run on a UI thread not on your eternal thread. I took this peace of code from the method that you call inside run() method of your thread.

    in external threads. You must do processing and data works. and UI updating must be done on UI thread and to run things on UI Thread always use activity.runOnUiThread() method.

    regards,
    Aqif Hamid

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.