如何从listview中填充的SQLite中删除数据

时间:2015-05-11 06:04:06

标签: android sqlite listview

我想删除包含List-view数据的SQLite行中的数据。在这里,我使用了从here下载的自定义List-view。谁能告诉我怎么做?

我在下面做了一些事情,但Data没有删除任何人都可以告诉我该怎么做。大感谢提前

这是我的活动:

package com.developer.milanandroid;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.milan.lib.progressgenarator.lib.ProgressGenerator;
import com.milan.lib.progressgenarator.lib.ProgressGenerator.OnCompleteListener;
import com.milan.swipemenulistview.SwipeMenu;
import com.milan.swipemenulistview.SwipeMenuCreator;
import com.milan.swipemenulistview.SwipeMenuItem;
import com.milan.swipemenulistview.SwipeMenuListView;
import com.milan.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.processbutton.lib.milan.ActionProcessButton;

public class DatabaseListView extends Activity implements OnCompleteListener {
    MediaPlayer media_player;
    ActionProcessButton fetch_database;
    SwipeMenuListView database_results;
    LoginDataBaseAdapter logindatabase_adapter;
    SimpleCursorAdapter cursoradapter;
    Cursor cursor;
    TextView username_txt,password_txt;
    String user_name_string,password_string;
    String text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.databaselistview);
        LinearLayout linear = (LinearLayout)findViewById(R.id.linearLayout1);
        username_txt = (TextView)linear.getChildAt(0);
        password_txt = (TextView)linear.getChildAt(0);
        user_name_string = username_txt.getText().toString();
        password_string = password_txt.getText().toString();
        fetch_database = (ActionProcessButton)findViewById(R.id.Button_Fetch_from_Database);
        database_results = (SwipeMenuListView)findViewById(R.id.listview_database);
        final ProgressGenerator progressGenerator = new ProgressGenerator(DatabaseListView.this);
        logindatabase_adapter = new LoginDataBaseAdapter(DatabaseListView.this);
        fetch_database.setMode(ActionProcessButton.Mode.PROGRESS);
        fetch_database.setOnClickListener(new View.OnClickListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {

                progressGenerator.start(fetch_database);
                media_player = media_player.create(DatabaseListView.this, R.raw.retrievingfromdatabase);
                media_player.start();


                String[] from = {logindatabase_adapter.USER_NAME,logindatabase_adapter.USER_PASSWORD};
                int[] to = {R.id.txt_username,R.id.txt_pasword};
                cursor = logindatabase_adapter.feching_Data();
                cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);

            }
        });



        SwipeMenuCreator swime_menu_listview = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem swipemenuitem_delete = new SwipeMenuItem(getApplicationContext());
                swipemenuitem_delete.setBackground(new ColorDrawable(Color.rgb(0x36, 0x49, 0xEE)));
                swipemenuitem_delete.setWidth(dp2px(90));
                swipemenuitem_delete.setIcon(R.drawable.databasedelete);
                menu.addMenuItem(swipemenuitem_delete);

            }
        };
    database_results.setMenuCreator(swime_menu_listview);
    database_results.setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
            int items = position;
            position = database_results.getSelectedItemPosition(); 
            switch(index){
            case 0:

                logindatabase_adapter.deleteEntry(user_name_string);
                Toast.makeText(getApplicationContext(), "Delete button clicked", Toast.LENGTH_SHORT).show();
                break;

            }
            return false;
        }
    });

    }







    protected int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.database_list_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    @Override
    public void onComplete() {
        database_results.setAdapter(cursoradapter);

    }
}

这是我的Databaseadapter:

package com.developer.milanandroid;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;

public class LoginDataBaseAdapter 
{
        //Database name
        static final String DATABASE_NAME = "MilanloginRegistration.db";
        static final int DATABASE_VERSION = 1;
        public static final int NAME_COLUMN = 1;
        // TODO: Create public field for each column in your table.
        // SQL Statement to create a new database.
        public static final String TABLE_NAME="MilanLoginregistration";
        public static final String ID="_id";
        public static final String USER_NAME="USERNAME";
        public static final String USER_PASSWORD ="PASSWORD";


