gpt4 book ai didi

java - 防止发生错误时强行关闭

转载 作者:行者123 更新时间:2023-12-01 10:06:30 24 4
gpt4 key购买 nike

我有以下代码。当编辑文本抛出“找不到字符串”错误时,它会强制关闭。我可以做什么来预防它?例如使用 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();
}

最佳答案

如果您想防止应用程序因任何类型的错误而崩溃,您应该使用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();
}

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

关于java - 防止发生错误时强行关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36421185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com