0

In this project all the functionality works good accept delete and display all data. Once if i delete the record and after that if I am going to insert it, then it will inserted but I am not able to see it. I think it is inserted after some previous index value. So please tell me where I am wrong to delete all the records and display all records. I am using cursor for it. and I don't know how to delete and display all the record by cursor. Please give me your view that where I am wrong. The project code is here :

package com.example.databaseExample2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter 
{
    public static final String KEY_ROWID = "_id";
    public static final String KEY_ISBN = "isbn";
    public static final String KEY_TITLE = "title";
    public static final String KEY_PUBLISHER = "publisher";    
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "test";
    private static final String DATABASE_TABLE = "titles";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE =
        "create table titles (_id integer primary key autoincrement, "
        + "isbn text not null, title text not null, " 
        + "publisher text not null);";

    private final Context context; 

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) 
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper 
    {
        DatabaseHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            db.execSQL(DATABASE_CREATE);
        }

        @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 titles");
            onCreate(db);
        }
    }    

    //---opens the database---
    public DBAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---    
    public void close() 
    {
        DBHelper.close();
    }

    //---insert a title into the database---
    public long insertTitle(String isbn, String title, String publisher) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ISBN, isbn);
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_PUBLISHER, publisher);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular title---
    public boolean deleteTitle(long rowId) 
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

//    public boolean deleteAllTitle()
//    {
//      return db.delete(DATABASE_TABLE,null, null);
//    }

    //---retrieves all the titles---
    public Cursor getAllTitles() 
    {
        Cursor mCursor = db.query(DATABASE_TABLE, new String[] {
                KEY_ROWID, 
                KEY_ISBN,
                KEY_TITLE,
                KEY_PUBLISHER}, 
                null, 
                null, 
                null, 
                null, 
                null);
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //---retrieves a particular title---
    public Cursor getTitle(long rowId) throws SQLException 
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {
                        KEY_ROWID,
                        KEY_ISBN, 
                        KEY_TITLE,
                        KEY_PUBLISHER
                        }, 
                        KEY_ROWID + "=" + rowId, 
                        null,
                        null, 
                        null, 
                        null, 
                        null);
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    public void deleteAll()
    {
        this.db.delete(DATABASE_TABLE, null, null);
    }

    //---updates a title---
    public boolean updateTitle(long rowId, String isbn, 
    String title, String publisher) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_ISBN, isbn);
        args.put(KEY_TITLE, title);
        args.put(KEY_PUBLISHER, publisher);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

And another file is here:

package com.example.databaseExample2;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DatabaseActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // define resources
        final Button display_btn = (Button)findViewById(R.id.test_button);
        final EditText number = (EditText)findViewById(R.id.number);
        final Button insert = (Button)findViewById(R.id.insert);
        final Button delete = (Button)findViewById(R.id.delete);
        final Button allDisplay = (Button)findViewById(R.id.all);

        final DBAdapter db = new DBAdapter(this); // create new database

        allDisplay.setOnClickListener(new View.OnClickListener() 
        {

            public void onClick(View v) 
            {
                db.open();
                Cursor c = db.getAllTitles();
                if (c.moveToLast())        
                {
//                  for(int i=0;c.getCount()>0;i++ )
//                  {
                        DisplayTitle(c);
                    //}
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "No title found",   Toast.LENGTH_LONG).show();                  
                }
                db.close();

            }
        });

        delete.setOnClickListener(new View.OnClickListener() 
        {

            public void onClick(View v) 
            {
                db.open();
                Cursor c = db.getAllTitles();
                if(c.getCount()>0)
                {
                    db.deleteAll();
                }
                db.close();
                System.out.println("Record Delete.");
                Toast.makeText(getApplicationContext(), "Record Delete.", Toast.LENGTH_SHORT).show();
            }
        });


        insert.setOnClickListener(new View.OnClickListener() 
        {

            public void onClick(View v) 
            {
                //---add 2 titles---
                db.open();        
                long id;

                id = db.insertTitle("128","C-Programming","Dhiren");        
                id = db.insertTitle("256","Android","Shreyash");
                id = db.insertTitle("512","Android","Kandarp");
                id = db.insertTitle("1024","Android","Sweta");

                db.close();
                System.out.println("Record Inserted.");
                Toast.makeText(getApplicationContext(), "Record Inserted.", Toast.LENGTH_SHORT).show();

            }
        });


        display_btn.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                //---get a title---
                //String id1 = .toString();
                if(number.getText().toString().equals(""))
                {   
                    Toast.makeText(getApplicationContext(), "Please Enter Any Value...",    Toast.LENGTH_LONG).show();
                }
                else
                {

                    Integer id = (Integer)Integer.parseInt(number.getText().toString());
                    //System.out.println("The Id is:  "+id);
                    db.open();

                    Cursor c = db.getTitle(id);

                    if (c.moveToFirst())        
                    {
                        DisplayTitle(c);
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), "No title found",   Toast.LENGTH_LONG).show();                  
                    }
                    db.close();
                }
            }
        });

    }

    public void DisplayTitle(Cursor c)
    {
            Toast.makeText(this, 
                    "id: " + c.getString(0) + "\n" + "ISBN: " + c.getString(1) + "\n" +  "TITLE: " + c.getString(2) + "\n" +
                    "PUBLISHER:  " + c.getString(3),Toast.LENGTH_LONG).show();  
    }  
    public void DisplayAll(Cursor c)
    {
        for(int i = 0; c.getCount()!=0;i++)
        {
            Toast.makeText(this, 
                    "id: " + c.getString(0) + "\n" + "ISBN: " + c.getString(1) + "\n" +  "TITLE: " + c.getString(2) + "\n" +
                   "PUBLISHER:  " + c.getString(3),Toast.LENGTH_LONG).show();   
            c.moveToNext();
        }
    }
}

Please help me regarding this.

2
  • Any error you are getting ? Please paste your log-cat here
    – Dharmendra
    Aug 27, 2011 at 4:54
  • Thanks for reply. but I am not getting any errors, But the records are inserted after the some index that i have created before. Do one click on insert, then delete and then again insert the data. Now in second time the data are inserted after some index, So tell me where i am wrong ?? Aug 27, 2011 at 6:33

2 Answers 2

1
allDisplay.setOnClickListener(new View.OnClickListener() 
    {

        public void onClick(View v) 
        {
            db.open();
            Cursor c = db.getAllTitles();
            while(c.moveToNext())        
            {
              Toast.makeText(DatabaseActivity.this,c.getString(0),Toast.LENGTH_LONG).show();
            }


        }
    });

UpDate

when you need to delete all no need to check other option.Just have to call delete

delete.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) 
        {
            db.open();              

                db.deleteAll();              
            db.close();
            System.out.println("Record Delete.");
            Toast.makeText(getApplicationContext(), "Record Delete.", Toast.LENGTH_SHORT).show();
        }
    });

Update

public Cursor getAllTitles() 
    {
        Cursor mCursor = db.query(DATABASE_TABLE, new String[] {
                KEY_ROWID, 
                KEY_ISBN,
                KEY_TITLE,
                KEY_PUBLISHER}, 
                null, 
                null, 
                null, 
                null, 
                null);

        return mCursor;
    }

Update

You have used sqlite auto increment field.So it will be increased forever until it exceeds maximum value.Suppose you have deleted 10 records.If you insert next time the id will be 11.It won't start from 1.See official docs

13
  • Ok Thanks. let me check it. But what about the delete all data??? I think i have to use delete Table. But how i have to use it that is i don't know. Please let me know how to delete all data. Aug 27, 2011 at 5:57
  • Its works for me. But what about the delete all Data ?? Please help me for that also. Aug 27, 2011 at 6:02
  • Yes Thanks. But should i have to set the cursor to delete the all records ? And in your allDisply code i am not getting the first one record. Accept it, i got all record to be display. So please update the displayAll code. Aug 27, 2011 at 6:36
  • 1
    why to think cursor when deleting records.And yes you will not get first record because you just cross the first record when selecting.to get all record see updated answer
    – Rasel
    Aug 27, 2011 at 6:38
  • 1
    It depends.suppose you have id 1,2,3.Now you deleted 2.What is the next id you want, 2 or 4.If 4 you have to find the max(id) before inserting and have to insert by incrementing 1.If 2 then you have to write code to find the missing id in between.then insert record with the id.Friend, you have to write some codes
    – Rasel
    Aug 27, 2011 at 7:16
1

If you insert data into a table, a cursor that is already open on the table may or may not see the newly added data. If you close, reopen and reposition the cursor appropriately, you should see the new data.

1
  • Yes Thanks. But in My code if i delete it and then insert it again then it will stored after the index that is the last index of the previous deleted data. So am i wrong in inserting data ? or in set the cursor to insert the data ? Aug 27, 2011 at 6:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.