Creating a thread in android not working - java

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.

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

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

Related

Apache HttpAsyncClient Reading of Response?

private void init() {
#Reactor
ioReactorConfig = IOReactorConfig.custom()
.setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setConnectTimeout(30000)
.setSoTimeout(30000)
.build();
try {
ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
} catch (IOReactorException e) {
e.printStackTrace();
//TODO handle exception
}
connManager = new PoolingNHttpClientConnectionManager(ioReactor);
httpClient = HttpAsyncClients.custom().setConnectionManager(connManager).build();
}
private ZCResponse httPost(URI uri, Object object,List<NameValuePair> params, Map<String,String> headers) {
HttpPost postRequest = new HttpPost(uri);
HttpResponse httpResponse = null;
try {
addHeaders(postRequest,headers);
addPostParams(postRequest,object,params);
Future<HttpResponse> futureResponse = httpClient.execute(postRequest, null);
httpResponse = futureResponse.get();
response = **readResponse(httpResponse);**
}
private String readResponse(HttpResponse response) throws IOException {
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
I have the following doubts about the code using Apache Http Async client
What is the role of reactor with NPoolingConnectionManager.
Currently, the response body is read from from post request's stream.And not using NIO or non-blocking way of reading the response body.Is it the right way.

Making an Async HTTPGet class

I am trying to retrieve a string from a server using HTTPGet, then I want to set that string to a TextView in my MainActivity class. Here is the class I am trying to use to accomplish this. (I didn't include the imports here, but they are in the actual class. I also withheld the URL I am using here, but the actual URL is in my class)
public class GetFromServer {
public String getInternetData() throws Exception {
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("URL withheld");
HttpGet request = new HttpGet();
request.setURI(website);
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 + nl);
}
in.close();
data = sb.toString();
return data;
}finally {
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
Then to use it in my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
GetFromServer test = new GetFromServer();
String returned = null;
try {
returned = test.getInternetData();
textView.setText(returned);
} catch (Exception e) {
e.printStackTrace();
}
}
This doesn't work because I get the android.os.NetworkOnMainThreadException, which means I have to use an AsyncTask. What I am asking is how do I turn this class into an AsyncTask so that it will work? Once it is an AsyncTask, how do I use it in my MainActivity class?
There's a pretty thorough explanation of AsyncTask over at the developer documentation.
Basically, you subclass AsyncTask, defining the types of parameters you will be working with. Your HTTPGet code will go into the doInBackground() method. To run it, you create a new instance of your AsyncTask class and call execute().

HttpClient wont work in jelly bean?

I've build app android uses http client to get content from URL,
String getRequest(String SUrl){
String vResult = "TEST";
//SUrl result of "http://mydomain.com/file.php?var=21"
HttpClient client = new DefaultHttpClient();
HttpGet request;
try{
request=new HttpGet(SUrl);
HttpResponse response = client.execute(request);
vResult=request(response);
}catch(Exception ex){
Log.e("From Server", ex.getMessage());
}
return vResult;
}
public static String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
in android gingerbread the code above work fine get content from server,but in jelly bean the code result log like this
java.lang.NullPointerException: println needs a message
why i get null in jelly bean even i already declare all variable?
thanks
Try this..
catch(Exception ex){
Log.e("From Server", ""+ex.printStackTrace());
}

Http Post and network delay

I need to make about 15 calls to diferent web services (php) at the application startup.
I'm using the following code for the post
public static String post(String url, List<BasicNameValuePair>
postvalues, HttpClient httpclient) {
try {
if (httpclient == null) {
httpclient = new DefaultHttpClient();
}
HttpPost httppost = new HttpPost(url);
if ((postvalues == null)) {
postvalues = new ArrayList<BasicNameValuePair>();
}
httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return requestToString(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String requestToString(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
The problem is that some of the petitions must be requested in a given order and each request takes about 1-2 second so the "Loading splash" takes about 10 seconds.
So my question is:Since all the connections are to the same server, how can I improve this delay? Is there some way of open a connection and send all the petitions through that "tunnel" reducing the delay?
NOTE: I tested the code and the requests take the same time reusing the httpclient using a new one in each connection
Thanks
What you have in mind is a HTTP persistent connection which reuses the TCP connection.
About this topic there is already a good question & answer here on Stackoverflow:
Persistent HttpURLConnections on Android

Using GSON to parse a json datafeed

i have a simple JSON feed which returns an image path, and a set of coordinations. The "coords" can have an unlimited set of coordinations. In my example below it only has 3 set.
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
How would i use GSON to parse this? How do I build the class for this?
Thanks
You're going to have a hard time with that because it's not valid JSON.
http://jsonlint.com/
If it were valid JSON such as ...
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
I believe GSON could parse coords to a map of <String, ArrayList<Integer>> but I'd need to try it to make sure.
Add the gson-1.7.1.jar file and write this class to get the required JSONObject or JSONArray from the url.
public class GetJson {
public JSONArray readJsonArray(String url) {
String read = null;
JSONArray mJsonArray = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonArray = new JSONArray(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonArray;
}
public JSONObject readJsonObject(String url) {
String read = null;
JSONObject mJsonObject = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonObject = new JSONObject(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonObject;
}
}
ENJOY...
Then to parse the JSON see the these tutorials,
Tutorial 1
Tutorial 2
Tutorial 3

Categories