如何在此数据库应用程序中删除删除后插入的数据?

时间:2011-08-27 04:39:30

标签: android database android-layout android-emulator cursor

在这个项目中,所有功能都能很好地接受删除并显示所有数据。 一旦我删除了记录,之后如果我要插入它,那么它将被插入但我无法看到它。我认为它是在一些先前的索引值之后插入的。所以请告诉我删除所有记录并显示所有记录的错误。 我正在使用光标。我不知道如何通过光标删除和显示所有记录。请告诉我你错在哪里。 项目代码在这里:

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;
    }
}

另一个档案在这里:

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();
        }
    }
}

请帮我解决这个问题。

2 个答案:

答案 0 :(得分: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();
            }


        }
    });

<强>更新

当你需要删除所有不需要检查其他选项时。只需要调用删除

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();
        }
    });

<强>更新

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;
    }

<强>更新

你已经使用了sqlite自动增量字段。所以它会永远增加,直到它超过最大值。假设你删除了10条记录。如果你下次插入id将是11.它不会从1开始。查看official个文档

答案 1 :(得分:1)

如果将数据插入表中,则表上已打开的游标可能会也可能不会看到新添加的数据。如果关闭,重新打开并适当地重新定位光标,您应该看到新数据。