0

From the accepted answer to this question, I building an AlertDialog that I can use several times in my Activity but I having a problem with the positive button. Have been trying to supply the right context to line (!NetworkCheck.isAvailableAndConnected(getApplicationContext())) { in the code below:

MainActivity

public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";
    private AlertDialog internetDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //The usuals
        Log.d(TAG, "onCreate called");

        internetDialog = new AlertDialog.Builder(MainActivity.this)
                .setTitle(R.string.alert_titl)
                .setCancelable(false)
                .setIcon(R.mipmap.ic_launcher)
                .setMessage(R.string.alert_mess)
                .setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!NetworkCheck.isAvailableAndConnected(getApplicationContext())) {
                            internetDialog.show();
                        } else {
                            getData();
                        }

                    }
                })
                .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();

                    }
                })
                .create();



        if (NetworkCheck.isAvailableAndConnected(this)) {

              getData();

              } else {
                  internetDialog.show();
              }
          }


    //This method will get data from the web api

    private void getData(){


        Log.d(TAG, "getData called");
        //Showing progress dialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
        mProgressDialog.show();


        //Creating a json request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, "onResponse called");
                        //Dismissing the progress dialog
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }
                        /*progressDialog.dismiss();*/


                        //calling method to parse json array
                        parseData(response);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }

                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);

    }

NetworkCheck

public class NetworkCheck {

    public static boolean isAvailableAndConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
        boolean isNetWorkConnected = isNetworkAvailable && cm.getActiveNetworkInfo().isConnected();

        return isNetWorkConnected;

    }

}

The negative button is working quite alright but the positive button only succeeds in dismissing the dialog. getData is not called (if there is an internet connection) neither is the the dialog shown again (if there is no internet connection). Please, what is the right context (if that's the problem) to supply to (!NetworkCheck.isAvailableAndConnected(getApplicationContext())) { to make the positive button work? I have tried getApplicationContext, getBaseContext and MainActivity.this but it didn't work.

If I do this:

if (NetworkCheck.isAvailableAndConnected(this)) {

            //Caling method to get data
            getData();
        } else {
            final Context mContext;
            mContext = this;
            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle(R.string.alert_titl);
            alertDialogBuilder.setCancelable(false);
            alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
            alertDialogBuilder.setMessage(R.string.alert_mess);
            alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!NetworkCheck.isAvailableAndConnected(mContext)) {
                        alertDialogBuilder.show();
                    } else {
                        getData();
                    }


                }
            });
            alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            });
            alertDialogBuilder.show();

        }

the retry button calls getData if there is an internet connection and re-shows the dialog if there is no connection.

I could have used this approach but I cant't show the dialog in another method if I wanted to.

Community
  • 1
  • 1
X09
  • 3,827
  • 10
  • 47
  • 92

2 Answers2

1

I hope you have added these two lines in your manifest file.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Ok as I don't have rights to comment yet, I'm writing it in answer section.Below answer will surely solve your problem ,please try it:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    //The usuals
    Log.d(TAG, "onCreate called");

    showDialog();


    if (NetworkCheck.isAvailableAndConnected(MainActivity.this)) {

        getData();

    } else {
        internetDialog.show();
    }

}

private void showDialog() {
    internetDialog = new AlertDialog.Builder(MainActivity.this)
            .setTitle(R.string.alert_titl)
            .setCancelable(false)
            .setIcon(R.mipmap.ic_launcher)
            .setMessage(R.string.alert_mess)
            .setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!NetworkCheck.isAvailableAndConnected(MainActivity.this)) {
                        if (internetDialog != null && internetDialog.isShowing()) {
                            internetDialog.dismiss();
                            internetDialog = null;
                            showDialog();
                            internetDialog.show();
                        }
                    } else {
                        getData();
                    }

                }
            })
            .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            })
            .create();


}

//This method will get data from the web api

private void getData(){


    Log.d(TAG, "getData called");
    //Showing progress dialog
    mProgressDialog = new ProgressDialog(MainActivity.this);
    mProgressDialog.setCancelable(false);
    mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
    mProgressDialog.show();


    //Creating a json request
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, "onResponse called");
                    //Dismissing the progress dialog
                    if (mProgressDialog != null) {
                        mProgressDialog.hide();
                    }
                    /*progressDialog.dismiss();*/


                    //calling method to parse json array
                    parseData(response);

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (mProgressDialog != null) {
                        mProgressDialog.hide();
                    }

                }
            });

    //Creating request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(jsonArrayRequest);

}
Dhruvi
  • 1,971
  • 2
  • 10
  • 18
0

I can't comment so need to add it in answer. Noting wrong with your contest, you may use getBaseContext(). in your case, getdata() could only be call if your internet connected, you may try it with connecting the internet and clicking the positive button it should now call getdata(). I have checked it is working fine. Second what I assumed is you want to prevent dialog to dismiss on positive button clicking if still internet disconnected. The criteria is little different.

Change your code to this

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Message");
        builder.setPositiveButton("OK",
                new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //Do nothing here because we override this button later to change the close behaviour.
                        //However, we still need this because on older versions of Android unless we
                        //pass a handler the button doesn't get instantiated
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        internetDialog = builder.create();
        internetDialog.show();
        internetDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                boolean test = NetworkCheck.isAvailableAndConnected(getBaseContext());
                        if (test) {
                            getData();
                            internetDialog.dismiss();
                        }
                //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
            }
        });
enter code here

You may have look following detailed answers. https://stackoverflow.com/a/15619098/4381591 or better to use custom dialog. https://stackoverflow.com/a/4016574/4381591 :)

Community
  • 1
  • 1
Junaid Hafeez
  • 1,618
  • 1
  • 16
  • 25
  • No, I want the dialog to dismiss when the positive button is clicked. If it's clicked and there is internet connectivity then it should call getdata() else it should show itself again. Now do you get me? The problem is that it refused to show itself of there is no connectivity, instead it just dismissed the dialog – X09 Apr 16 '16 at 14:02
  • You may have a look on first link of sogger's answers. "Show itself again" is what you are doing wrong. I gave two links one to manage default behavior of alert dialog and other for custom dialog to keep it showing or showing again :) – Junaid Hafeez Apr 16 '16 at 14:16
  • @Ozuf have a look on my edited answer :) I have tested and it is working fine. – Junaid Hafeez Apr 16 '16 at 14:46
  • In the updated answer, are we building two AlertDialog? – X09 Apr 16 '16 at 15:01
  • no. this is a single alertdialog. First one is builder. We just use it separately to override positive button onclick method. – Junaid Hafeez Apr 16 '16 at 15:03
  • I did try it but the results is not what I wanted. I have updated my question, please can you take a look at it. – X09 Apr 16 '16 at 15:25
  • you just need to declare `AlertDialog.Builder alertDialogBuilder` in global context i,e before oncreate() method. then you may call it anywhere to show. – Junaid Hafeez Apr 16 '16 at 15:42
  • @Ozuf are you sure this was not the right answer to your question? – Junaid Hafeez Apr 16 '16 at 15:54