在 Android 中显示自定义 AlertDialog,同时捕获异常

发布于 2024-11-05 13:57:30 字数 8525 浏览 3 评论 0原文

我正在尝试在 catch 块中向用户显示警报消息。不同之处在于我的 try/catch 位于主活动的 onCreate() 内部,因此一旦打开应用程序就会执行它。

我已经尝试过这个(我在活动结束时有一个用于对话框的 OnClick() ,其中包含 dialog.dismiss()this.finish()< /code> 之后):

 catch (SQLException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_sql))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogSQL = builder.create();
        dialogSQL.show();

        e.printStackTrace();
    }

我也尝试了这个:

   catch (NumberFormatException e) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getString(R.string.label_title_error));
        dialog.setIcon(R.drawable.error_icon);
        dialog.setMessage(getString(R.string.msg_error_numberformat));
        dialog.setNeutralButton(getString(R.string.label_ok), null);

        dialog.create().show();

        e.printStackTrace();
    }

在调试时强制异常,我可以看到它只是捕获异常,显示在 LogCat 中(作为警告)并保持流程,直到遇到另一个未处理的异常,然后显示默认的“抱歉!/强制关闭”Android 对话框。 LogCat 中没有与该对话框相关的其他异常。

为什么它不显示我的自定义警报对话框?我考虑了 Builder 需要的上下文,但是如果 onCreate() 中的 super() 在此代码之前,那么为什么它会显示该消息呢?

谢谢大家。

更新:好的,根据要求,这里有更多代码。

public class PinActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener{

private Facade facade = null;

public static int INSERT_SAL = 0;
public static int INSERT_OK = 1;
public static int INSERT_CANCEL = 2;

EditText edtIniPin;
TextView txtSelecPin;
TextView txtCancPin;

int pinMaxLengthInt;

private String[] serviceNames;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.v("FLUXO", "PIN -->> ON CREATE");
    super.onCreate(savedInstanceState);

    facade = Facade.getInstance();
    try {
        serviceNames = facade.loadApplication(this);
        facade.loadParameters(0);

        setContentView(R.layout.pin_screen);

        //Instanciando Views da Tela
        edtIniPin = (EditText) findViewById(R.id.editTextPin);
        txtSelecPin = (TextView) findViewById(R.id.btn_select_pin);
        txtCancPin = (TextView) findViewById(R.id.btn_cancel_pin);

        pinMaxLengthInt = Facade.getInstance().getPinSize();

        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(pinMaxLengthInt);
        edtIniPin.setFilters(FilterArray);

        edtIniPin.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (edtIniPin.getText().length() > 0) {
                    txtCancPin.setText(getString(R.string.btn_clean));
                }
                else if (edtIniPin.getText().length() == 0){
                    txtCancPin.setText(getString(R.string.btn_exit));
                }
                else if (edtIniPin.getText().length() == Facade.getInstance().getPinSize()){
                    edtIniPin.setEnabled(false);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    } catch (SQLException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_sql))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogSQL = builder.create();
        dialogSQL.show();

        e.printStackTrace();
    } catch (CorruptedAppException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_corrupted))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogCorrupted = builder.create();
        dialogCorrupted.show();

        e.printStackTrace();
    } catch (NoServiceAvailableException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_noservice))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogNoService = builder.create();
        dialogNoService.show();

        e.printStackTrace();
    } catch (NumberFormatException e) {

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getString(R.string.label_title_error));
        dialog.setIcon(R.drawable.error_icon);
        dialog.setMessage(getString(R.string.msg_error_numberformat));
        dialog.setNeutralButton(getString(R.string.label_ok), null);

        dialog.create().show();

    e.printStackTrace();
    }

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.v("FLUXO", "PIN -->> ON ACTIVITY RESULT");
    if (resultCode == INSERT_OK) {
        String[] initCode = (String[]) data.getSerializableExtra("init_code");

        try {
            Facade.getInstance().insertInitCode(serviceNames[0], initCode, this);
        } catch (NumberFormatException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.label_title_error))
            .setIcon(R.drawable.error_icon)
            .setMessage(getString(R.string.msg_error_numberformat))
            .setPositiveButton(getString(R.string.label_ok), this);

            AlertDialog dialog = builder.create();
            dialog.show();

            e.printStackTrace();

        } catch (SQLException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.label_title_error))
            .setIcon(R.drawable.error_icon)
            .setMessage(getString(R.string.msg_error_sql))
            .setPositiveButton(getString(R.string.label_ok), this);

            AlertDialog dialog = builder.create();
            dialog.show();

            e.printStackTrace();

        } catch (CorruptedAppException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.label_title_error))
            .setIcon(R.drawable.error_icon)
            .setMessage(getString(R.string.msg_error_corrupted))
            .setPositiveButton(getString(R.string.label_ok), this);

            AlertDialog dialog = builder.create();
            dialog.show();

            e.printStackTrace();
        }
    }
    else if (resultCode == INSERT_CANCEL){
        this.finish();
    }

}

