2016-01-08 2 views
0

Я написал код для простого веб-браузера, но когда я нажимаю кнопку, приложение перестает показывать сообщение «К сожалению, приложение остановилось». и он показывает мне фатальное исключение.приложение остановилось автоматически, как только я нажму кнопку. показывая фатальное исключение

Я разместил logcat, код Java, а также макет. Все три находятся в том же разделе.

LogCat

--------- beginning of crash 
01-08 11:31:04.144 2603-2603/? E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: com.example.dell.firstapp, PID: 2603 
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.loadUrl(java.lang.String)' on a null object reference 
      at com.example.dell.firstapp.MyBrowser.onClick(MyBrowser.java:54) 
      at android.view.View.performClick(View.java:4780) 
      at android.view.View$PerformClick.run(View.java:19866) 
      at android.os.Handler.handleCallback(Handler.java:739) 
      at android.os.Handler.dispatchMessage(Handler.java:95) 
      at android.os.Looper.loop(Looper.java:135) 
      at android.app.ActivityThread.main(ActivityThread.java:5257) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
01-08 11:31:04.175 1242-1935/? W/ActivityManager﹕ Force finishing activity 1 com.example.dell.firstapp/.MyBrowser 
01-08 11:31:04.603 1242-2595/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4 
01-08 11:31:04.850 1242-2595/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented 
01-08 11:31:04.850 1242-2595/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x9f1d71a0, error=EGL_SUCCESS 
01-08 11:31:04.975 1242-1260/? I/Choreographer﹕ Skipped 38 frames! The application may be doing too much work on its main thread. 
01-08 11:31:06.604 1242-1260/? W/ActivityManager﹕ Activity pause timeout for ActivityRecord{35c22eec u0 com.example.dell.firstapp/.MyBrowser t18 f} 
01-08 11:31:06.614 1242-1260/? I/Choreographer﹕ Skipped 98 frames! The application may be doing too much work on its main thread. 
01-08 11:31:14.222 1242-1260/? W/ActivityManager﹕ Launch timeout has expired, giving up wake lock! 
public class MyBrowser extends Activity implements View.OnClickListener{ 

    EditText url; 
    WebView ourBrow; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.simplebrowser); 

     WebView ourBrow=(WebView) findViewById(R.id.wvBrowser); 
     ourBrow.getSettings().setJavaScriptEnabled(true); 
     ourBrow.getSettings().setLoadWithOverviewMode(true); 
     ourBrow.getSettings().setUseWideViewPort(true); 

     ourBrow.setWebViewClient(new ourViewClient()); 
     try { 
      ourBrow.loadUrl("http://www.google.com"); 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 

     Button go=(Button) findViewById(R.id.bGo); 
     Button back=(Button) findViewById(R.id.bBack); 
     Button forward=(Button) findViewById(R.id.bFwd); 
     Button refresh=(Button) findViewById(R.id.bRefresh); 
     Button clearHistory=(Button) findViewById(R.id.bHistory); 
     url=(EditText) findViewById(R.id.etURL); 
     go.setOnClickListener(this); 
     back.setOnClickListener(this); 
     forward.setOnClickListener(this); 
     refresh.setOnClickListener(this); 
     clearHistory.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()){ 
      case R.id.bGo: 
       String theWebsite=url.getText().toString(); 
       ourBrow.loadUrl(theWebsite); 
       //Hiding the keyboard after using an EditText 
       InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       imm.hideSoftInputFromWindow(url.getWindowToken(),0); 
       break; 
      case R.id.bBack: 
       if(ourBrow.canGoBack()) 
        ourBrow.goBack(); 
       break; 
      case R.id.bFwd: 
       if(ourBrow.canGoForward()) 
        ourBrow.goForward(); 
       break; 
      case R.id.bRefresh: 
       ourBrow.reload(); 
       break; 
      case R.id.bHistory: 
       ourBrow.clearHistory(); 
       break; 
     } 
    } 
} 



    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" android:layout_height="match_parent"> 

    <LinearLayout 
     android:weightSum="100" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"> 
     <EditText 

      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/etURL" 
      android:layout_weight="20" /> 
     <Button 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="Go" 
      android:id="@+id/bGo" 
      android:layout_weight="80" 
      android:layout_marginRight="16dp"/> 
    </LinearLayout> 
    <LinearLayout 
     android:orientation="horizontal" 
     android:weightSum="8" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"> 
     <Button 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/bBack" 
      android:text="Go back page" 
      android:layout_weight="2"/> 
     <Button 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/bFwd" 
      android:text="Go forward" 
      android:layout_weight="2" 
      /> 
     <Button 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/bRefresh" 
      android:text="Refresh page" 
      android:layout_weight="2"/> 
     <Button android:text="clear History" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/bHistory" 
      android:layout_weight="2"/> 
    </LinearLayout> 
    <WebView 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:id="@+id/wvBrowser"></WebView> 

</LinearLayout> 
+4

Используйте 'ourBrow = (WebView) findViewById (R.id.wvBrowser);' вместо 'WebView ourBrow = (WebView) findViewById (R.id.wvBrowser);' –

ответ

1

Причина вы получаете этот NullPointer это вы не правильно инициализировать ваш WebView. Вы создаете объект для глобального WebView ourBrow; и вы используете то же самое внутри метода onClickourBrow.loadUrl(theWebsite);. В этом случае ваш веб-просмотр по-прежнему равен нулю.

В вашем методе onCreate вы используете webview со следующим кодом.

WebView ourBrow=(WebView) findViewById(R.id.wvBrowser); 

Так внутри OnCreate метода ваш код не получает nullPointer.

Решение:

Просто изменить
WebView ourBrow=(WebView) findViewById(R.id.wvBrowser);

к

ourBrow=(WebView) findViewById(R.id.wvBrowser); 

Примечание: ρяσѕρєя К уже добавили раствор в комментариях. Я просто добавляю объяснение.

+0

Он работает .... спасибо :) – ABSTONE

0
Please remove local declaration of webview object 'ourBrow' inside onCreate() method of activity. please replace your line 'WebView ourBrow=(WebView) findViewById(R.id.wvBrowser);' with 'ourBrow=(WebView) findViewById(R.id.wvBrowser);'. 

When you declare local webview object than the local object got initialize and global object will still null. And inside of onClick() method global object will access so it is got every time null. 

 Смежные вопросы

  • Нет связанных вопросов^_^