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(){
}
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
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