Не получается достать данные из базы данных
Я создала базу данных SQLite, но не получается достать данные из этой базы, когда нажимаю на кнопку, приложение вылетает.
java:
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText name, contact, dob;
DBHelper DB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
contact = findViewById(R.id.contact);
dob = findViewById(R.id.dob);
Button insert = (Button) findViewById(R.id.btnInsert);
Button view = (Button) findViewById(R.id.view);
DB = new DBHelper(this);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String nameTXT = name.getText().toString();
String contactTXT = contact.getText().toString();
String dobTXT = dob.getText().toString();
Boolean checkinsertdata = DB.insertuserdata(nameTXT, contactTXT, dobTXT);
if (checkinsertdata == true) {
Toast.makeText(MainActivity.this, "New Entry Inserted", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "New Entry Not Inserted", Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Cursor res = DB.getdata();
if (res.getCount() == 0) {
Toast.makeText(MainActivity.this, "No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Name : " + res.getString(0) + "\n");
buffer.append("Contact : " + res.getString(1) + "\n");
buffer.append("Date of Birth : " + res.getString(2) + "\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("User Entries");
builder.setMessage(buffer.toString());
builder.show();
}
});
}
}
DBHelper:
package com.example.myp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "Userdata.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create Table USerDeatils(name TEXT primary key, contact TEXT, dob TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
DB.execSQL("drop Table if exists Userdeatils");
}
public Boolean insertuserdata(String name, String contact, String dob) {
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("contact", contact);
contentValues.put("dob", dob);
long result = DB.insert("Userdetails", null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Boolean updateuserdata(String name, String contact, String dob) {
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("contact", contact);
contentValues.put("dob", dob);
Cursor cursor = DB.rawQuery("Select DISTINCT Userdetails where name = ?", new String[]{name}); // from instead of all
if (cursor.getCount() > 0) {
long result = DB.update("Userdetails", contentValues, "name=?", new String[]{name});
if (result == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public Boolean deleteuserdata(String name) {
SQLiteDatabase DB = this.getWritableDatabase();
Cursor cursor = DB.rawQuery("Select ALL Userdetails where name = ?", new String[]{name});
if (cursor.getCount() > 0) {
long result = DB.delete("Userdetails", "name=?", new String[]{name});
if (result == -1) {
return false;
} else {
return true;
}
} else{
return false;
}
}
public Cursor getdata() {
SQLiteDatabase DB = this.getWritableDatabase();
Cursor cursor = DB.rawQuery("Select DISTINCT Userdetails", null); // ALL
return cursor;
}
}
Logcat:
2021-08-10 10:36:33.175 12720-12720/? I/com.example.my: Not late-enabling -Xcheck:jni (already on)
2021-08-10 10:36:33.213 12720-12720/? E/com.example.my: Unknown bits set in runtime_flags: 0x8000
2021-08-10 10:36:33.213 12720-12720/? W/com.example.my: Unexpected CPU variant for X86 using defaults: x86
2021-08-10 10:36:34.148 12720-12752/com.example.myp D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
2021-08-10 10:36:34.135 12720-12720/com.example.myp W/RenderThread: type=1400 audit(0.0:53): avc: denied { write } for name="property_service" dev="tmpfs" ino=883 scontext=u:r:untrusted_app:s0:c133,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 app=com.example.myp
2021-08-10 10:36:34.152 12720-12752/com.example.myp W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
2021-08-10 10:36:34.349 12720-12752/com.example.myp D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2021-08-10 10:36:34.410 12720-12752/com.example.myp D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2021-08-10 10:36:34.435 12720-12752/com.example.myp D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2021-08-10 10:36:34.938 12720-12720/com.example.myp W/com.example.my: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2021-08-10 10:36:34.939 12720-12720/com.example.myp W/com.example.my: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2021-08-10 10:36:35.455 12720-12750/com.example.myp D/HostConnection: HostConnection::get() New Host Connection established 0xd6569190, tid 12750
2021-08-10 10:36:35.457 12720-12750/com.example.myp D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0
2021-08-10 10:36:35.470 12720-12750/com.example.myp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2021-08-10 10:36:35.473 12720-12750/com.example.myp D/EGL_emulation: eglCreateContext: 0xd651a1e0: maj 3 min 0 rcv 3
2021-08-10 10:36:35.476 12720-12750/com.example.myp D/EGL_emulation: eglMakeCurrent: 0xd651a1e0: ver 3 0 (tinfo 0xd650f370)
2021-08-10 10:36:35.511 12720-12750/com.example.myp W/Gralloc3: mapper 3.x is not supported
2021-08-10 10:36:35.528 12720-12750/com.example.myp D/HostConnection: createUnique: call
2021-08-10 10:36:35.528 12720-12750/com.example.myp D/HostConnection: HostConnection::get() New Host Connection established 0xd6569410, tid 12750
2021-08-10 10:36:35.542 12720-12750/com.example.myp D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0
2021-08-10 10:36:35.544 12720-12750/com.example.myp D/eglCodecCommon: allocate: Ask for block of size 0x1000
2021-08-10 10:36:35.545 12720-12750/com.example.myp D/eglCodecCommon: allocate: ioctl allocate returned offset 0x3ffff4000 size 0x2000
2021-08-10 10:36:35.608 12720-12750/com.example.myp D/EGL_emulation: eglMakeCurrent: 0xd651a1e0: ver 3 0 (tinfo 0xd650f370)
2021-08-10 10:36:37.601 12720-12720/com.example.myp I/AssistStructure: Flattened final assist data: 2244 bytes, containing 1 windows, 13 views
2021-08-10 10:36:45.976 12720-12720/com.example.myp E/SQLiteLog: (1) no such table: Userdetails
2021-08-10 10:36:45.979 12720-12720/com.example.myp E/SQLiteDatabase: Error inserting dob=lll name=ll contact=lll
android.database.sqlite.SQLiteException: no such table: Userdetails (code 1 SQLITE_ERROR): , while compiling: INSERT INTO Userdetails(dob,name,contact) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1597)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1468)
at com.example.myp.DBHelper.insertuserdata(DBHelper.java:38)
at com.example.myp.MainActivity$1.onClick(MainActivity.java:40)
at android.view.View.performClick(View.java:7125)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2021-08-10 10:36:46.248 12720-12750/com.example.myp D/EGL_emulation: eglMakeCurrent: 0xd651a1e0: ver 3 0 (tinfo 0xd650f370)
2021-08-10 10:36:46.286 12720-12750/com.example.myp D/EGL_emulation: eglMakeCurrent: 0xd651a1e0: ver 3 0 (tinfo 0xd650f370)
2021-08-10 10:36:53.709 12720-12720/com.example.myp E/SQLiteLog: (1) no such column: Userdetails
2021-08-10 10:36:53.710 12720-12720/com.example.myp D/AndroidRuntime: Shutting down VM
--------- beginning of crash
2021-08-10 10:36:53.733 12720-12720/com.example.myp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myp, PID: 12720
android.database.sqlite.SQLiteException: no such column: Userdetails (code 1 SQLITE_ERROR): , while compiling: Select DISTINCT Userdetails
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1443)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1382)
at com.example.myp.DBHelper.getdata(DBHelper.java:86)
at com.example.myp.MainActivity$4.onClick(MainActivity.java:80)
at android.view.View.performClick(View.java:7125)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Ответы (1 шт):
Прежде чем что-то написать в БД, нужно создать таблицу. А именно: Userdetails, как сказано в ошибке android.database.sqlite.SQLiteException: no such table: Userdetails (code 1 SQLITE_ERROR): , while compiling: INSERT INTO Userdetails(dob,name,contact) VALUES (?,?,?)
В твоем DBHelper допиши что-то вроде:
public class DbHelper extends SQLiteOpenHelper {
public static final String SQL_CREATE_ENTRIES = "CREATE TABLE Userdetails ...";
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
}
Документация: https://developer.android.com/training/data-storage/sqlite#java
Update:
По новой ошибке android.database.sqlite.SQLiteException: no such column: Userdetails (code 1 SQLITE_ERROR): , while compiling: Select DISTINCT Userdetails
У тебя неправильно составлен query Select DISTINCT Userdetails where name = ? (и не только он).
Попробуй select distinct * from Userdetails where name = ?
или select distinct name, contact, dob from Userdetails where name = ?
Да и вообще не понятно, зачем тебе там курсор понадобился? Просто вытри его.
То же самое и с методом deleteuserdata, Select ALL Userdetails where name = ? неправильно и курсор там не нужен.