Reputation: 18130
I have a method that I'm calling but, for newer versions of Android it fails. Apparently, this is due to the lack of threading. My method is to send a message to my server. This is the code (sans threading)
public String sendMessage(String username, Editable message){
BufferedReader in = null;
String data = null;
try{
DefaultHttpClient client = new DefaultHttpClient();
URI website = new URI("http://abc.com/user_send.php?username="+username+"&message="+message);
HttpPost post_request = new HttpPost();
post_request.setURI(website);
HttpGet request = new HttpGet();
request.setURI(website);
//executing actual request
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l);
}
in.close();
data = sb.toString();
return data;
}catch (Exception e){
return "ERROR";
}
}
Now, just trying to put a thread around it:
public String sendMessage(String username, Editable message){
BufferedReader in = null;
String data = null;
Thread sendThread = new Thread(){
try{
DefaultHttpClient client = new DefaultHttpClient();
URI website = new URI("http://thenjtechguy.com/njit/gds/user_send.php?username="+username+"&message="+message);
HttpPost post_request = new HttpPost();
post_request.setURI(website);
HttpGet request = new HttpGet();
request.setURI(website);
//executing actual request
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l);
}
in.close();
data = sb.toString();
return data;
}catch (Exception e){
return "ERROR";
}
} sendThread.start();
}
But that doesn't work. What am I doing wrong? Also, if you notice I'm breaking any fundamental rules in android regarding the HttpClient, please let me know.
Upvotes: 0
Views: 2012
Reputation: 11230
Your implementation is not correct - you did not override run() method
class SendThread extends Thread {
public void run(){
//add your implementation here
}
}
Tow start the thread
SendThread sendThread = new SendThread();
sendThread.start();
Upvotes: 2
Reputation: 34775
Better to a head and use AsyncTask concept.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. Refer this LINK for sample implementation
Upvotes: 1