如何修复android中的数据库中的Null指针异常

时间:2015-04-16 14:03:16

标签: android sqlite nullpointerexception

我正在创建一个Android应用程序,它包含使用sqllite的注册表单。当我单击注册按钮时,它显示 java.lang.NullPointerException 。任何人都可以告诉我我在哪里犯了错误。我正在尝试这个1小时,这太烦人了,请帮助我。

这是我的活动:

registration = (ButtonFloatSmall)findViewById(R.id.btn_flt_sml_registration);
        registration.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                registrationdialog = new Dialog(Login.this);                                            //Creating a dialog
                registrationdialog.setContentView(R.layout.registrationdialog);                         //Adding custom layout to a dialog
                registrationdialog.setTitle("User Registration");                                       //Setting title to a dialog
                registrationdialog.setCancelable(false);

                username_dialog = (EditText)registrationdialog.findViewById(R.id.edt_dialog_username);  
                password_dialog = (EditText)registrationdialog.findViewById(R.id.edt_dialog_password);
                confirm_password = (EditText)registrationdialog.findViewById(R.id.edt_dialog_confirm_password);



                /*------For viewing passwords if "Show passwords" is checked---*/

                show_password =(CheckBox)registrationdialog.findViewById(R.id.show_password);
                show_password.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                        if(!isChecked){

                            password_dialog.setTransformationMethod(PasswordTransformationMethod.getInstance());
                            confirm_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        }
                        else{

                            password_dialog.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                            confirm_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

                        }


                    }
                });





                Registerbutton = (Button)registrationdialog.findViewById(R.id.Btn_Register);
                Registerbutton.setMode(ActionProcessButton.Mode.ENDLESS);
                Registerbutton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        username_dialog_string = username_dialog.getText().toString();
                        password_dialog_string = password_dialog.getText().toString();
                        confirm_password_string = confirm_password.getText().toString();

                        if(username_dialog_string.equals("")||password_dialog_string.equals("")||confirm_password_string.equals("")){
                            validation_manager.validateAllAndSetError();
                        }
                        else if(password_dialog_string.equals(confirm_password_string)){
                            progressGenerator.start(Registerbutton);

                            logindatabaseadapter.insertEntry(username_dialog_string,password_dialog_string);
                            Registerbutton.setEnabled(false);
                            username_dialog.setEnabled(false);
                            password_dialog.setEnabled(false);
                            confirm_password.setEnabled(false);
                            registrationdialog.setCancelable(true);

                        }
                        else{
                            Toast.makeText(Login.this, "Password and confirm passwords are not matched please try again ", Toast.LENGTH_LONG).show();
                        }


                    }
                });


                clear_Button = (ActionProcessButton)registrationdialog.findViewById(R.id.Btn_Clear);
                clear_Button.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                                username_dialog.setText("");
                                password_dialog.setText("");
                                confirm_password.setText("");

                    }
                });

                registrationdialog.show();

            }
        });

这是我的登录数据库适配器:

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;

public class LoginDataBaseAdapter 
{
        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.
        static final String DATABASE_CREATE = "create table "+"MilanLoginregistration"+
                                     "( " +"ID"+" integer primary key autoincrement,"+"USERNAME  text UNIQUE,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 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 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});             
        }       
}

这是我的logcat:

04-16 19:32:56.962: E/AndroidRuntime(6545): FATAL EXCEPTION: main
04-16 19:32:56.962: E/AndroidRuntime(6545): Process: com.developer.milanandroid, PID: 6545
04-16 19:32:56.962: E/AndroidRuntime(6545): java.lang.NullPointerException
04-16 19:32:56.962: E/AndroidRuntime(6545):     at com.developer.milanandroid.Login$1$2.onClick(Login.java:181)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at android.view.View.performClick(View.java:4463)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at android.view.View$PerformClick.run(View.java:18770)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at android.os.Handler.handleCallback(Handler.java:808)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at android.os.Handler.dispatchMessage(Handler.java:103)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at android.os.Looper.loop(Looper.java:193)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at android.app.ActivityThread.main(ActivityThread.java:5292)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at java.lang.reflect.Method.invokeNative(Native Method)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at java.lang.reflect.Method.invoke(Method.java:515)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
04-16 19:32:56.962: E/AndroidRuntime(6545):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

尝试在调用任何查询之前初始化db类,然后在调用每个查询之前打开数据库,然后在查询后关闭它。

LoginDataBaseAdapter logindatabaseadapter; (Global)    
logindatabaseadapter = new LoginDataBaseAdapter (this);    
logindatabaseadapter.open();
logindatabaseadapter.insertEntry(username_dialog_string,password_dialog_string);
logindatabaseadapter.close();