Null Pointer Exception for Progress Bar

fragment_photo_gallery

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:id="@+id/recyclerview"
    android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/loading_indicator"
    style="@style/Widget.AppCompat.ProgressBar"
    android:layout_centerInParent="true"/>

PhotoGalleryFragment
in onCreateView
View view=inflater.inflate(R.layout.fragment_photo_gallery, container, false);

    recyclerView=(RecyclerView)view.findViewById(R.id.recyclerview);
    progressBar=(ProgressBar)view.findViewById(R.id.loading_indicator);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));

    progressBar.setVisibility(View.GONE);
    setUpAdapter();
    return view;

in onPreExecute of AsyncTask
@Override
protected void onPreExecute() {
super.onPreExecute();
if(galleryItemLise.size()==0){
progressBar.setVisibility(View.VISIBLE);
}
}
in onPostExecute of AsyncTask
@Override
protected void onPostExecute(List galleryItems1) {
super.onPostExecute(galleryItems);
progressBar.setVisibility(View.GONE);
galleryItems=galleryItems1;
setUpAdapter();
}

I am getting NullPointerException for ProgressBar.Please help

Can you paste in the full error message/stacktrace?

When do you start your AsyncTask? Is it possible that the onCreateView method has not executed by the time your AsyncTask is started? Try starting your AsyncTask in onCreateView.

1 Like

I am not sure whether onCreateView is executed before AsyncTask or not.Can you tell me how to check that?
Here is the full error message/stacktrace
java.lang.RuntimeException: Unable to start activity ComponentInfo{pritish.sawant.com.photogallery/pritish.sawant.com.photogallery.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ProgressBar.setVisibility(int)’ on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2681)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ProgressBar.setVisibility(int)’ on a null object reference
at pritish.sawant.com.photogallery.PhotoGalleryFragment$FetchTask.onPreExecute(PhotoGalleryFragment.java:136)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at pritish.sawant.com.photogallery.PhotoGalleryFragment.updateItems(PhotoGalleryFragment.java:207)
at pritish.sawant.com.photogallery.PhotoGalleryFragment.onCreate(PhotoGalleryFragment.java:54)
at android.support.v4.app.Fragment.performCreate(Fragment.java:2180)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1244)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1085)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:976)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:95)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1245)
at android.app.Activity.performStart(Activity.java:6335)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2556)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2681)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

In the stacktrace that you posted, the crash is caused by:

java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ProgressBar.setVisibility(int)’ on a null object reference

This means that you are trying to call the setVisibility method on your progress bar but the progress bar is null.

In the onPreExecute method of your AsyncTask, you are setting the visibility of the progress bar. I suspect that you are starting your AsyncTask in onCreate, which is called before onCreateView. The progress bar will be null until onCreateView is called (that’s where you use findViewById to make it not null.

Try starting your AsyncTask at the bottom of onCreateView rather than in onCreate.

Perfect.Thanks alot.

Progress bars are used to show progress of a task. For example, when you are uploading or downloading something from the internet, it is better to show the progress of download/upload to the user.
Some important attributes used to describe a ProgressBar are given below :
android:max : We can set the maximum value of the ProgressBar using this attribute. By default the progress bar maximum value is 100
android:indeterminate : A boolean value is set depending on whether the time is determinate or not. Setting this attribute to false would show the actual progress. Else if it’s set to true a cyclic animation is displayed to show that progress is happening
android:minHeight : It’s used to set the height of the ProgressBar
android:minWidth : It’s used to set the width of the ProgressBar
android:progress : It’s used to set the number by which the progress bar value will be incremented
style : By default the progress bar will be displayed as a spinning wheel. If we want it to be displayed
<RelativeLayout xmlns:androclass=”http://schemas.android.com/apk/res/android"
xmlns:tools=”http://schemas.android.com/tools"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”.MainActivity” >
<Button
android:id=”@+id/button1"
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”116dp”
android:text=”download file” />

Visit : Android Notification Example Using NotificationCompat
Activity.java
package com.example.progressbar1;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick() {
btnStartProgress = (Button) findViewById(R.id.button1);
btnStartProgress.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// creating progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage(“File downloading …”);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar and filesize status
progressBarStatus = 0;
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// performing operation
progressBarStatus = doOperation();
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
// Updating the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// performing operation if file is downloaded,
if (progressBarStatus >= 100) {
// sleeping for 1 second after operation completed
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}//end of onClick method
});
}
// checking how much file is downloaded and updating the filesize
public int doOperation() {
//The range of ProgressDialog starts from 0 to 10000
while (fileSize <= 10000) {
fileSize++;
if (fileSize == 1000) {
return 10;
} else if (fileSize == 2000) {
return 20;
} else if (fileSize == 3000) {
return 30;
} else if (fileSize == 4000) {
return 40;//you can add more else if
} else{
return 100;
}
}//end of while
return 100;
}//end of doOperation
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

thanks. I am getting one more problem.My Image view Displays the same image.
For more details please check out
Same Image is getting Displayed

It really does work in onCreateView as the progressbar wont be initialized earlier in onCreate.
I set the progress bar as GONE and the RecyclerView as VISIBLE in the onPostExecute.
To finish, i do it the other way around, this is progress bar back as VISIBLE and recyclerview as GONE so this effect takes place everytime i perform a search. To achieve this, i use the method:

private void updateItems()
{
showProgressBar();
String query=QueryPreferences.getStoredQuery(getActivity());
new FetchItemsTask(query).execute();
}

public void hideProgressBar()
{
mProgressBar.setVisibility(View.GONE);
mPhotoRecyclerView.setVisibility(View.VISIBLE);
}
public void showProgressBar()
{
mProgressBar.setVisibility(View.VISIBLE);
mPhotoRecyclerView.setVisibility(View.GONE);
}

This method (updateItems()) is called by the search option from the MenuItem