4

I'm trying to access a website, and put the html source code into a TextView. The browser on my emulator works, but I believe accessing the internet within my app is not functioning properly. I think I might have to use an AsyncTask, but I don't know how to implement that properly or if I even have to use it. I'm very new to programming, and have been looking on this website for a while, but cannot seem to figure it out.

This is the main code:

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView httpTest = (TextView) findViewById(R.id.textView1);
GetTest sourceCode = new GetTest();
String returned;
try {
    returned = sourceCode.getInternetData();
    httpTest.setText(returned);

} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
 }

Here is the code that is supposed to get the HTML source code:

public class GetTest {

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

My permissions in the manifest:

<uses-permission android:name="android.permission.INTERNET" />

Finally, here is my logcat:

04-30 02:28:44.368: E/Trace(1095):      error opening trace file: No such file or directory (2)
04-30 02:28:45.338: D/dalvikvm(1095):       GC_FOR_ALLOC freed 51K, 7% free 2555K/2728K, paused 41ms, total 44ms
04-30 02:28:45.348: I/dalvikvm-heap(1095):  Grow heap (frag case) to 3.216MB for 635812-byte allocation
04-30 02:28:45.398: D/dalvikvm(1095):       GC_FOR_ALLOC freed 2K, 6% free 3174K/3352K, paused 45ms, total 45ms
04-30 02:28:45.447: D/dalvikvm(1095):       GC_CONCURRENT freed <1K, 6% free 3177K/3352K, paused 5ms+4ms, total 57ms
04-30 02:28:45.509: W/System.err(1095):     android.os.NetworkOnMainThreadException
04-30 02:28:45.509: W/System.err(1095):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-30 02:28:45.509: W/System.err(1095):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-30 02:28:45.509: W/System.err(1095):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-30 02:28:45.509: W/System.err(1095):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-30 02:28:45.518: W/System.err(1095):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-30 02:28:45.518: W/System.err(1095):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-30 02:28:45.518: W/System.err(1095):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-30 02:28:45.518: W/System.err(1095):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-30 02:28:45.518: W/System.err(1095):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-30 02:28:45.528: W/System.err(1095):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-30 02:28:45.528: W/System.err(1095):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-30 02:28:45.528: W/System.err(1095):     at com.example.edittexttest.GetTest.getInternetData(GetTest.java:24)
04-30 02:28:45.528: W/System.err(1095):     at com.example.edittexttest.MainActivity.onCreate(MainActivity.java:18)
04-30 02:28:45.528: W/System.err(1095):     at android.app.Activity.performCreate(Activity.java:5104)
04-30 02:28:45.528: W/System.err(1095):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-30 02:28:45.528: W/System.err(1095):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-30 02:28:45.528: W/System.err(1095):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-30 02:28:45.528: W/System.err(1095):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 02:28:45.528: W/System.err(1095):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-30 02:28:45.538: W/System.err(1095):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 02:28:45.538: W/System.err(1095):     at android.os.Looper.loop(Looper.java:137)
04-30 02:28:45.538: W/System.err(1095):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-30 02:28:45.538: W/System.err(1095):     at java.lang.reflect.Method.invokeNative(Native Method)
04-30 02:28:45.538: W/System.err(1095):     at java.lang.reflect.Method.invoke(Method.java:511)
04-30 02:28:45.538: W/System.err(1095):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-30 02:28:45.538: W/System.err(1095):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-30 02:28:45.548: W/System.err(1095):     at dalvik.system.NativeStart.main(Native Method)
04-30 02:28:45.758: D/gralloc_goldfish(1095):   Emulator without GPU emulation detected.

Thanks for the help in advanced!

1 Answers1

2

Your code performs a networking operation in the main thread. If you are targeting the Honeycomb or higher (3.0+), you cannot perform a networking operation on the main thread. So you got this:

android.os.NetworkOnMainThreadException

Please see How to fix android.os.NetworkOnMainThreadException? for more info. It would be great if you spend some time learning how to use AsyncTask. Anyway, below is a rough code of how to use it. (I tried to modify stuffs from your code.)

public class YoursActivity extends Activity {

    private TextView httpTest;
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        httpTest = (TextView) findViewById(R.id.textView1);
        new HttpTask().execute();
        ...    
    }
    ...

    private class HttpTask extends AsyncTask<String, Void, String> {

      @Override
      protected String doInBackground(String... params) {
            GetTest sourceCode = new GetTest();
            String returned = "";
            try {
                returned = sourceCode.getInternetData();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
            return returned;
      }      

      @Override
      protected void onPostExecute(String returned) {
            httpTest.setText(returned);                
      }
    }   

}
Community
  • 1
  • 1
pt2121
  • 11,720
  • 8
  • 52
  • 69
  • 1
    Thanks! I tried to give you an upvote, but I don't have enough rep to do it. One extra question: My doInBackGround is returning an error. It says "This method must return a result of type string". I believe this is because my catch statement is not returning anything. To fix this I declared an arbitrary String variable and returned it in the catch statement. This shouldn't be a problem if the try statement works, but is there a way to fix this error with returning the actual "returned" string variable? – Brandon Cooper May 01 '13 at 01:11
  • 1
    Yes you're right. You have to return returned...give me 1 min. I'm editing the answer. (I modified doInBackground) Please see the update. – pt2121 May 01 '13 at 01:55