2011-12-19 202 views
0

我在將數據插入數據庫時​​遇到了未知錯誤。 LogCat顯示「無法插入數據」,但是,我使用的代碼是從另一個活動(工作)複製的。無法將數據插入到Android設備的sqlite數據庫

奇怪的是,當我將代碼放在onStart()方法中時,它可以工作。但是當我放入我的onClick()時,它失敗了。

onStart():< - 不知道是否它的相關的錯誤

@Override 
public void onStart() { 
    super.onStart(); 

    dbopener = new DB_Route_ListOpener(this); 

    try { 

     dbopener.createDatabase(); 

    } catch (IOException ioe) { 

     throw new Error("Unable to create database"); 

    }//create database 

    try { 

     dbopener.openDatabase(); 

    }catch(SQLException sqle){ 

     throw sqle; 

    }//open database 

    // Configure the listview 
    routeItems = new ArrayList<String>(dbopener.selectData(new String [] {"RouteName"}, null, null, null, null, null)); 

    routeListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,routeItems); 
    routeListItem = (ListView)this.findViewById(R.id.mlt_route_list_route); 
    routeListItem.setAdapter(routeListAdapter); 
    routeListItem.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

    dbopener.close(); 

}//onStart 

onClick()

@Override 
public void onClick(View v) { 

    // TODO Auto-generated method stub 
    if (v == findViewById(R.id.mlt_route_btn_addroute))//add 
    { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setCancelable(false); 
     builder.setMessage("Add name ?"); 

     builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
     { 

      public void onClick(DialogInterface dialog, int which) 
      { 
       // TODO Auto-generated method stub 
       dialog.dismiss(); 

       ContentValues cv = new ContentValues(); 
       cv.put("RouteName", "test"); 
       dbopener.insertData(null, cv); 

      } 
     });//clear all data 

     builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
     { 

      public void onClick(DialogInterface dialog, int which) 
      { 
       // TODO Auto-generated method stub 
       dialog.cancel(); 
      } 
     });//negative 

     builder.create().show(); 
    }//if 

我插入查詢:

public void insertData (String nullColumnHack, ContentValues values) { 

    try 
    { 
     myDatabase.insert(DB_TABLE, nullColumnHack, values); 
    } catch (Exception e) { 
     Log.e("Error :","unable to insert data"); 
    }//catch 

}//insertData 
+1

顯示您logacat – vnshetty 2011-12-19 08:45:51

+1

把e.printStackTrace()在「插入查詢」 catch塊,然後看看實際未能例外 - 你得到的異常從數據庫插入會告訴你你做了什麼不正確。通過消耗和隱藏異常,使logcat輸出變得無用。 – zeetoobiker 2011-12-19 08:57:13

+0

@zeetoobiker究竟是 – vnshetty 2011-12-19 09:05:09

回答

1

您需要設置dbopener爲一個全局變量和從OnStart()移動dbopener.close();OnDestroy()因爲你關閉了數據庫插入數據

+0

感謝您的回答,因爲我不知道我可以放在onDestroy上。我一直在onStop,並總是收到數據庫爲空的錯誤,因此無法結束。謝謝。 – Jovi 2011-12-20 04:54:57

0

AlertDialog.Builder builder = new AlertDialog.Builder(this);不`噸使用「本」的任何點擊監聽器裏之前,因爲它是指當前視圖,而不是父視圖。嘗試像如下使用className.this ...

AlertDialog.Builder builder = new AlertDialog.Builder(className.this);