@Override
protected void onStart() {
    Log.v("FLUXO", "PIN -->> ON START");
    super.onStart();
    txtSelecPin.setOnClickListener(this);
    txtCancPin.setOnClickListener(this);
}

@Override
protected void onResume() {
    Log.v("FLUXO", "PIN -->> ON RESUME");
    super.onResume();

    if (!facade.isInitialized(serviceNames[0], this)) {
        Intent itInicial = new Intent(this, InitialActivity.class);
        startActivityForResult(itInicial, INSERT_SAL);
    }
}

@Override
protected void onStop() {
    Log.v("FLUXO", "PIN -->> ON STOP");
    super.onStop();
}

@Override
protected void onPause() {
    Log.v("FLUXO", "PIN -->> ON PAUSE");
    super.onPause();
}

@Override
public void onBackPressed() {
    Log.v("FLUXO", "PIN -->> ON BACK KEY PRESSED");
    super.onBackPressed();
    moveTaskToBack(true);
}

@Override
protected void onDestroy() {
    Log.v("FLUXO", "PIN -->> ON DESTROY");
    super.onDestroy();
}

/**
 * Método chama próxima tela
 */
private void nextScreen(){
    Log.v("FLUXO", "PIN -->> NEXT SCREEN");
    Intent it = new Intent(this, ValueActivity.class);
    startActivity(it);
}

@Override
public void onClick(View v) {
       //lots of stuff (...)
}

@Override
public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    System.exit(0);
}

}

I'm trying to display an alert message for the users in a catch block. The difference is that my try/catch is inside the onCreate() from the main activity, so it's executed as soon as the application is opened.

I've tried this (I have an OnClick() for Dialogs in the end of the Activity with dialog.dismiss() and this.finish() after):

 catch (SQLException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_sql))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogSQL = builder.create();
        dialogSQL.show();

        e.printStackTrace();
    }

and I also tried this:

   catch (NumberFormatException e) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getString(R.string.label_title_error));
        dialog.setIcon(R.drawable.error_icon);
        dialog.setMessage(getString(R.string.msg_error_numberformat));
        dialog.setNeutralButton(getString(R.string.label_ok), null);

        dialog.create().show();

        e.printStackTrace();
    }

Forced the exceptions while debugging and I can see that it simply catches the exception, displays in the LogCat (as warning) and keep with the flow until it hits another untreated exception and then display that default "Sorry!/Force Close" Android dialog. And there are no other exceptions related to the dialog in the LogCat.

Why it does not display my custom AlertDialogs for the catch? I thought about the context that the Builder needs, but if the super() from onCreate() is before this code so why it does displays the message?

Thanks Everyone.

UPDATE: Ok, as requested, here goes more code.

public class PinActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener{

private Facade facade = null;

public static int INSERT_SAL = 0;
public static int INSERT_OK = 1;
public static int INSERT_CANCEL = 2;

EditText edtIniPin;
TextView txtSelecPin;
TextView txtCancPin;

int pinMaxLengthInt;

private String[] serviceNames;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.v("FLUXO", "PIN -->> ON CREATE");
    super.onCreate(savedInstanceState);

    facade = Facade.getInstance();
    try {
        serviceNames = facade.loadApplication(this);
        facade.loadParameters(0);

        setContentView(R.layout.pin_screen);

        //Instanciando Views da Tela
        edtIniPin = (EditText) findViewById(R.id.editTextPin);
        txtSelecPin = (TextView) findViewById(R.id.btn_select_pin);
        txtCancPin = (TextView) findViewById(R.id.btn_cancel_pin);

        pinMaxLengthInt = Facade.getInstance().getPinSize();

        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(pinMaxLengthInt);
        edtIniPin.setFilters(FilterArray);

        edtIniPin.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (edtIniPin.getText().length() > 0) {
                    txtCancPin.setText(getString(R.string.btn_clean));
                }
                else if (edtIniPin.getText().length() == 0){
                    txtCancPin.setText(getString(R.string.btn_exit));
                }
                else if (edtIniPin.getText().length() == Facade.getInstance().getPinSize()){
                    edtIniPin.setEnabled(false);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    } catch (SQLException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_sql))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogSQL = builder.create();
        dialogSQL.show();

