2011-12-19 200 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);