0

I have done the code below for getting a xml result, but its not showing any result. I was expecting to see the result in the TextView txtVwHttp-which i have in the mainActivities layout xml file. Any suggestion? i have given the internet permission in manifest.xml.

public class MainActivity extends Activity 
{
 TextView txtvw;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtvw = (TextView)findViewById(R.id.txtVwHttp);

    //If connection doesnt work, even aftr givin permission for internet
     StrictMode.ThreadPolicy policy = new    StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);


    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("api.androidhive.info/pizza/?format=xml");
    HttpResponse response;

    try
    { response = httpClient.execute(httpGet);
          Log.i("Preda", response.getStatusLine().toString());
     HttpEntity entity = response.getEntity();
     if(entity != null)
       {     InputStream inStream = entity.getContent();
         String result = convertStreamToString(inStream);  // my defined method
             txtvw.setText(result);
             inStream.close();
         } } catch(Exception exc){}
    }

    private static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        { while((line = reader.readLine()) != null)
               {  sb.append(line + "\n"); }
        }

        catch(Exception exp)
            { exp.printStackTrace() ;}

        finally { try{ is.close(); }
             catch(IOException ioExp){ ioExp.printStackTrace(); }
    }

    return sb.toString();
    }      }
Sandeep R
  • 2,284
  • 3
  • 25
  • 51
shaon007
  • 163
  • 3
  • 16

1 Answers1

0

While it might be a good exercise to learn how to use DefaultHttpClient it is not a very practical thing to do. You need to write a lot of boilerplate code and you need to wrap your calls in an AsyncTask to not block the UI thread. If you want a nice, clean and stable solution I'd suggest that you use the well known Android Asynchronous Http Client 3rd party library. From the site:

"An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing."

Making a GET is as easy as:

AsyncHttpClient client = new AsyncHttpClient();
client.get("api.androidhive.info/pizza/?format=xml", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        txtvw.setText(response);
    }
});

PS Reading a stream as a string can be done in a more concise way. I always do this:

public static String getAsString(InputStream is) {
    if(is == null) {
        return null;
    }
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : null;
}

From the following SO answer.

Community
  • 1
  • 1
britzl
  • 10,132
  • 7
  • 41
  • 38
  • you have set the text inside asynHttpClient. what do i need to do inside oncreat()? & where shall i use the getAsString() ? – shaon007 Feb 13 '14 at 07:08
  • Sorry, the PS regarding getAsString() was referring to a better/shorter version of your convertStreamToString(). The first snippet of code was a complete example for doing an HTTP GET using AndroidAsyncHttpClient. Note that I'm not setting the text "inside" asyncHttpClient, I'm setting it in an anonymous response handler instance (instance of AsyncHttpResponseHandler). Put the entire snippet of code inside your onCreate and make sure to put the AndroidAsyncHttpClient .jar file in your /libs folder of the project and you should be ready to give it a try. – britzl Feb 13 '14 at 08:16