0

I have followed this very basic example tutorial for loading a URL in a WebView async: android-asynctask-example.

However the app force closes when i click 'Load Webpage', with the error:

"Can't create handler inside thread that has not called Looper.prepare()".

When I remove the line "webView.getSettings().setJavaScriptEnabled(true);", the app works fine, and displays a WebView (obviously with no JavaScript enabled in the WebView).

If i leave that line in, but set enabled to false, the app also works without crashing.

I wish to modify this project, however i need JavaScript enabled, so was wondering if anyone had a clue as to why it was failing?

Any help will be greatly appreciated!

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
loufar
  • 37
  • 8

1 Answers1

0

Try it this way,

public class MainActivity extends Activity {
final Context context = this;
     WebView webView =null;
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}

private class LoadWebPageASYNC extends AsyncTask<String, Void, String> {
            @Override
    protected void onPreExecute(String result) {
             webView = (WebView) findViewById(R.id.webView);
             webView.getSettings().setJavaScriptEnabled(true);

    }
    @Override
    protected String doInBackground(String... urls) {

    webView.loadUrl(urls[0]);
              return null;
    }

    @Override
    protected void onPostExecute(String result) {

    }
}

public void dummyFunc(View view){
    Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();

}

public void readWebpage(View view) {
    LoadWebPageASYNC task = new LoadWebPageASYNC();
    task.execute(new String[] { "http://www.javacodegeeks.com" });

}

}

Andro Selva
  • 53,910
  • 52
  • 193
  • 240