2015-10-12 21 views
0

'公共類addbudget擴展ActionBarActivity實現View.OnClickListener {使用ContentValues給空指針異常

DBhelper helper; 
SQLiteDatabase db; 
EditText txtBudget; 
TextView txr; 
ListView rldlist; 
Button btn66; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.addbudget); 

    btn66=(Button)findViewById(R.id.btn_addBudget); 
    btn66.setOnClickListener(this); 

    txr=(TextView)findViewById(R.id.addbud); 

    txtBudget=(EditText)findViewById(R.id.etBudget); 

    rldlist = (ListView) findViewById(R.id.rldlist); 

    Bundle data_from_list= getIntent().getExtras(); 
    String value_in_tv= data_from_list.getString("passed data key"); 
    txr.setText(value_in_tv); 

} 

private void clearfield(){ 
    txtBudget.setText(""); 

} 


public void onClick(View v) { 
    if (btn66 == v) { 
     ContentValues value = new ContentValues(); 
     value.put(DBhelper.Amount, txtBudget.getText().toString()); 
     value.put(DBhelper.Description,txr.getText().toString()); 

     if (txtBudget.length() == 0) { 
      txtBudget.requestFocus(); 
      txtBudget.setError("Field Cannot Be Empty"); 
     } else { 
      db = helper.getWritableDatabase(); 
      db.insert(DBhelper.TABLE2, null, value); 
      db.close(); 
      clearfield(); 
      Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show(); 


     } 
    } 
} 
} 

`

這是我的活動,在這裏我想插入值的數據庫,裏面添加值Onclicklistener,我有我的代碼添加數據到數據庫,

我需要向數據庫添加「Textview txr」值和「EditText txtBudget」值,我從其他活動使用Bundle檢索「Textview txr」的值。

現在的問題是,我得到空指針異常,當我點擊添加按鈕。幫我解決這個問題。

10-12 22:23:17.142 11785-11785/com.example.username.god E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException at com.example.username.god.addbudget.onClick(addbudget.java:92) at android.view.View.performClick(View.java:4439) at android.view.View$PerformClick.run(View.java:18398) at android.os.Handler.handleCallback(Handler.java:725) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5299) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)

回答

0

這裏:

db = helper.getWritableDatabase(); 

線造成的問題,因爲helper對象是null

需要用它來調用方法之前,用來初始化輔助對象:

helper=new DBhelper(addbudget.this); 
db = helper.getWritableDatabase(); 
+0

我怎樣才能解決這個問題,plz幫助我 – xyz

+0

@xyz:看我的更新answer.if仍面臨着同樣的問題,那麼PLZ份額'DBhelper '問題的類代碼也 –

+0

哦,它的工作。非常感謝你 – xyz