Friday 15 February 2013

httprequest - HttpClient in android not working properly -


I'm new to Android development. I'm just trying to get some data from the Internet and display it . When I run the program, no blank page is displayed, no error appears.

Thanks

HttpExample.java

  package com.example. Bucky1; Import android App Importroid.os.Bundle; Import android.widget.TextView; Public class increases the HttpExample activity {TextView httpStuff; @ Override Protected Zero (InstanceStat saved from bundle) {// Todo auto-generated method stub super. Connet (Saved Instantstate); SetContentView (R.layout.httpexample); HttpStuff = (TextView) findViewById (R.id.tvhttp); GetMethodEx getdata = new GetMethodEx (); Returned string; Try {return = getdata.getInternetData (); HttpStuff.setText (returned); } Hold (exception e) {e.printStackTrace (); }}}   

GetMethod.java

  package com.example.bucky1; Import java.io.buffferedReader; Import java.io.InputStreamReader; Import java.net.URI; Import org.apache.http.HttpResponse; Import org.apache.http.client.HttpClient; Import org.apache.http.client.methods.HttpGet; Import org.apache.http.impl.client.DefaultHttpClient; Public class GetMethodEx {public string getInternetData () throws an exception {in BufferedReader = zero; String data = null; Try {HTTP Client Client = New DefaultHttpClient (); URI website = new URI ("http://www.mybringback.com"); HttpGet Request = New HttpGet (); Request.setURI (website); HTTPRPRESS response = Client Execute (request); In = new buffer reader (new interstitial reader (feedback gatitity). GetContent ())); String l = ""; String nl = System.getProperty ("line.seprator"); Stringbuffer sb = new stringbuffer (""); 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; } Hold (exception e) {e.printStackTrace (); }}}}}   

httpexample.xml

  & lt ;? Xml version = "1.0" encoding = "UTF-8"? & Gt; & Lt; LinearLayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: orientation = "vertical" & gt; & Lt; ScrollView Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" & gt; & Lt; TextView Android: id = "@ + id / tvhttp" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "TextView" /> & Lt; / Scrollview & gt; & Lt; / LinearLayout & gt;    

You need to talk a lot to work things out

  1. Make sure you have Internet permission set.
  2. You can only connect to the Internet on a different thread which is not a UI thread
  3. You can edit UI only on the UI thread, so use the onPostExecute method on your asyncTask
  4. To get an easy way, use the content of your response EntityUtils.toString (response.getEntity)

No comments:

Post a Comment