-1

So, first off, here is my code:

public class MainActivity extends Activity {


Button refresh;
TextView login;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    login = (TextView) findViewById(R.id.tvLogin);
    GetMethod test = new GetMethod();
    String returned;
    try{
        returned = test.getInternetData();
        login.setText(returned);
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

That's my MainActivity in my Android app. Here is GetMethod.

public class GetMethod {

public String getInternetData() throws Exception{
    BufferedReader in = null;
    String data = null;
    try{
        HttpClient client = new DefaultHttpClient();
        URI website = new URI("https://www.google.com/");
        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();
            }
        }
    }
}

}

I'm not getting errors and I don't see anything wrong, but I'm tired and if this is simple, I'm sorry. I've been fiddling with it forever. I've found the code on test.getInternetData()is givind an exception.

EDIT:Clarification, it's not getting to the code login.setText(returned);

user3053417
  • 33
  • 1
  • 4

2 Answers2

0

for network related operation you have to use Asynctask or threads in android otherwise you will get NetworkonMainThread Exception.

refer here

Community
  • 1
  • 1
Nambi
  • 11,944
  • 3
  • 37
  • 49
0

First off, you should always execute a long running query (like a network request) on a separate thread. Android has a very nice AsyncTask that you can extend for this purpose. My guess is that the exception is Android killing your request. They started enforcing this harder back in the 3.0 days so the UI thread doesn't get held up (bad user experience).

Another thing you could try. Rather than creating a URI, just hand the URI string into the HttpGet constructor. Then to get the String response, use EntityUtils.toString(response.getEntity());

I should note, AsyncTasks are a one-off use. So you have to create a new instance each time you want to execute a query. So don't use anonymous classes, use inner classes. Here's an example of using an AsyncTask:

private class MyTask extends AsyncTask<String, Integer, String> {
   // This happens on the background thread, do not attempt to access anything on the UI thread
   @Override
   protected String doInBackground(String... urls) {
      if( urls == null || urls.length < 1 ) {
         return null;
      }
      HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet(urls[0]);
      HttpResponse response = client.execute(request);

      return EntityUtils.toString(response.getEntity());
   }

   // This happens on the UI thread. Do any visual updates here
   @Override
   protected void onPostExecute(String result) {
      if( result != null ) {
          // Do something with it
      }
   }
}

The one thing you probably noticed is you can't just return the result in the function that starts the network query (because it happens asynchronously). You'll want to use a Callback. If you don't know what that is, look up the Observer gang of four pattern. That is one pattern that will serve you well now, and frequently in the future.

Spidy
  • 39,723
  • 15
  • 65
  • 83