Java 在sql lite数据库中插入信息无效
已经存储在数据库中的文本显示没有任何问题。但新插入的数据不显示。我认为“添加新文本不会显示任何内容,就好像没有执行插入操作一样。”。我不知道为什么它不起作用。请帮忙 我的DatabaseHandler类Java 在sql lite数据库中插入信息无效,java,android,database,sqlite,Java,Android,Database,Sqlite,已经存储在数据库中的文本显示没有任何问题。但新插入的数据不显示。我认为“添加新文本不会显示任何内容,就好像没有执行插入操作一样。”。我不知道为什么它不起作用。请帮忙 我的DatabaseHandler类 public class databaseHandler extends SQLiteOpenHelper { private Context main_context; private static String DB_PATH; private static St
public class databaseHandler extends SQLiteOpenHelper
{
private Context main_context;
private static String DB_PATH;
private static String DB_NAME = "word.sqlite";
private static String DB_TBL_BOOKS = "word";
private static String DB_TBL_SETTING = "setting";
private static final int DB_version = 1;
public static final String COLUMN_ID = "ID";
public static final String COLUMN_FIRST_NAME = "title";
public static final String COLUMN_LAST_NAME = "content";
private SQLiteDatabase db;
public databaseHandler(Context con)
{
super(con, DB_NAME, null, DB_version);
main_context = con;
DB_PATH = con.getCacheDir().getPath() + "/" +DB_NAME;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
copyDB();
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
@Override
public void onCreate(SQLiteDatabase db) {
String query;
query = "CREATE TABLE word (id INTEGER PRIMARY KEY NOT NULL , title VARCHAR, content VARCHAR DEFAULT null)";
db.execSQL(query);
Log.d("log","table Created");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("tag", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS word");
onCreate(db);
}
private boolean db_exist() {
File f = new File(DB_PATH);
if (f.exists())
{
return true;
}
else
{
return false;
}
}
private boolean copyDB() {
try {
FileOutputStream out = new FileOutputStream(DB_PATH);
InputStream in =main_context.getAssets().open(DB_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0)
{
out.write(buffer , 0, ch);
}
out.flush();
out.close();
in.close();
return true;
} catch (Exception e) {
Log.i("amirmessage", "error in 84 -> " + e.toString());
return false;
}
}
public void open()
{
if (db_exist())
{
try {
File temp = new File(DB_PATH);
db =SQLiteDatabase.openDatabase(temp.getAbsolutePath() , null , SQLiteDatabase.OPEN_READWRITE);
}catch (Exception e) {
Log.i("amirmessage", "error in 100 -> " + e.toString());
}
}
else {
if (copyDB())
{
open();
}
}
}
@Override
public synchronized void close() {
db.close();
}
//---------
public List<HashMap<String , Object>> getresultOfSerach()
{
Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS ,null);
List<HashMap<String , Object>> all_data = new ArrayList<>();
try {
while ( result.moveToNext())
{
HashMap<String , Object> temp = new HashMap<>();
temp.put("id" , result.getString(0));
temp.put("content" , result.getString(2));
temp.put("title" , result.getString(1));
all_data.add(temp);
Log.d("update","Query: ");
}
} finally
{
result.close();
}
return all_data;
}
public void addcontent(String state, String title)
{
ContentValues cv = new ContentValues();
cv.put("content", state);
cv.put("title", title);
db = this.getWritableDatabase();
db.insert(DB_TBL_BOOKS,null,cv);
Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();
}
}
显示信息的主要活动代码在这里
public class Main2Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private databaseHandler db;
private ListView resultListView;
private List<HashMap<String , Object>> resultsbooks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getBaseContext(),addcontent.class);
startActivity(i);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
resultListView = (ListView) findViewById(R.id.catListview);
db = new databaseHandler(getBaseContext());
showresultOfSerarch();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onbtnfind()
{
resultListView.setAdapter(null);
String serachBy;
serachBy = "author";
String query =" ";
showresultOfSerarch();
}
public void showresultOfSerarch()
{
db.open();
resultsbooks = db.getresultOfSerach();
db.close();
String[] from = {"title","content"};
int[] to = {R.id.txttitle, R.id.txtcontent};
SimpleAdapter adp = new SimpleAdapter(
getBaseContext(), resultsbooks, R.layout.tbl_contest_row, from, to
);
resultListView.setAdapter(adp);
}
公共类Main2活动扩展了AppCompative活动
实现NavigationView.OnNavigationItemSelectedListener{
专用数据库处理程序数据库;
私有列表视图resultListView;
私人列表结果书;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
意向i=新意图(getBaseContext(),addcontent.class);
星触觉(i);
}
});
抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
ActionBarDrawerToggle切换=新建ActionBarDrawerToggle(
这,抽屉,工具栏,R.string.navigation\u drawer\u open,R.string.navigation\u drawer\u close);
抽屉。设置抽屉定位器(开关);
toggle.syncState();
NavigationView NavigationView=(NavigationView)findViewById(R.id.nav_视图);
navigationView.setNavigationItemSelectedListener(此);
resultListView=(ListView)findViewById(R.id.catListview);
db=新的databaseHandler(getBaseContext());
showResultToSerarch();
}
@凌驾
public void onBackPressed(){
抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
if(抽屉isDrawerOpen(重力压缩机启动)){
抽屉。关闭抽屉(重力压缩机启动);
}否则{
super.onBackPressed();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main2,菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
@SuppressWarnings(“StatementWithEmptyBody”)
@凌驾
公共布尔值onNavigationItemSelected(MenuItem项){
//处理导航视图项单击此处。
int id=item.getItemId();
if(id==R.id.nav_摄像机){
//处理相机的动作
}否则如果(id==R.id.nav_画廊){
}else if(id==R.id.nav_幻灯片){
}else if(id==R.id.nav_manage){
}else if(id==R.id.nav_共享){
}else if(id==R.id.nav_send){
}
抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
抽屉。关闭抽屉(重力压缩机启动);
返回true;
}
公共无效onbtnfind()
{
resultListView.setAdapter(null);
弦塞拉奇比;
serachBy=“作者”;
字符串查询=”;
showResultToSerarch();
}
公开作废showresultOfSerarch()
{
db.open();
resultsbooks=db.getresultOfSerach();
db.close();
字符串[]from={“title”,“content”};
int[]to={R.id.txttitle,R.id.txtcontent};
SimpleAdapter adp=新SimpleAdapter(
getBaseContext(),resultsbooks,R.layout.tbl_竞赛_行,从,到
);
resultListView.setAdapter(adp);
}
}你做得对,但错了 你能更改你的类文件吗 根据您的字段ID进行更改
public class AddContent extends AppCompatActivity
{
private DatabaseHandler db;
public String title1;
public String content;
EditText etcontent;
EditText ettitle1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_content);
db = new DatabaseHandler(getBaseContext());
// sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Button btn_add = (Button) findViewById(R.id.btn_add);
etcontent = (EditText) findViewById(R.id.edt_text1);
ettitle1 = (EditText) findViewById(R.id.edt_text2);
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
title1 = ettitle1.getText().toString();
content = etcontent.getText().toString();
onbtnadd(v);
}
});
}
public void onbtnadd(View v) {
db.open();
db.addcontent(content, title1);
db.close();
}
您可以将return添加到
addcontent
而不是void方法,以了解插入是否有效
public float addcontent(String state, String title)
{
float insert_result = 0.0f;
ContentValues cv = new ContentValues();
cv.put("content", state);
cv.put("title", title);
db = this.getWritableDatabase();
insert_result = db.insert(DB_TBL_BOOKS,null,cv);
Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();
return insert_result;
}
然后您可以调用它,并在onClick事件中获得如下值
public void onbtnadd(View v) {
title1 = ettitle1.getText().toString();
content = etcontent.getText().toString();
db.open();
float result = db.addcontent(content, title1);
if(result>0){
Toast.makeText(main_context,"Insert Successful!" , Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(main_context,"Insert Failed!" , Toast.LENGTH_SHORT).show();
}
db.close();
}
public void showData() {
db.getresultOfSerach();
}
更新
要读取数据库,请创建如下方法
/*
Prepare BD To Read
*/
private void read() {
if (db != null) {
if (!db.isOpen()) {
db = getReadableDatabase();
}
} else {
db = getReadableDatabase();
}
}
然后编辑getresultOfSerach()
以显示数据
public List<HashMap<String , Object>> getresultOfSerach()
{
read();
Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS ,null);
List<HashMap<String , Object>> all_data = new ArrayList<>();
String id = "";
String contact = "";
String title = "";
try {
if(result!=null) {
while (result.moveToNext()) {
HashMap<String, Object> temp = new HashMap<>();
id = result.getString(0);
contact = result.getString(2);
title = result.getString(1);
temp.put("id", id);
temp.put("content", contact);
temp.put("title", title);
all_data.add(temp);
Log.e("data ", id + "-"+ contact +"-"+ title);
}
}
} finally
{
result.close();
}
return all_data;
}
首先我想说的是,请遵循编码准则 您没有设置显示“word”表中插入的数据 您的数据插入逻辑工作正常。 在“word”表中添加数据后,请尝试读取值。您可以对读取的值进行以下更改
public void onbtnadd() {
db.open();
db.addcontent(content, title1);
Cursor cursor = db.getReadableDatabase().rawQuery("select * from word", null);
if (cursor.moveToFirst()) {
do {
// get all records inserted in 'word' table here
} while (cursor.moveToNext());
}
db.close();
}
显示logcat pleaselog不显示任何内容,即使未显示错误是否有任何异常?不,不存在问题中的解决方案,它应该是一个没有任何解决迹象的问题,相反,要么用绿色复选标记有用的答案,要么传递你自己的答案。你的错误是在oncreate时间获取值。。因此,请更改BTN单击时间,然后正常工作。检查它,但不工作,Listview不显示任何内容。调试它获取db.GetResultTofsSerach()返回列表大小检查内部值或不遵循此链接清除CRUD(创建、读取、更新和删除)插入成功!但是什么也没有显示
public void onbtnadd() {
db.open();
db.addcontent(content, title1);
Cursor cursor = db.getReadableDatabase().rawQuery("select * from word", null);
if (cursor.moveToFirst()) {
do {
// get all records inserted in 'word' table here
} while (cursor.moveToNext());
}
db.close();
}