已经存储在数据库中的文本显示没有任何问题。但新的插入数据没有显示。我认为“通过添加新文本不会显示任何内容,就像没有执行插入操作一样。”我不知道为什么它不起作用。请帮忙......
我的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();
}
}
我的活动插入代码在这里
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);
}
}
答案 0 :(得分:1)
首先,我想说,请遵循编码指南。
您没有规定显示插入&#39; word&#39;表
您的数据插入逻辑工作正常。 将数据添加到&#39; word&#39;表,尝试阅读价值观。您可以进行以下更改以读取值。
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();
}
答案 1 :(得分:0)
你做得对,但错了。
你可以改变你的班级档案
根据你的字段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();
}
答案 2 :(得分:0)
您可以添加返回10M
而不是void方法,以了解插入是否有效..
addcontent
然后你可以调用它并获得像这样的onClick事件的价值
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;
}
要读取数据库,请创建一个类似
的方法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();
}
然后修改您的/*
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;
}