I am trying to call a REST web service from my phone. For this, I use the following code. I have only one action with a button and text. Whenever I click a button, it gives the following error in logcat:
AndroidRuntime :: at android.os.Handler.dispatchMessage(Handler.java:92)
What am I doing wrong? how can i solve this ??? Below are my classes.
rest.java
public class Rest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_rest);
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String url = "http://192.168.1.145/tst.php";
RestService re = new RestService();
JSONObject jb = RestService.doGet(url);
TextView tv = (TextView) findViewById(R.id.txtView);
tv.setText(jb.toString());
}
});
}
}
RestService.java
public class RestService {
public static JSONObject doGet(String url) {
JSONObject json = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
json=new JSONObject(result);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
private static String convertStreamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
source
share