2013-10-28 21 views
0

我已經按照這個非常基本的示例教程在WebView異步中加載URL: android-asynctask-example'doInBackground'中的setJavaScriptEnabled(true)強制關閉應用程序

但是應用程序強制關閉,當我點擊「加載網頁」,用錯誤:

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

當我刪除行"webView.getSettings().setJavaScriptEnabled(true);",應用程序工作正常,並且顯示的WebView(很明顯,沒有啓用JavaScript的在WebView中)。

如果我離開那條線,但將啓用設置爲false,則該應用程序也不會崩潰。

我想修改這個項目,但是我需要啓用JavaScript,所以想知道如果有人有一個線索,爲什麼它失敗?

任何幫助將不勝感激!

+0

做前期或postExecute方法 –

+0

這個東西,這可能是有益的: http://stackoverflow.com/questions/3875184/cant-create -handler-內線程是 - 有 - 不叫,打環準備 –

回答

0

嘗試這種方式,

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" }); 

} 

}