如何提供正确的上下文,使AlertDialog的按钮工作

时间:2016-04-16 12:29:51

标签: android android-alertdialog

accepted answer to this question开始,我构建了一个AlertDialog,我可以在Activity中多次使用,但是我遇到了正面按钮的问题。 一直试图为行(!NetworkCheck.isAvailableAndConnected(getApplicationContext())) {提供正确的上下文 在下面的代码中:

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;

    }

}

否定按钮工作正常但正面按钮只能成功解除对话框。未调用getData(如果有互联网连接),再次显示的对话框也没有(如果没有互联网连接)。     请问,提供给(!NetworkCheck.isAvailableAndConnected(getApplicationContext())) {使正面按钮工作的正确背景(如果存在问题)是什么?我尝试了getApplicationContextgetBaseContextMainActivity.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();

        }

如果有互联网连接,则重试按钮会调用getData,如果没有连接则重新显示对话框。

我本可以使用这种方法,但如果我愿意的话,我不能用另一种方法显示对话框。

2 个答案:

答案 0 :(得分:1)

我希望您在清单文件中添加了这两行。

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

好的,因为我还没有权利发表评论,我在答案部分写了这篇文章。下面的回答肯定能解决你的问题,请试试吧:

 @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);

}

答案 1 :(得分:0)

我无法发表评论,因此需要将其添加回答。 您的比赛注意到错误,您可以使用getBaseContext()。在您的情况下,getdata()只能在您的互联网连接时调用,您可以尝试连接互联网并单击肯定按钮,它现在应该调用getdata()。我已经检查过它工作正常。第二个我假设你想要阻止对话框解除正面按钮点击,如果仍然互联网断开连接。标准略有不同。

将您的代码更改为此

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

您可能会看到详细的答案。 https://stackoverflow.com/a/15619098/4381591 或者更好地使用自定义对话框。 https://stackoverflow.com/a/4016574/4381591:)