0

In my application, I am trying to show a spinner/progressBar while an URL is being loaded on webView but I'm getting "java.lang.NullPointerException: How to solve this problem please refer the below code.

Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference" here id the complete error log.
    11-04 17:47:49.952 14105-14105/com.srimanjavagroup.sjg E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.srimanjavagroup.sjg, PID: 14105
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference

MainActivity.java

package com.srimanjavagroup.sjg;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

private WebView webView;
private ProgressBar progress;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    progress = (ProgressBar) findViewById(R.id.progressBar);
    //progress.setVisibility(View.GONE);
    final String ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";

        setContentView(R.layout.activity_main);
        webView = (WebView)findViewById(R.id.webView);
        //webView.setWebViewClient(new myWebclient());
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setUserAgentString(ua);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
    if(isNetworkAvailable()) {
        webView.loadUrl("http://www.srimanjavagroup.com");
        webView.setWebViewClient(new WebViewClient(){
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                webView.loadUrl("file:///android_asset/error.html");
                Toast.makeText(getApplicationContext(), "Internet is not available", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                progress.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progress.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    } else{
        webView.loadUrl("file:///android_asset/error.html");
        Toast.makeText(getApplicationContext(), "Internet is not available", Toast.LENGTH_SHORT).show();
    }
}


@Override
protected void onNewIntent(Intent intent) {`enter code here`
    super.onNewIntent(intent);
    Log.d("","Notification pass");
    Toast.makeText(getApplicationContext(), "notification test", Toast.LENGTH_LONG).show();
}

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

@Override
public void onBackPressed() {
    if(webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

main_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_width="wrap_content" />


    <WebView
        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


    </WebView>



    </android.support.constraint.ConstraintLayout>

I can't figure out why I'm getting the NullPointerException, looking over the code, everything seems how it should be.

I feel like I'm about to learn something new here because I cleaned the project, tried it out and error keeps occurring regardless.. so I'm not sure what I'm missing.

forpas
  • 160,666
  • 10
  • 38
  • 76

1 Answers1

3

First you must inflate your activity's layout:

setContentView(R.layout.activity_main);

and then find the progressbar:

progress = (ProgressBar) findViewById(R.id.progressBar);

otherwise there is no progressbar to be found and progress is null.

So the first 2 lines in onCreate() must be:

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

and after that:

progress = (ProgressBar) findViewById(R.id.progressBar);
forpas
  • 160,666
  • 10
  • 38
  • 76