以下代码上的空指针异常

时间:2015-02-18 12:30:53

标签: android

我是android和java的初学者,任何人都可以帮我在我的代码中找出这个错误的原因PLZ ???

serviceSwitch =(Switch) this.findViewById(R.id.switchservice);
serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
        try{
            if(isChecked){
                arrayChecking();
                Toast.makeText(getApplicationContext(), "set date n time ", Toast.LENGTH_LONG).show();                  
            }
        }
        catch(Exception e){
            Log.e("switchfailed",e.toString());
        }
    }       
});

arrayChecking的代码 它检查tbpreferenceArray是否为空?如果它为空它显示吐司,否则它传递意图在我的应用程序中调用后台服务

public void arrayChecking(){

    if(tbPreferenceArray.length>0){
        Toast.makeText(getApplicationContext(), "Please Set the Time and Day", Toast.LENGTH_LONG).show();
        serviceSwitch.setChecked(false);        
    }
    else{
        Intent i = new Intent(MainActivity.this, TimerService.class);
        MainActivity.this.startService(i);
        Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_LONG).show();   
    }
}

共享偏好代码

SharedPreferences prefs = getApplicationContext().getSharedPreferences("TogglePreference", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt("tbPreferenceArray" +"_size", toggleButtonArray.length); 
    for(int i=0;i<toggleButtonArray.length;i++)
    {
        editor.putBoolean("tbPreferenceArray" + "_" + i, toggleButtonArray[i]);

    }
    editor.commit();
    Toast.makeText(getApplicationContext(), "Your timetable is ok",Toast.LENGTH_LONG).show();

1 个答案:

答案 0 :(得分:0)

请更正您的代码,如下所示:

if(tbPreferenceArray!= null && tbPreferenceArray.length>0)