        static final String DATABASE_CREATE = "create table "+ TABLE_NAME +
                                     "( " +ID+" integer primary key autoincrement,"+"USERNAME text UNIQUE,"+USER_PASSWORD+" text); ";
        // Variable to hold the database instance
        public  SQLiteDatabase db;
        // Context of the application using the database.
        private final Context context;
        // Database open/upgrade helper
        private DataBaseHelper dbHelper;
        public  LoginDataBaseAdapter(Context _context) 
        {
            context = _context;
            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        public  LoginDataBaseAdapter open() throws SQLException 
        {
            db = dbHelper.getWritableDatabase();
            return this;
        }
        public void close() 
        {
            db.close();
        }

        public  SQLiteDatabase getDatabaseInstance()
        {
            return db;
        }



        public void insertEntry(String username,String password)
        {
           ContentValues newValues = new ContentValues();

            newValues.put("USERNAME",username);
            newValues.put("PASSWORD",password);

            // Insert the row into your table
            db.insert("MilanLoginregistration",null,newValues);
            ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
        }
        public int deleteEntry(String username)
        {
            //String id=String.valueOf(ID);
            String where="USERNAME=?";
            int numberOFEntriesDeleted= db.delete("MilanLoginregistration", where, new String[]{username}) ;
           // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
            return numberOFEntriesDeleted;
        }

        public Cursor feching_Data(){

            String[] columns = {ID,USER_NAME,USER_PASSWORD};
            db = dbHelper.getWritableDatabase();
            Cursor cursor = db.query(TABLE_NAME, columns,null,null,null,null,null);
            return cursor;

        }
        public String getSinlgeEntry(String userName)
        {
            Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
            if(cursor.getCount()<1) // UserName Not Exist
            {
                cursor.close();
                return "NOT EXIST";
            }
            cursor.moveToFirst();
            String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
            cursor.close();
            return password;                
        }
        public String checkSinlgeEntry(String userName)
        {
            Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
            if(cursor.getCount()>=1) // UserName  Exist
            {
                cursor.close();
                return "NOT EXIST";
            }
            cursor.close();
            return "";              
        }
        public void  updateEntry(String user_name,String pasword)
        {
            // Define the updated row content.
            ContentValues updatedValues = new ContentValues();
            // Assign values for each row.  
            updatedValues.put("USERNAME", user_name);
            updatedValues.put("PASSWORD",pasword);


            String where="USERNAME = ?";
            db.update("MilanLoginregistration",updatedValues, where, new String[]{user_name});             
        }   
        /*public void Display(View v){
            Cursor c = db.rawQuery("select * from MilanloginRegistration", null);
            admin_settings_child.text_fetched_database_results.setText("");
            c.moveToFirst();
            do{
                String username = c.getString(c.getColumnIndex("USERNAME"));
                String password = c.getString(1);
                admin_settings_child.text_fetched_database_results.append("USERNAME::-->"+username+"PASSWORD::-->"+password+"\n");

            }while(c.moveToNext());
        }*/
    }

2 个答案:

答案 0 :(得分:1)

根据您展示的代码,有几个可能的问题。

首先,您只在Adapter的构造函数中打开一次连接。但关闭它几次。 在致电deleteEntry()之前检查是否有任何方法被调用: getSinlgeEntry()checkSinlgeEntry()

其次,您还没有注意到您使用了Debugger。如果您使用它,您可以轻松了解哪些线条会让您遇到问题。 因此,您可能看不到数据已被删除,因为您没有使用CursorLoader,但它可以简化您的工作,您必须在其中一个回调中更新您的适配器,但使用{{1}你必须通过重新加载手动更新它。请参阅doc

如果不适合您,请再次参考Cursor。您将能够获取问题行,因此您的问题将得到很快解决。现在只是猜测。希望它有用。

答案 1 :(得分:1)

点击删除按钮,您需要拨打delete(position);并编写如下代码。

public void delete(int position) {
    AlertDialog dialog = new AlertDialog.Builder(this)
            // .setIcon(R.drawable.mainicon)
            .setTitle("")
            .setMessage("Are You Sure You Want to Delete " + "?")
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            try {
                                 mDatabase.open();
                                 mDatabase.delSecRec(ItemsList.get(position)
                                 .getItemID());
                                 mDatabase.close();
                                refreshList();

                            } catch (Exception e) {

                            }
                        }

                    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            }).show();
}

要刷新适配器,您需要调用此方法。

private void refreshList() {
            db.open();
            ItemsList = db.getAllItems();
            db.close();
            if (ItemsList != null) {
                setAdapterList();
            } else {
                ShowMessage.show(ViewMyThings.this, "No Record found yet !!!");
            }
            mListView.setAdapter(mAdapter);

        }

希望你能从这段代码中得到启发。