2015-03-02 43 views
0

當我得到當我執行這個代碼的異常:安卓:java.lang.IllegalStateException執行Toast.makeText

public void onClick(View view){ 
(...) 
CharSequence text1 = "Please insert a number."; 
int id= view.getId(); 
(...) 
    else if(id== R.id.buttonOK){ 
       if(editText.getText().toString().matches("")) 
       { 
        Toast.makeText(view.getContext(), text1, Toast.LENGTH_SHORT).show(); 
       } 

執行Toast.makeText時,唯一的例外是。我已經嘗試過作爲第一個參數:

getApplicationContext()

MyActivity.this

view.getContext()

和我總是得到這個錯誤。你能幫我麼?

例外:

java.lang.IllegalStateException: Could not execute method of the activity 
      at android.view.View$1.onClick(View.java:4007) 
      at android.view.View.performClick(View.java:4756) 
      at android.view.View$PerformClick.run(View.java:19749) 
      at android.os.Handler.handleCallback(Handler.java:739) 
      at android.os.Handler.dispatchMessage(Handler.java:95) 
      at android.os.Looper.loop(Looper.java:135) 
      at android.app.ActivityThread.main(ActivityThread.java:5221) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
    Caused by: java.lang.reflect.InvocationTargetException 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372) 
      at android.view.View$1.onClick(View.java:4002) 
            at android.view.View.performClick(View.java:4756) 
            at android.view.View$PerformClick.run(View.java:19749) 
            at android.os.Handler.handleCallback(Handler.java:739) 
+0

處理這種使用您的activity.this代替「view.getContext()」這一點。 – 2015-03-02 17:03:06

+0

@SurenderKumar沒有工作,我得到了同樣的錯誤 – porthfind 2015-03-02 17:07:20

+0

你確定你是在別的地方犯錯嗎? – Apurva 2015-03-02 17:08:38

回答

0

您可以使用活動的實例,例如:

MainActivity.this 

你的情況:

Toast.makeText(MainActivity.this, text1, Toast.LENGTH_SHORT).show(); 
+0

它沒有工作,我得到了同樣的錯誤 – porthfind 2015-03-02 17:09:17

0

如果錯誤是在你給出的代碼是:

//make sure that you had declared and defined editext properly 
    else if(id== R.id.buttonOK){ 
        if(editText.getText().toString().equals("")) 
        { 
         Toast.makeText(view.getContext(), "String", Toast.LENGTH_SHORT).show(); 
        } 
+0

我已經在Toast.makeTest之前使用Log.d來檢查問題是否在if,但我可以看到,它進入瞭如果沒有問題,問題在Toast.makeText中。 – porthfind 2015-03-02 17:23:43

+0

您是否嘗試用字符串替換charsequnce。 – 2015-03-02 17:25:52

+0

是的,我已經試過了 – porthfind 2015-03-02 17:27:41

0

InvocationTargetException僅僅是一個在動態調用中引發的異常的包裝。真正的問題是,它包裹NullPointerException異常:

代碼

editText.getText().toString() 

拋出空指針異常。因此,處理空指針異常

您可以通過下面的代碼

//global variable 
String edittextvalue = ""; 

if(null != editext.getText.toString()){ 
edittextvalue = editext.getText.toString() 
} 

//now in toast condition 
if(edittextvalue.equals(""){ 
Toast.makeText(context, text1, Toast.LENGTH_SHORT).show(); 
}