2015-03-02 38 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(); 
}