2

I'm a beginner & I don't know most of the Android Paradigms please help!!

Sorry!! if anyone find's this question a duplicate.

I'm facing a problem with ProgressDialog dismissing on null reference during loading of a Spinner.

It happens once during disconnecting & reconnecting to Internet, but before disconnection everything works fine i.e the loading stops when there is something in the Spinner

I've set the dismiss() method to execute when there is something in the Spinner using if() statement, but I don't know how it executes before it finds something in the Spinner, I've even set a Regex so that the dialog should get dismissed when it matches the Regex & even after this the dialog dismisses anyway.

Here's my code

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spingroup = (Spinner) findViewById(R.id.spingrp);

        if(Connection.isConn(this)) {
            Toast.makeText(this, "No internet connection detected, please check your internet connection", Toast.LENGTH_SHORT).show();
            AlertDialog alertDog = new AlertDialog.Builder(this).create();

            alertDog.setTitle("No Internet!!");
            alertDog.setMessage("Please connect to internet & try again");
            alertDog.setIcon(R.drawable.no_internet);
            alertDog.setCanceledOnTouchOutside(false);
            alertDog.setButton("Exit", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alertDog.show();
        }

        if (!Connection.isConn(this)){

            progress = ProgressDialog.show(MainActivity.this, "Loading Group","Please wait!!", true);
            progress.setCancelable(true);
            progress.setIcon(R.drawable.list_icon);
        }
//Yes this if() statement gets called before the null reference error


        dbrefspingrp = FirebaseDatabase.getInstance().getReference();
        dbrefspingrp.child("2018-19").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                final List<String> listgrp = new ArrayList<String>();
                listgrp.add("--Select Group--");

                for (DataSnapshot grpsnap: dataSnapshot.getChildren()){
                    String group = grpsnap.getKey();
                    listgrp.add(group);
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item,listgrp );
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                adapter.notifyDataSetChanged();
                spingroup.setAdapter(adapter);

                String test = listgrp.get(listgrp.size()-1);

                boolean reg = Pattern.matches("(?i)group no [0-9]{2}", test);

                if (reg == true) {
                    progress.dismiss();
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

My Attempts

1-

if (spingroup.getSelectedItem().toString().equals("--Select Group--")) {
                        progress.dismiss();
                    }

2-

if (!spingroup.getSelectedItem().toString().equals(null)) {
                        progress.dismiss();
                    }

3-

if (spingroup.getSelectedItem().toString().equals("--Select Group--") && spingroup.getSelectedItem.toString != (null) {
                        progress.dismiss();
                    }
Cybertronian
  • 473
  • 1
  • 8
  • 17

1 Answers1

2

Your problem is that the ProgressDialog progress is null. Probably because this part of the code is never called (or at least not before you try to access the ProgressDialog):

if (!Connection.isConn(this)){

    progress = ProgressDialog.show(MainActivity.this, "Loading Group","Please wait!!", true);
    progress.setCancelable(true);
    progress.setIcon(R.drawable.list_icon);
}

You can avoid the exception by checking your ProgressDialog before accessing it like:

if (progress != null && progress.isShowing()) {
   progress.dismiss();
}
Rene Ferrari
  • 4,096
  • 3
  • 22
  • 28
  • I appreciate your contribution but the `ProgressDialog` gets called because before the error there is a loading with title `Loading Group` & message `Please Wait`. – Cybertronian May 02 '19 at 19:27
  • Can you post your stacktrace? Maybe I can figure out where the problem lies with it :) – Rene Ferrari May 02 '19 at 19:38
  • java.lang.NullPinterException: Attempt to invoke virtual method 'void android.app.ProgressDialog.dismiss()' on a null reference at com.example.myapp.MainActivity$3.onDataChange(MainActivity.java:136) – Cybertronian May 02 '19 at 19:57
  • Thanks! Have you tried my suggestion with `progress != null && progress.isShowing()`? If it does not work - is there any other part in the MainACtivity where the progressDialog is used? – Rene Ferrari May 02 '19 at 20:07
  • 1
    Thank you sir! it worked, during re-connection of internet there was no error. but as I stayed in the app till the re-connection of the internet, there was no loading & the spinner got filled with data but I want a loading till the data gets loaded. Otherwise it shows the loading. – Cybertronian May 02 '19 at 20:22
  • Great! I am happy it helped! :) – Rene Ferrari May 02 '19 at 20:23
  • Sorry to bother you, but I stayed in the app till the re-connection of the internet, so when internet was connected there was no loading & the `Spinner` got filled with data – Cybertronian May 02 '19 at 20:27
  • So you expected the progressDialog to show then? Well the problem is you are only checking in the onCreate if you should show your progressDialog or not. You would have to listen to connectivity changes and then update your ui accordingly. So the best way would be registering a listener and when your internet connection changes you update your ui as required. You can use the solution provided [here](https://stackoverflow.com/questions/48527171/detect-connectivity-change-in-android-7-and-above-when-app-is-killed-in-backgrou) which lets you listen to changes in connectivity – Rene Ferrari May 02 '19 at 20:35
  • Since you are a beginner (as you have said yourself) I can't estimate how much you know but if you do not know how listeners work maybe [this](https://guides.codepath.com/android/Creating-Custom-Listeners) will help you – Rene Ferrari May 02 '19 at 20:37