dimanche 10 mai 2015

How to delete a databse row from listview populated from sqlite database

I am creating an android application that consists of user registration form and store the details in sqlite database of the android.I want to delete a record from database which was populated in a list view in my activity.Here i am using a list view custom library downloaded from here when i click delete button it was showing error. Please help me with this. This is my list view activity:

package com.developer.milanandroid;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
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.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;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.databaselistview);
        username_txt = (TextView)findViewById(R.id.txt_username);
        password_txt = (TextView)findViewById(R.id.txt_pasword);
        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:
                user_name_string = username_txt.getText().toString();
                password_string = password_txt.getText().toString();
                logindatabase_adapter.deleteEntry(user_name_string, password_string);

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

    }
}

This is my login database adapter class:

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 password)
        {
            //String id=String.valueOf(ID);
            String where="USERNAME=?";
            int numberOFEntriesDeleted= db.delete("MilanLoginregistration", where, new String[]{username,password}) ;
           // 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());
        }*/
    }

This is my logcat:

01-02 05:00:22.810: E/AndroidRuntime(14355): FATAL EXCEPTION: main
01-02 05:00:22.810: E/AndroidRuntime(14355): Process: com.developer.milanandroid, PID: 14355
01-02 05:00:22.810: E/AndroidRuntime(14355): java.lang.NullPointerException
01-02 05:00:22.810: E/AndroidRuntime(14355):    at com.developer.milanandroid.DatabaseListView$3.onMenuItemClick(DatabaseListView.java:90)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at com.milan.swipemenulistview.SwipeMenuListView$1.onItemClick(SwipeMenuListView.java:75)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at com.milan.swipemenulistview.SwipeMenuView.onClick(SwipeMenuView.java:85)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at android.view.View.performClick(View.java:4438)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at android.view.View$PerformClick.run(View.java:18422)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at android.os.Handler.handleCallback(Handler.java:733)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at android.os.Looper.loop(Looper.java:136)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at android.app.ActivityThread.main(ActivityThread.java:5017)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at java.lang.reflect.Method.invokeNative(Native Method)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at java.lang.reflect.Method.invoke(Method.java:515)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-02 05:00:22.810: E/AndroidRuntime(14355):    at dalvik.system.NativeStart.main(Native Method)

Aucun commentaire:

Enregistrer un commentaire