-1

I'm building one of my very first apps, this time I'm using Android Studio 1.5.

The app is a very simple web browser, for which I already had to make a lot of fixes. Everything was working fine until I decided that pressing the "enter" key would be simpler and more convenient than clicking on a dumb "go" button.

Oh boy wasn't I wrong

The app builds fine, but once I launch it to my phone, it crashes immediately.

below is my MainActivity.java and below that is the exception generated.

As you probably can see, I already checked extensively for "null" object attributes, and the error persists

--CODE--

package eu.depa.browsing.stack;

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements OnKeyListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);                         //what .xml it's tied to

    //getSupportActionBar().hide();                                 //hide ugly ass fat bar
                                                                    //TODO fix exception generated by this

    WebView webview = (WebView) findViewById(R.id.webView); //actual web window
    EditText toptextbar = (EditText) findViewById(R.id.toptextbar);   //address bar

    webview.getSettings().setJavaScriptEnabled(true);               // Enable javascript
    webview.setWebChromeClient(new WebChromeClient());              // Set WebView client
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
}

WebView webview = (WebView) findViewById(R.id.webView);           //actual web window
EditText toptextbar = (EditText) findViewById(R.id.toptextbar);   //address bar


@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (v != null && event != null && toptextbar.getText() != null && keyCode == KeyEvent.KEYCODE_ENTER){
        String text = String.valueOf(toptextbar.getText());
        if (!(text.contains(" ")) && text.contains(".")) {
            if (text.split("//")[0].equals("http:") || text.split("//")[0].equals("https:"))
                webview.loadUrl(text);
            else
                webview.loadUrl("http://" + text);
        } else {
            String search = "";
            String[] parts = text.split(" ");
            for (String item : parts)
                search = search + item + "%20";
            webview.loadUrl("http://duckduckgo.com/" + search);
        }
        toptextbar.setText(webview.getUrl());
    }
    return false;
}
}

--EXCEPTION-- I don't even think this is what I should be providing

12-17 14:12:15.291 19699-19699/eu.depa.browsing.stack E/AndroidRuntime: FATAL EXCEPTION: main
    Process: eu.depa.browsing.stack, PID: 19699
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{eu.depa.browsing.stack/eu.depa.browsing.stack.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
        at android.app.ActivityThread.access$900(ActivityThread.java:155)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:139)
        at android.app.ActivityThread.main(ActivityThread.java:5308)
        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:950)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
        at android.app.Activity.findViewById(Activity.java:2129)
        at eu.depa.browsing.stack.MainActivity.<init>(MainActivity.java:37)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1606)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2246)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
        at android.app.ActivityThread.access$900(ActivityThread.java:155) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:139) 
        at android.app.ActivityThread.main(ActivityThread.java:5308) 
        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:950) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
Depa
  • 53
  • 5
  • Good job at posting the logcat, most people don't do that immediately. Basically, don't call findViewById outside of or before the method call of onCreate (after setContentView). – OneCricketeer Dec 17 '15 at 13:39

3 Answers3

3

Remove the following field initialization code, you can not invoke findViewById() before the onCreate() was invoked:

WebView webview = (WebView) findViewById(R.id.webView);           //actual web window
EditText toptextbar = (EditText) findViewById(R.id.toptextbar);   //address bar

By the field initialization code I mean the code between onCreate() and onKey() methods. Just leave the fields' declaration:

private WebView webview;
private EditText toptextbar;
aga
  • 27,954
  • 13
  • 86
  • 121
  • It may not be clear to OP which two lines you mean by this. Those lines are in onCreate and outside of it. – OneCricketeer Dec 17 '15 at 13:36
  • Thank you, this was the answer I've been looking for the whole day. thanks. – Depa Dec 17 '15 at 13:39
  • @cricket_007 it's one of those awkward moments when you know where the error is but it's hard to point to it in your answers. If only SO could show line numbers... – aga Dec 17 '15 at 13:42
  • Agreed. I usually have to copy out long sections of code to an editor for errors with line numbers – OneCricketeer Dec 17 '15 at 13:47
0
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

Check the ids youre giving in, are you sure they exist in the XML?

Especially check the webview as its row nr 37:

at eu.depa.browsing.stack.MainActivity.<init>(MainActivity.java:37)
Paul
  • 478
  • 2
  • 16
0

Your xml file should looks like below:

Your webview's xml id must be webView:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <WebView
        android:id="@+id/webView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></WebView>

</RelativeLayout>

Hope this will help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151