        e.printStackTrace();
    } catch (CorruptedAppException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_corrupted))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogCorrupted = builder.create();
        dialogCorrupted.show();

        e.printStackTrace();
    } catch (NoServiceAvailableException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(getString(R.string.label_title_error))
        .setIcon(R.drawable.error_icon)
        .setMessage(getString(R.string.msg_error_noservice))
        .setPositiveButton(getString(R.string.label_ok), this);

        AlertDialog dialogNoService = builder.create();
        dialogNoService.show();

        e.printStackTrace();
    } catch (NumberFormatException e) {

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getString(R.string.label_title_error));
        dialog.setIcon(R.drawable.error_icon);
        dialog.setMessage(getString(R.string.msg_error_numberformat));
        dialog.setNeutralButton(getString(R.string.label_ok), null);

        dialog.create().show();

    e.printStackTrace();
    }

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.v("FLUXO", "PIN -->> ON ACTIVITY RESULT");
    if (resultCode == INSERT_OK) {
        String[] initCode = (String[]) data.getSerializableExtra("init_code");

        try {
            Facade.getInstance().insertInitCode(serviceNames[0], initCode, this);
        } catch (NumberFormatException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.label_title_error))
            .setIcon(R.drawable.error_icon)
            .setMessage(getString(R.string.msg_error_numberformat))
            .setPositiveButton(getString(R.string.label_ok), this);

            AlertDialog dialog = builder.create();
            dialog.show();

            e.printStackTrace();

        } catch (SQLException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.label_title_error))
            .setIcon(R.drawable.error_icon)
            .setMessage(getString(R.string.msg_error_sql))
            .setPositiveButton(getString(R.string.label_ok), this);

            AlertDialog dialog = builder.create();
            dialog.show();

            e.printStackTrace();

        } catch (CorruptedAppException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.label_title_error))
            .setIcon(R.drawable.error_icon)
            .setMessage(getString(R.string.msg_error_corrupted))
            .setPositiveButton(getString(R.string.label_ok), this);

            AlertDialog dialog = builder.create();
            dialog.show();

            e.printStackTrace();
        }
    }
    else if (resultCode == INSERT_CANCEL){
        this.finish();
    }

}

@Override
protected void onStart() {
    Log.v("FLUXO", "PIN -->> ON START");
    super.onStart();
    txtSelecPin.setOnClickListener(this);
    txtCancPin.setOnClickListener(this);
}

@Override
protected void onResume() {
    Log.v("FLUXO", "PIN -->> ON RESUME");
    super.onResume();

    if (!facade.isInitialized(serviceNames[0], this)) {
        Intent itInicial = new Intent(this, InitialActivity.class);
        startActivityForResult(itInicial, INSERT_SAL);
    }
}

@Override
protected void onStop() {
    Log.v("FLUXO", "PIN -->> ON STOP");
    super.onStop();
}

@Override
protected void onPause() {
    Log.v("FLUXO", "PIN -->> ON PAUSE");
    super.onPause();
}

@Override
public void onBackPressed() {
    Log.v("FLUXO", "PIN -->> ON BACK KEY PRESSED");
    super.onBackPressed();
    moveTaskToBack(true);
}

@Override
protected void onDestroy() {
    Log.v("FLUXO", "PIN -->> ON DESTROY");
    super.onDestroy();
}

/**
 * Método chama próxima tela
 */
private void nextScreen(){
    Log.v("FLUXO", "PIN -->> NEXT SCREEN");
    Intent it = new Intent(this, ValueActivity.class);
    startActivity(it);
}

@Override
public void onClick(View v) {
       //lots of stuff (...)
}

@Override
public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    System.exit(0);
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里兽 2024-11-12 13:57:30

AlertDialog 通常需要其父上下文可见才能正常工作(根据我的经验;如果我错了,有人纠正我)。除非出现其他错误(没有完整代码很难判断),如果将其移至 onResume() 函数中,您可能可以使其正常工作。

AlertDialog generally needs its parent Context to be visible to work correctly (in my experience; someone correct me if I'm wrong). Barring other errors (hard to tell without the full code) you could probably make that work right if you move it into your onResume() function.

溇涏 2024-11-12 13:57:30

是Activity生命周期的问题!

这就是我所做的:

        } catch (NumberFormatException e) {
        showDialog(
                R.string.label_title_error, 
                R.drawable.error_icon, 
                R.string.msg_error_noservice, 
                R.string.label_ok);
        error = true;
        e.printStackTrace();

    }

还有这个:

    @Override
protected void onResume() {
    Log.v("FLUXO", "PIN -->> ON RESUME");
    super.onResume();
    if (!error) {
        if (!facade.isInitialized(serviceNames[0], this)) {
            Intent itInicial = new Intent(this, InitialActivity.class);
            startActivityForResult(itInicial, INSERT_SAL);
        }       

    }
}

It was a problem with the life cicle of the Activity!

Heres what I did:

        } catch (NumberFormatException e) {
        showDialog(
                R.string.label_title_error, 
                R.drawable.error_icon, 
                R.string.msg_error_noservice, 
                R.string.label_ok);
        error = true;
        e.printStackTrace();

    }

and this:

    @Override
protected void onResume() {
    Log.v("FLUXO", "PIN -->> ON RESUME");
    super.onResume();
    if (!error) {
        if (!facade.isInitialized(serviceNames[0], this)) {
            Intent itInicial = new Intent(this, InitialActivity.class);
            startActivityForResult(itInicial, INSERT_SAL);
        }       

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文