Reputation: 22699
I am getting this network on main thread exception, even though I am running a new thread. Any idea what's going wrong here ?
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txturl=(EditText) findViewById(R.id.txtedit);
Button btngo=(Button) findViewById(R.id.btngo);
final WebView wv=(WebView) findViewById(R.id.webview);
btngo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t=new Thread(new Runnable()
{
public void run()
{
try
{
InputStream in=OpenHttpConnection("http://google.com");
byte [] buffer = new byte[10000];
in.read(buffer);
final String s=new String(buffer);
wv.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
wv.loadData(s, "text/html", "utf-8");
}
}) ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.run();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private InputStream OpenHttpConnection (String urlString) throws IOException
{
URL url=new URL(urlString);
InputStream in=null;
int response=-1;
URLConnection uc=url.openConnection();
if(!(uc instanceof HttpURLConnection))
throw new IOException("Not an http connection");
HttpURLConnection httpCon=(HttpURLConnection) uc;
httpCon.connect();
response=httpCon.getResponseCode();
if(response==HttpURLConnection.HTTP_OK)
in=httpCon.getInputStream();
return in;
}
}
Upvotes: 2
Views: 938
Reputation: 7259
As posted earlier the run thread executes on the main thread and as per the new android apis, executing IO operations or network operations on the main thread will throw this error. Hence it is required that you perform the network call in an async task and on post execute method return or update the GUI.
Upvotes: 1
Reputation: 200030
run()
executes the method on the current (main) thread, rather than start()
, which runs the run
method on a new thread.
Upvotes: 6