Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SQLite-插入新行时不更新表_Java_Android_Sqlite - Fatal编程技术网

Java SQLite-插入新行时不更新表

Java SQLite-插入新行时不更新表,java,android,sqlite,Java,Android,Sqlite,我正在尝试制作一个应用程序,允许用户添加联系人,然后预览他们。我正在使用SQLite在本地保存数据。我已经为我的数据库创建了一个SQLHelper,但是当我尝试选择all时,它会显示任何数据 SQLHelper package com.freelancer.camelo.contacts; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; i

我正在尝试制作一个应用程序,允许用户添加联系人,然后预览他们。我正在使用SQLite在本地保存数据。我已经为我的数据库创建了一个SQLHelper,但是当我尝试选择all时,它会显示任何数据

SQLHelper

package com.freelancer.camelo.contacts;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyContactsDb.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_NAME = "name";
    public static final String CONTACTS_COLUMN_SURNAME = "surname";
    public static final String CONTACTS_COLUMN_ADDRESS = "address";
    public static final String CONTACTS_COLUMN_POSTAL = "postal";
    public static final String CONTACTS_COLUMN_PHONE = "phone";
    private HashMap hp;

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, name text,surname text,phone text, address text,postal text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact (String name, String surname, String phone, String address,String postal) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(CONTACTS_COLUMN_NAME, name);
        contentValues.put(CONTACTS_COLUMN_SURNAME, surname);
        contentValues.put(CONTACTS_COLUMN_PHONE, phone);
        contentValues.put(CONTACTS_COLUMN_ADDRESS, address);
        contentValues.put(CONTACTS_COLUMN_POSTAL, postal);
        db.insert("contacts", null, contentValues);
        return true;
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
        return res;
    }

    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
        return numRows;
    }

    public boolean updateContact (Integer id, String name, String surname, String phone, String address,String postal) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(CONTACTS_COLUMN_NAME, name);
        contentValues.put(CONTACTS_COLUMN_SURNAME, surname);
        contentValues.put(CONTACTS_COLUMN_PHONE, phone);
        contentValues.put(CONTACTS_COLUMN_ADDRESS, address);
        contentValues.put(CONTACTS_COLUMN_POSTAL, postal);
        db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteContact (Integer id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contacts",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }

    public ArrayList<String> getAllContacts() {
        ArrayList<String> array_list = new ArrayList<>();

        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT * FROM "+CONTACTS_TABLE_NAME;
        Cursor res =  db.rawQuery( selectQuery, null );
        res.moveToFirst();

        while(!res.isAfterLast()){
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
            res.moveToNext();
        }
        return array_list;
    }
}




这是我试图检索数据的时候

ArrayList<String> contactsArrayList = mydb.getAllContacts();

        if (contactsArrayList.size() == 0) {
            Toast.makeText(this, "DB is empty", Toast.LENGTH_SHORT).show();
        } else {
            for (int i = 0; i < contactsArrayList.size(); i++) {
                Toast.makeText(this, contactsArrayList.get(i).toString(), Toast.LENGTH_SHORT).show();
            }
        }

ArrayList contactsArrayList=mydb.getAllContacts();
如果(contactsArrayList.size()==0){
Toast.makeText(这个“DB为空”,Toast.LENGTH_SHORT.show();
}否则{
对于(int i=0;i

每次我运行该活动时,它都会发出“DB为空”的祝酒声。

这是一个示例,希望您的DB模式是正确的。
I've modified your code a little bit:

public ArrayList<String> getAllContacts() {
    ArrayList<String> array_list = new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery = "SELECT * FROM "+CONTACTS_TABLE_NAME;
    Cursor res =  db.rawQuery( selectQuery, null );

    //check if data exist, proceed
    if (res.moveToNext()){
        do{
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
        }while(res.moveToNext());
    }

    //remember to close cursor after use
    res.close();

    return array_list;
}


//void instead of boolean
public void insertContact (String name, String surname, String phone, String address,String postal) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(CONTACTS_COLUMN_NAME, name);
    contentValues.put(CONTACTS_COLUMN_SURNAME, surname);
    contentValues.put(CONTACTS_COLUMN_PHONE, phone);
    contentValues.put(CONTACTS_COLUMN_ADDRESS, address);
    contentValues.put(CONTACTS_COLUMN_POSTAL, postal);

    //throw if not inserted
    db.insertOrThrow("contacts", "", contentValues);
}
此方法属于扩展SqkiteDatabase的类

    //-----------------------------------------------------------------------------------------------------
public boolean insertNote(NoteModel noteModel) {
    if (LOG_DEBUG) UtilLogger.showLogInsert(TAG, noteModel);

    try {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
        contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
        contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
        contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
        contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
        contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
        contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
        contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
        contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
        contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
        contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());

        long rowId = mSqLiteDatabase.insert(DBSchema.DB_TABLE_NAME, null, contentValues);
        if (LOG_DEBUG) Log.w(TAG, " insert Done :  at row Id: " + rowId);

        return true;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}

我认为您需要检查表是否已创建,数据是否存在,然后才能检索。为此,您只需按照链接并在emulator中查看数据

如果它正常工作,那么我认为您的检索数据代码没有问题。

使用
insertOrThrow()
而不是
insert()
来检测插入问题。
try {
    mydb.insertContact("one", "two", "three", "foir", "five");
}catch(Exception e){
    Toast.makeText(context, "Insert Failed: " + e.toString(), Toast.LENGTH_SHORT).show();
    }
    //-----------------------------------------------------------------------------------------------------
public boolean insertNote(NoteModel noteModel) {
    if (LOG_DEBUG) UtilLogger.showLogInsert(TAG, noteModel);

    try {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
        contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
        contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
        contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
        contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
        contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
        contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
        contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
        contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
        contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
        contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());

        long rowId = mSqLiteDatabase.insert(DBSchema.DB_TABLE_NAME, null, contentValues);
        if (LOG_DEBUG) Log.w(TAG, " insert Done :  at row Id: " + rowId);

        return true;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}