简体   繁体   中英

Check and Retrieve Data from SQLite

I am using a SQLite DB in my app. I have a function that writes data into the database. The code is as follows

                c.put("Name",name.getText().toString());
                c.put("Mail", mail.getText().toString());
                c.put("Contact", contact.getText().toString());
                mail.setText("");
                contact.setText("");
                Boolean check=mydb.insertContact(c);

Here is the insertContact function

    public boolean insertContact(ContentValues contentValues)
    {
         SQLiteDatabase db = this.getWritableDatabase();
         db.insert("sports", null, contentValues);
         return true;
    }

My question is, Is there any way to check if my data has been inserted into the DB? This function always returns true so I don't know if my data has been inserted successfully.

Now I have a function that retrieves all the data from the DB. The code is as follows

       allusers.setOnClickListener(new View.OnClickListener(){
       @Override
       public void onClick(View v) {
            String textarr[] =new String[10];
            textarr= mydb.getyourdata();
            int i = 0;
            while (i <= textarr.length) {
            String text=textarr[i];
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
       }}});

mydb is the SQL handler. This is the getyourdata() function

public String[]  getyourdata(){
    String selectQuery = "SELECT  * FROM " + CONTACTS_TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    String[] data = null;
    int i=0;
    if (cursor.moveToFirst()) {
        do {
            data[i]=cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_NAME));
            i++; 
        } while (cursor.moveToNext());
    }
    db.close();
    return data;
}

The compiler is showing null pointer exception in this line

           while (i <= textarr.length) 

I have no idea of how to solve this. Please help me. This is my DB table structure (Name varchar(50),Mail varchar(50),Contact varchar(15),Location varchar(30))

Thanks in advance.

-1 is returned if error occurred. .insert(...) returns the row id of the new inserted record.

for more help try SQLite.insert return -1 but data inserted into database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM