Android 由某些致命异常导致的应用程序

Android 由某些致命异常导致的应用程序,android,eclipse,nullpointerexception,Android,Eclipse,Nullpointerexception,我已经在android 2.3.6(API 10)上开发了我的应用程序,该应用程序运行良好,然后我退出活动,但它的服务在1小时后在后台执行,当我再次运行它时,由于一些致命的异常,它强制停止,但再次运行并正常工作 请帮助我理解此堆栈跟踪并帮助我解决此问题。谢谢 OnOffScreen类: public class OnOffScreen extends Activity { private TextView txtDevId,txtdevTag,txtOnOffSt,btnonoffMain,l

我已经在android 2.3.6(API 10)上开发了我的应用程序,该应用程序运行良好,然后我退出活动,但它的服务在1小时后在后台执行,当我再次运行它时,由于一些致命的异常,它强制停止,但再次运行并正常工作

请帮助我理解此堆栈跟踪并帮助我解决此问题。
谢谢

OnOffScreen类:

public class OnOffScreen extends Activity {

private TextView txtDevId,txtdevTag,txtOnOffSt,btnonoffMain,lblAlarm,txtMonitor,txtVersion,txtOcc;
private TextView txtOnOffDevType,txtTimerApp,txtStartTime,txtStartAct,txtStopTime,txtStopAct;
private ListView lstDeviceInfo;
private Button btnReport,btnOn,btnOff,btnConfig,btnStatus;
@SuppressWarnings("unused")
private Context context;
private ExceptionDialog dlg;
private SharedPreferences prefs;
private DataBaseAdapter dba;
private UtilityFunction utility;
@SuppressWarnings("unused")
private ImageView imgMain; 
private String DevId,SwId;
private Bundle bundle;
private SendSMS smsSend;
private SMSReceiver receivedSms;
private Cursor cursor,curCord;
private customCursorAdapter adpt;
private TableRow trSwitchId;
@SuppressWarnings("unused")
private ConstantClass ccl;
private static String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public OnOffScreen(){

    dba = new DataBaseAdapter(this);        
    smsSend = new SendSMS(this);
    receivedSms = new SMSReceiver(this);
    utility = new UtilityFunction(this);
     ccl = new ConstantClass();
}

  @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        final boolean isCsTitle = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.onoffscr);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if(isCsTitle)
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
        final TextView mtxTitle = (TextView)findViewById(R.id.lblMyTitle);
        mtxTitle.setText("Device On/Off Screen");
        ConstantClass.Clear_Main_Screen=false;
        ConstantClass.afterSendGotoMain = true;
        try{
            if(dba.IsConOpenOrClose()==false)
                dba.Open();
        bundle = getIntent().getExtras();
        if(bundle!=null){           
            DevId = bundle.getString("devIdTag");
            SwId = bundle.getString("SwIdTag");
            prefs = getPreferences(MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("DeviceId", DevId);
            editor.putString("SwitchId", SwId);
            //////finally saved the data/////////
            editor.commit();
        }
        txtDevId = (TextView)findViewById(R.id.txtOnScDevID);
        txtdevTag = (TextView)findViewById(R.id.txtOnScDevTag);
        txtOnOffSt = (TextView)findViewById(R.id.txtOnScDevStatus);
        txtMonitor = (TextView) findViewById(R.id.txtOnScDevMonitor);
        txtOnOffDevType = (TextView)findViewById(R.id.txtonoffDevType);
        txtVersion = (TextView)findViewById(R.id.txtOnOffDevAppVer);
        lstDeviceInfo = (ListView)findViewById(R.id.lstDeviceInfo);
        lblAlarm = (TextView)findViewById(R.id.lblOnOffAlarm);
        txtTimerApp = (TextView)findViewById(R.id.txtOnOffDevTimer);
        txtOcc = (TextView)findViewById(R.id.txtOnOffDevOcc);
        txtStartTime = (TextView)findViewById(R.id.txtOnOffStartTime);
        txtStartAct = (TextView)findViewById(R.id.txtOnOffDevStartAct);
        txtStopTime = (TextView)findViewById(R.id.txtOnOffDevStopTime);
        txtStopAct = (TextView)findViewById(R.id.txtOnOffDevStopAct);
        //imgMain = (ImageView)findViewById(R.id.imgOnOffDevice);
        btnOn = (Button)findViewById(R.id.btnOnOffOn);
        btnOff = (Button)findViewById(R.id.btnOnOffOff);
        btnStatus = (Button)findViewById(R.id.btnStatus);
        btnConfig = (Button)findViewById(R.id.btnOnOffConfig);
        btnReport = (Button)findViewById(R.id.btnOnOffSeeReport);
        btnonoffMain = (Button)findViewById(R.id.btnOnOffMain);
        trSwitchId = (TableRow)findViewById(R.id.tbRowSwitchId);
        btnOn.setOnClickListener(btnClick);         
        btnOn.setBackgroundResource(R.drawable.onbutton);
        btnOff.setOnClickListener(btnClick);
        btnOff.setBackgroundResource(R.drawable.offbutton);
        btnStatus.setOnClickListener(btnClick);
        btnStatus.setBackgroundResource(R.drawable.checkstatus);
        btnConfig.setOnClickListener(btnClick);
        btnonoffMain.setOnClickListener(btnClick);
        btnReport.setOnClickListener(btnClick);         
        if(SwId.equals("0000")){
            trSwitchId.setVisibility(TableRow.GONE);
        }else
            trSwitchId.setVisibility(TableRow.VISIBLE);

        /************Filling the Coordinator number to cursor***************/           
          curCord = dba.getCoord(dba.CurrentWorkingCoordinator(DataBaseAdapter.Key_SendCoord, 1));
            if(curCord!=null){
            ConstantClass.address = curCord.getString(curCord.getColumnIndex(DataBaseAdapter.Key_MbNo)).toString();
            startManagingCursor(curCord);           
            }

                cursor = dba.SelFromDeviceStorage(DevId, SwId);         
                startManagingCursor(cursor);        
            if (cursor.getCount()>0){
                fillControl(cursor);            
            }
            String tag = cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevTag));
            String alarm =utility.ReturnAlarm(DevId, tag);
            lblAlarm.setText(alarm);
            lblAlarm.setFocusable(true);
        lblAlarm.setOnClickListener(btnClick);
        }catch(SQLiteException e){
            Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
        }finally{
            if(curCord!=null)
                curCord.close();
        }
  }
  View.OnClickListener btnClick = new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
        case R.id.lblOnOffAlarm:
            if(lblAlarm.getText().toString()!=null){
                dlg = new ExceptionDialog(OnOffScreen.this,"Alarm " ,lblAlarm.getText().toString());
                dlg.show();
            }
            break;
        case R.id.btnOnOffOn:
            try{
            //ConstantClass.address = "5556";
                if (ConstantClass.timer != null)
                    ConstantClass.timer.cancel();
                ConstantClass.timer = new Timer();
                ConstantClass.timer.schedule(new AuditTimerTask(OnOffScreen.this), 300000);
            String msg = "<"+Integer.toHexString(26)+"3" + txtDevId.getText().toString() + SwId + Integer.toHexString(1)+">";
            smsSend.send_SMS( msg.toUpperCase());
            ////////go to mainn Screen //////

            }catch(Exception e){
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            break;
        case R.id.btnOnOffOff:
            try{
                //ConstantClass.address = "5556";
                if (ConstantClass.timer != null)
                    ConstantClass.timer.cancel();
                ConstantClass.timer = new Timer();
                ConstantClass.timer.schedule(new AuditTimerTask(OnOffScreen.this),300000);
                String msg = "<"+Integer.toHexString(26)+"3" + txtDevId.getText().toString() + SwId + Integer.toHexString(0)+">";
                smsSend.send_SMS( msg.toUpperCase());
                //////////now going to Main Screen//////////////                    
                }catch(Exception e){
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            break;
        case R.id.btnStatus:
            try{
                if (ConstantClass.timer != null)
                    ConstantClass.timer.cancel();
                ConstantClass.timer = new Timer();
                ConstantClass.timer.schedule(new AuditTimerTask(OnOffScreen.this),300000);
                String msg = "<"+Integer.toHexString(26)+"3" + txtDevId.getText().toString() + SwId + Integer.toHexString(9)+">";
                smsSend.send_SMS( msg.toUpperCase());
            }catch(Exception e){
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            break;
        case R.id.btnOnOffConfig:
            /*
             * code for go on to the Config Device Screen from OnOffScreen *
             */
            Intent onOffConfig = new Intent(OnOffScreen.this,ConfigDevice.class);
            onOffConfig.putExtra("DeviceId", txtDevId.getText().toString());
            onOffConfig.putExtra("SwId", SwId);
            OnOffScreen.this.startActivity(onOffConfig);
            break;
        case R.id.btnOnOffMain:
            /*
             * code for go on to main Zigbee Activity Class from the OnOffScreen *
             */
            try{
            Intent onOffMain = new Intent(OnOffScreen.this,ZigbeeActivity.class);
            onOffMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            if(dba.IsConOpenOrClose()==false)
                dba.Open();
            String sQuery = new String("UPDATE " + ConstantClass.dbName[3] + " SET " + DataBaseAdapter.Key_AlarmID + " = " + "0" +
            " WHERE " + DataBaseAdapter.Key_AlarmDevID + " = ?");
            dba.UpdateQuery(sQuery, DevId); 
            OnOffScreen.this.startActivity(onOffMain);
            }catch(Exception e){
                Toast.makeText(OnOffScreen.this, "On OffScreen " +  e.getMessage(),Toast.LENGTH_LONG).show();
            }
            break;
        case R.id.btnOnOffSeeReport:
            Intent rptInt = new Intent(OnOffScreen.this,ReportHistory.class);
            String dTag = null,stag = null,devsr=null, pic=null;

            if(cursor!=null){
                DevId = cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevID));
                SwId = cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_SwID));
                dTag = cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevTag));
                stag = cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_SwTag));
                devsr = String.valueOf(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevSr)));
                pic = String.valueOf(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevPic)));

                    rptInt.putExtra("DeviceID",DevId);

                    rptInt.putExtra("SwitchId", SwId);

                    rptInt.putExtra("DeviceTag", dTag);

                    rptInt.putExtra("SwitchTag",stag );

                    rptInt.putExtra("DeviceSr", devsr);

                    rptInt.putExtra("DevicePic", pic);
            OnOffScreen.this.startActivity(rptInt);
            }
            else
                OnOffScreen.this.startActivity(rptInt);
            break;
        }
    }
};
@Override
public void onStart(){
    super.onStart();        
        ///////registering the Receiver for sms receiving///////////
            registerReceiver(smsSend.sms_send,smsSend.getSentIntentFilter());
             registerReceiver(smsSend.sms_delivered,smsSend.getDeliveredFilter());
            IntentFilter filter = new IntentFilter(SMS_RECEIVED);
            registerReceiver(receivedSms,filter);    

}
  @Override 
  public void onResume(){
      super.onResume(); 
     try{                    
              dba.Open();            
      //////loading the prefrences////////
      SharedPreferences prefs = getPreferences(MODE_PRIVATE);
      DevId = prefs.getString("DeviceId", "");
      SwId = prefs.getString("SwitchId", "");         
      cursor = dba.SelFromDeviceStorage(DevId, SwId);           
        startManagingCursor(cursor);        
        if (cursor.getCount()>0){
            fillControl(cursor);            
        }
      }catch(Exception e){
          Log.d("Resume On Off", e.getMessage());

      }
  }

  @Override
  public void onPause(){
      super.onPause();  
      if(cursor!=null)
          cursor.close();         
    ConstantClass.Clear_Main_Screen = true;


 }   
  @Override
  public void onBackPressed(){
      try{
            Intent onOffMain = new Intent(OnOffScreen.this,ZigbeeActivity.class);
            onOffMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            if(dba.IsConOpenOrClose()==false)
                dba.Open();
            String sQuery = new String("UPDATE " + ConstantClass.dbName[3] + " SET " + DataBaseAdapter.Key_AlarmID + " = " + "0" +
            " WHERE " + DataBaseAdapter.Key_AlarmDevID + " = ?");
            dba.UpdateQuery(sQuery, DevId); 
            OnOffScreen.this.startActivity(onOffMain);
            }catch(Exception e){
                Toast.makeText(OnOffScreen.this, "On OffScreen " +  e.getMessage(),Toast.LENGTH_LONG).show();
            }
  }
  @Override
  public void onDestroy(){        
      super.onDestroy();
      unregisterReceiver(receivedSms);
      unregisterReceiver(smsSend.sms_send);
      unregisterReceiver(smsSend.sms_delivered);
      if(cursor!=null)
          cursor.close();   
     if(dba!=null)
          dba.Close();
  }
  public String setDtTime(String temp){
        String dd,mm,yy,hh,min;
        dd = temp.substring(0, 2);
        mm = temp.substring(2, 4);
        int mon = Integer.valueOf(mm);
        mm = Integer.toString(mon+1);
        if(mm.length()!=2)
            mm = "0" + mm;
        yy  =   temp.substring(4, 6);
        hh = temp.substring(6, 8);
        min = temp.substring(8, 10);
    return dd+"/" + mm + "/" + yy + " " + hh + ":" + min; 
    }
  public void fillControl(Cursor cursor){
      try{
      if(cursor!=null)
          cursor.moveToFirst();
     adpt = new customCursorAdapter(this,cursor);
     lstDeviceInfo.setAdapter(adpt);
     txtDevId.setText(cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevID)).toString());
     txtDevId.setTextColor(Color.BLACK);
     txtdevTag.setText(cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevTag)));
     txtdevTag.setTextColor(Color.BLACK);

     if(cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_SwID)).toString().equals("0000")){
         txtOnOffDevType.setText("Plug");
     }else
         txtOnOffDevType.setText("Switch");
     txtOnOffDevType.setTextColor(Color.BLACK);
     if(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevOnOff))==1)
         txtOnOffSt.setText("ON");
     else
         txtOnOffSt.setText("OFF");
     txtMonitor.setTextColor(Color.BLACK);
     if(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevRu))==1)
         txtMonitor.setText("Yes");
     else
         txtMonitor.setText("NO");

     txtOnOffSt.setTextColor(Color.BLACK);

     if(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevTmr))==2)
         txtTimerApp.setText("Yes");
     else
         txtTimerApp.setText("NO");
     txtTimerApp.setTextColor(Color.BLACK);
     if((cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevOc))==1)|| cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevOc))==0){
         txtOcc.setText("Once");
     }else if(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevOc))==2){
         txtOcc.setText("Daily");
     }else if(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevOc))==4){
         txtOcc.setText("Annualy");
     }else 
         txtOcc.setText("Weakly");

     txtOcc.setTextColor(Color.BLACK);
     String onTime = cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevOnTm)).toString();
        /* for catching the On Status Device */
        txtStartTime.setText(setDtTime( onTime));
        txtStartTime.setTextColor(Color.BLACK);
        if(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevOnSt))==1)
            txtStartAct.setText("ON");
        else
            txtStartAct.setText("OFF");
        txtStartAct.setTextColor(Color.BLACK);
        String offTime =cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevOffTm)).toString();
        /* for getting the timer Off act from the dbase*/


        txtStopTime.setText(setDtTime(offTime));
        txtStopTime.setTextColor(Color.BLACK);
        if(cursor.getInt(cursor.getColumnIndex(DataBaseAdapter.Key_DevOffSt))==1)
            txtStopAct.setText("ON");
        else
            txtStopAct.setText("OFF");  
        txtStopAct.setTextColor(Color.BLACK);
        String tem = cursor.getString(cursor.getColumnIndex(DataBaseAdapter.Key_DevVersion));
        txtVersion.setText(tem.substring(0, 1)+ "." + tem.substring(1, 2) + "." + tem.substring(2));
        txtVersion.setTextColor(Color.BLACK);
      }catch(Exception e){
          Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();          
      }
  }
}
06-15 14:37:35.734: E/AndroidRuntime(31310): FATAL EXCEPTION: main

06-15 14:37:35.734: E/AndroidRuntime(31310): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zigbee/com.zigbee.OnOffScreen}: java.lang.NullPointerException
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.os.Looper.loop(Looper.java:130)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.app.ActivityThread.main(ActivityThread.java:3687)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at java.lang.reflect.Method.invokeNative(Native Method)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at java.lang.reflect.Method.invoke(Method.java:507)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at dalvik.system.NativeStart.main(Native Method)
06-15 14:37:35.734: E/AndroidRuntime(31310): Caused by: java.lang.NullPointerException
06-15 14:37:35.734: E/AndroidRuntime(31310):    at com.zigbee.OnOffScreen.onCreate(OnOffScreen.java:122)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-15 14:37:35.734: E/AndroidRuntime(31310):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
06-15 14:37:35.734: E/AndroidRuntime(31310):    ... 11 more

您有NullPointerException,因为存在null对象。请尝试调试您的应用程序。

您在该语句中遇到问题

if (SwId.equals("0000")) {
您在onCreate中调用此语句,并在onResume中初始化它

SwId=prefs.getString(“SwitchId”,”)

这就是您出现异常的原因。请始终记住,在启动应用程序时,它首先调用
onCreate
,然后再调用
onResume

您仅在以下条件下在onCreate中初始化它

if (bundle != null) {
    DevId = bundle.getString("devIdTag");
    SwId = bundle.getString("SwIdTag");
}

因此,在应用程序启动的第一时间,bundle将为null,并且该条件不会执行,应用程序将崩溃。

在OnOffScreen.java的第122行中有一个
NullPointerException
。检查或报告该行中的语句。仅当bundle不为null时,您才调用该语句。请参阅我的更新答案谢谢您的努力,但这不是问题所在,因为SwId为默认0000。实际上,我发现这是onBackPressed事件。好啊