2016-04-05 28 views
0

我有以下代碼。 當編輯文本拋出「找不到字符串」錯誤時,強制關閉。 我能做些什麼來防止它?例如使用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(); 
    } 
+0

可以顯示完整的堆棧跟蹤嗎? – Pooya

+0

有沒有什麼方法可以選擇或突出顯示用戶在edittext中進行過濾的所有simlare單詞? –

+0

我認爲這是一個不同的問題,最好是在SO – Pooya

回答

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(); 
} 

即使這不是一個很好的解決方案,你管理你的應用程序的方式,不要在每種情況下都崩潰。

+0

感謝這個鱈魚工作翅膀對我來說。 –

+0

是否有任何爲什麼突出顯示或選擇用戶在edittext中搜索它的單詞? –

+0

您可以嘗試使用android:selectAllOnFocus =「true」 –