发生错误时防止关闭力

时间:2016-04-05 08:37:47

标签: java android arrays android-edittext forceclose

我有以下代码。 当编辑文本抛出" String not found"错误它强制关闭。 我该怎么做才能防止它?例如,使用Toast通知?

    public void OnClImgBtSearch(View v)
{
    ImageButton ImgBtSearch=(ImageButton) findViewById(R.id.ImgBtSearch);
    EditText EditTextGhavaninShow=(EditText) findViewById(R.id.EditTextGhavaninShow);
    EditText EditTextGhavaninSearch=(EditText) findViewById(R.id.EditTextGhavaninSearch);

    String StrEditText =EditTextGhavaninSearch.getText().toString();


    //(EditTextGhavaninShow.getText().toString().contains(StrEditText))

    String s = EditTextGhavaninShow.getText().toString();
    try{
    if(EditTextGhavaninShow.getText().toString().contains(StrEditText));
    {
    int position = s.indexOf(StrEditText);              // where C is your character to be searched
    int Lastlen=s.lastIndexOf(StrEditText);
    int FirstLen=s.indexOf(StrEditText);
    EditTextGhavaninShow.setSelection(FirstLen,Lastlen);
    }}
    catch (TypeNotPresentException e) {
        Toast.makeText(getApplicationContext(), "عبارت مورد نظر یافت نشد", Toast.LENGTH_SHORT).show();

        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:1)

如果您想要防止您的应用因任何错误而崩溃,您应该使用Exception类:

try{
    if(EditTextGhavaninShow.getText().toString().contains(StrEditText)){
        int position = s.indexOf(StrEditText); // where C is your character to be searched
        int Lastlen=s.lastIndexOf(StrEditText);
        int FirstLen=s.indexOf(StrEditText);
        EditTextGhavaninShow.setSelection(FirstLen,Lastlen);
    }
}catch (Exception e) {
    Toast.makeText(getApplicationContext(), "عبارت مورد نظر یافت نشد", Toast.LENGTH_SHORT).show();
    e.printStackTrace();
}

尽管这不是一个好的解决方案,但您应该以不会在每个场景中崩溃的方式管理您的应用。