Данные вставляются в базу данных SQLite Android, но не отображаются - PullRequest
0 голосов
/ 26 декабря 2018

Я пытаюсь вставить некоторые значения в реальном времени, полученные от пользователя, и пытаюсь передать их в БД SQLite.Данные вставляются успешно, но когда я перехожу к следующему действию, нажимая кнопку «Показать данные», я получаю пустые значения.

Хотя я вижу, что если я продолжу добавлять значения ... списокпродолжает увеличиваться.

Это код для моего класса DataHelper

public class DataBaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "contact.db";
public static final String TABLE_NAME = "contact_table";

public static final String col_id = "ID";
public static final String col_name = "Name";
public static final String col_contact = "Contact";

public DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    String sql_query = "CREATE TABLE " + TABLE_NAME + "("
            + col_id + " INTEGER PRIMARY KEY," + col_name + " TEXT,"
            + col_contact + " TEXT" + ")";
    sqLiteDatabase.execSQL(sql_query);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(sqLiteDatabase);
}

public boolean insertdata(String name, String contact) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(col_name, name);
    contentValues.put(col_contact, contact);
    long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
    sqLiteDatabase.close();
    // To check whether data is inserted or not
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

public Cursor getAllData() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery("Select * from " + TABLE_NAME, null);
    return res;
}
}

Теперь у меня есть функция ClickMe () , которую я вызываю в моем OnClickListener of Кнопка вставки

     private void ClickMe() {
    String NAME = name.getText().toString();
    String CONTACT = contact.getText().toString();
    Boolean result = dataBaseHelper.insertdata(NAME,CONTACT);
    if (result==true){
        Toast.makeText(this, "Data Inserted", Toast.LENGTH_SHORT).show();
        Log.d(NAME,"");
        Log.d(CONTACT,"");
    }
    else {
        Toast.makeText(this, "Sorry", Toast.LENGTH_SHORT).show();
    }
}

Я получаю тост за Данные вставлены успешно .Переход к следующему следующему действию:

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           Clickme();
        }
    });

Код этого Clickme () :

 private void Clickme() {
     res = dataBaseHelper.getAllData();
    StringBuffer stringBuffer = new StringBuffer();
    if(res!= null && res.getCount()>0){
        while (res.moveToNext()){
            stringBuffer.append("Name: " + res.getString(1)+"\n");
            stringBuffer.append("Contact: " + res.getString(2)+"\n"+"\n");
        }
        name_tv.setText(stringBuffer.toString());
        Toast.makeText(this, "Data Retrieved Successfully", Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(this, "No Data to retrieve", Toast.LENGTH_SHORT).show();
    }
}

В результате ... Я получаю пустые значения для Имя и Контакты .Я пытаюсь выяснить, почему я не получаю отображаемые значения, хотя они вставляются.

Можете ли вы, ребята, помочь мне с этим .. ??

Также, если есть какие-то лучшепуть, чем это ... тогда, пожалуйста, предложите мне.Спасибо .. !!

Это отчет LOGCAT

2018-12-28 10:37:25.633 24721-24721/? I/e.mishr.locall: Late-enabling -Xcheck:jni
2018-12-28 10:37:25.699 24721-24741/com.example.mishr.locally I/e.mishr.locall: The ClassLoaderContext is a special shared library.
2018-12-28 10:37:25.719 24721-24721/com.example.mishr.locally I/e.mishr.locall: The ClassLoaderContext is a special shared library.
2018-12-28 10:37:25.782 24721-24721/com.example.mishr.locally I/Perf: Connecting to perf service.
2018-12-28 10:37:25.784 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:25.784 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:25.771 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232127): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:25.771 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232128): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:25.789 24721-24721/com.example.mishr.locally V/Font: Change font:2
2018-12-28 10:37:25.918 24721-24721/com.example.mishr.locally W/e.mishr.locall: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2018-12-28 10:37:25.919 24721-24721/com.example.mishr.locally W/e.mishr.locall: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2018-12-28 10:37:25.922 24721-24721/com.example.mishr.locally D/OpenGLRenderer: Skia GL Pipeline
2018-12-28 10:37:25.931 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:25.931 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:25.921 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232129): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:25.941 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232131): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:25.950 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:25.950 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:25.941 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232132): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:25.969 24721-24740/com.example.mishr.locally D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@55c8017[Splash_Screen]
2018-12-28 10:37:25.971 24721-24748/com.example.mishr.locally I/Adreno: QUALCOMM build                   : 0bf40b0, I486bafd568
Build Date                       : 08/22/18
OpenGL ES Shader Compiler Version: EV031.25.03.00
Local Branch                     : 
Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.3.R1.08.00.00.423.039
Remote Branch                    : NONE
Reconstruct Branch               : NOTHING
2018-12-28 10:37:25.971 24721-24748/com.example.mishr.locally I/Adreno: Build Config                     : S P 6.0.3 AArch64
2018-12-28 10:37:25.961 24721-24721/com.example.mishr.locally W/RenderThread: type=1400 audit(0.0:1232133): avc: denied { search } for name="proc" dev="debugfs" ino=15670 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0
2018-12-28 10:37:25.975 24721-24748/com.example.mishr.locally I/Adreno: PFP: 0x016ee170, ME: 0x00000000
2018-12-28 10:37:25.978 24721-24748/com.example.mishr.locally I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 1
2018-12-28 10:37:25.978 24721-24748/com.example.mishr.locally I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2018-12-28 10:37:25.978 24721-24748/com.example.mishr.locally I/OpenGLRenderer: Initialized EGL, version 1.4
2018-12-28 10:37:25.979 24721-24748/com.example.mishr.locally D/OpenGLRenderer: Swap behavior 2
2018-12-28 10:37:29.950 24721-24721/com.example.mishr.locally W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@86875ed
2018-12-28 10:37:29.961 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232134): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:29.975 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:29.976 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:29.971 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232136): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:30.050 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:30.050 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:30.041 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232138): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:30.097 24721-24740/com.example.mishr.locally D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@d5feb4a[MainActivity]
2018-12-28 10:37:30.202 24721-24721/com.example.mishr.locally I/AssistStructure: Flattened final assist data: 3740 bytes, containing 1 windows, 13 views
2018-12-28 10:37:43.957 24721-24740/com.example.mishr.locally D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@d5feb4a[MainActivity]
2018-12-28 10:37:44.051 24721-24721/com.example.mishr.locally W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@52ed6aa
2018-12-28 10:37:44.069 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:44.070 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:44.061 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232141): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:44.070 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:44.061 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232144): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:44.097 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:44.097 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:44.091 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232145): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:44.125 24721-24740/com.example.mishr.locally D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@1dea0f1[Home_Activity]
2018-12-28 10:37:45.711 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232147): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0
2018-12-28 10:37:45.720 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable"
2018-12-28 10:37:45.721 24721-24721/com.example.mishr.locally E/libc: Access denied finding property "vendor.perf.iop_v3.enable.debug"
2018-12-28 10:37:45.711 24721-24721/com.example.mishr.locally W/e.mishr.locally: type=1400 audit(0.0:1232148): avc: denied { read } for name="u:object_r:vendor_iop_prop:s0" dev="tmpfs" ino=15852 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:vendor_iop_prop:s0 tclass=file permissive=0

