为什么我尝试在溢出菜单上处理空值时会出现此异常?

时间:2014-08-21 09:40:04

标签: android

我所拥有的是Action栏上的溢出菜单..我有一个名为result的字符串,我想要做的是当这个字符串值为null时我希望它显示Toast消息而不是导航到其他活动,这是我的代码:

 @Override
            public boolean onOptionsItemSelected(MenuItem item) {
             Intent m=new Intent(Customer.this,Expendible_list.class);
             Intent i=new Intent(Customer.this,CartList.class);
                super.onOptionsItemSelected(item);

                switch(item.getItemId()){
                    case R.id.cat:
                         if(result.equals("")){
                               Toast.makeText(Customer.this, "الرجاء اختيار عميل قبل المواصلة", Toast.LENGTH_LONG).show();
                           }
                         else{
                          m.putExtra("customer", result);
                            m.putExtra("id", id);
                            startActivity(m);
                            break;    
                         }
                        case R.id.cart:

                             i.putExtra("customer", result);
                                i.putExtra("id", id);
                                startActivity(i);
                            break;  

                }
                return true;

            }

但是当我点击菜单中的第一项时,我的应用程序崩溃了,我在logcat中看到了这个异常:

FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.customer.Customer.onOptionsItemSelected(Customer.java:398)
at android.app.Activity.onMenuItemSelected(Activity.java:2548)

有什么问题?我该如何解决?

2 个答案:

答案 0 :(得分:1)

结果为空时,您希望显示Toast,因此请更改

if(result.equals("")){

if(result == null){

或将初始化更改为

String result = "";

答案 1 :(得分:0)

在以下行中,result对象为null。因为,你没有正确地初始化它,这就是你得到NullPointerException

的原因
if(result.equals(""))

在使用result对象之前,请确保您已正确初始化它而不是null ...否则,您无法摆脱NullPointerException

相关问题