gpt4 book ai didi

java - 在 sqlite 数据库中插入信息不起作用

转载 作者:搜寻专家 更新时间:2023-10-30 23:34:25 25 4
gpt4 key购买 nike

已经存储在数据库中的文本显示没有任何问题。但是新插入的数据没有显示。我认为“添加新文本不会显示任何内容,就好像没有执行插入操作一样。”。我不知道为什么它不起作用。请帮助...

我的 DatabaseHandler 类

 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();

}
}

我的 Activity 插入代码在这里

public class addcontent extends AppCompatActivity 

{

private databaseHandler db;
public String title1;
public String content;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
db = new databaseHandler(getBaseContext());
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

EditText etcontent = (EditText)findViewById(R.id.editText);
EditText ettitle1 = (EditText)findViewById(R.id.editText2);

title1=ettitle1.getText().toString();
content=etcontent.getText().toString();


}

public void onbtnadd(View v)
{

db.open();
db.addcontent( content,title1);

db.close();

}
}

我显示信息的 MainActivity 代码在这里

 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);
}

最佳答案

首先我想说的是,请遵循编码指南。

您没有准备显示插入“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();
}

关于java - 在 sqlite 数据库中插入信息不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com