Ответы [ 2 ]

0 голосов
/ 26 декабря 2018

Пожалуйста, замените следующий код для вашего метода getAllData.

public Cursor getAllData() {
    Cursor cursor = this.database.query(TABLE_NAME , new String[]{col_id, col_name , col_contact }, null, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
    }
    return cursor;
}

Обновление: ваш col_id равен INTEGER PRIMARY KEY , и вы не вводите никакого значения, поэтому необходимо использовать автоинкрементный первичный ключ , используя следующий код в методе onCreate. После изменения удалите приложение (так как БД уже создана, поэтому вам нужны свежие БД, потому что вы изменили свойство столбца) и попробуйте, надеюсь, этобудет работать

String sql_query = "CREATE TABLE " + TABLE_NAME + "("
            + col_id + " INTEGER PRIMARY KEY AUTOINCREMENT," + col_name + " TEXT,"
            + col_contact + " TEXT" + ")";
    sqLiteDatabase.execSQL(sql_query);
0 голосов
/ 26 декабря 2018

Обновите вашу Clickme функцию следующим образом:

private void Clickme() {
     res = dataBaseHelper.getAllData();
    StringBuffer stringBuffer = new StringBuffer();
    if(res!= null && res.getCount() > 0 && res.moveToFirst()){
       do {
            stringBuffer.append("Name: " + res.getString(1)+"\n");
            stringBuffer.append("Contact: " + res.getString(2)+"\n"+"\n");
        } while (res.moveToNext());

        name_tv.setText(stringBuffer.toString());
        Toast.makeText(this, "Data Retrieved Successfully", Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(this, "No Data to retrieve", Toast.LENGTH_SHORT).show();
    }
}

Я добавил дополнительное условие в ваш if блок: res.moveToFirst() и изменил ваш цикл while на do-while

Если вам интересно, почему я добавил moveToFirst, См. Эту ссылку SO ;Кроме того, не забудьте закрыть курсор , вызвав res.close()

РЕДАКТИРОВАТЬ:

Возможно, проблема в вашей функции вставки:

Вы вставляете Name и Contact, но в вашем ContentValues нет Id:

Ваш метод вставки:

SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col_name, name);
contentValues.put(col_contact, contact);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);

ПосколькуВы упомянули, Id как Первичный ключ , и для него нет значения, данные никогда не вставляются.

Теперь у вас есть два способа исправить этоПроблема:

  1. Измените запрос создания таблицы, добавив AUTOINCREMENT со следующим:

    String sql_query = "CREATE TABLE " + TABLE_NAME + "(" + col_id + " INTEGER PRIMARY KEY AUTOINCREMENT," + col_name + " TEXT," + col_contact + " TEXT" + ")";

  2. Добавить еще один ключ, вставляя в ContentValues:

    contentValues.put(col_id, 1);

Я бы предложил, перейдите с Вариант 1

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...