简体   繁体   中英

Null pointer exception in android sqlite

I am new to android I am creating an android application that consists of a registration dialog and sqlite storage.But here i was getting null pointer exception.I didn't find any mistake but it was showing null pointer exception.I have been trying this code since 2 hours

Here i used custom buttons fin alert dialog downloaded from here This is my activity displays alert dialog and registers into database

       package com.developer.milanandroid;

import java.io.File;
import java.util.ArrayList;

import com.milan.lib.progressgenarator.lib.ProgressGenerator;
import com.milan.lib.progressgenarator.lib.ProgressGenerator.OnCompleteListener;
import com.milan.paperbuttons.adminsettingsbuttons;
import com.milan.paperbuttons.ShowDatabase;
import com.milan.validation.lib.RegExpressionValueValidator;
import com.milan.validation.lib.ValidationManager;
import com.processbutton.lib.milan.ActionProcessButton;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class AdminSettings extends Activity implements OnCompleteListener{

    public LoginDataBaseAdapter logindatabase_adapter_child;
//  public  SQLiteDatabase db;
    Button Review;
    TextView text_fetched_database_results;
    String username,password;
    Cursor c;

    adminsettingsbuttons review,fetch_database,adduser;
    MediaPlayer media_player;
    private ArrayList<String> USER_NAME = new ArrayList<String>();
    private ArrayList<String> USER_PWD = new ArrayList<String>();
    Dialog database_list;
    DataBaseHelper database_helper_child;
    File Milan,Sample;

    //-----------------------RegistrationDialog variables--------------------------------//
    com.milan.material.widgets.dialog.FloatingEditText username_dialog,password_dialog,confirm_password;
    Dialog registration_dialog;
    private ValidationManager validation_manager;
    CheckBox show_password;
    public ActionProcessButton Registerbutton,clear_Button;
    LoginDataBaseAdapter logindatabaseadapter;
    String  dialog_user_name_string,dialog_pasword_string,dialog_confirm_string;
    int username_length=5,password_length=5;
    String stored_pass;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_settings);



        fetch_database = (adminsettingsbuttons)findViewById(R.id.Button_Fetch_from_Database);
        fetch_database.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                    Intent database_list = new Intent(AdminSettings.this,DatabaseListView.class);
                    startActivity(database_list);
                }
        });

        review = (adminsettingsbuttons)findViewById(R.id.button_review);
        review.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                //String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
                //Milan = new File(extStorageDirectory+"/Milan");
                //if(!Milan.exists()){

                //  Milan.mkdir();

                    /*media_player = new MediaPlayer(AdminSettings.this,)
                    media_player.start();*/
                    //}
                    //Sample = new File(extStorageDirectory+"/Milan/Sample.txt");
                //  try {
                //      Sample.createNewFile();
                //  } catch (IOException e) {
                        // TODO Auto-generated catch block
                //      e.printStackTrace();
                //  }
                Intent review = new Intent(getApplicationContext(),Review.class);
                startActivity(review);

            }
        });


        adduser= (adminsettingsbuttons)findViewById(R.id.button_Adduser);
        adduser.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                registration_dialog = new Dialog(AdminSettings.this);
                registration_dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
                registration_dialog.setContentView(R.layout.registrationdialog);
                registration_dialog.setTitle("User Registration");
                registration_dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.user);


                username_dialog = (com.milan.material.widgets.dialog.FloatingEditText)registration_dialog.findViewById(R.id.edt_dialog_username);
                password_dialog = (com.milan.material.widgets.dialog.FloatingEditText)registration_dialog.findViewById(R.id.edt_dialog_password);
                confirm_password = (com.milan.material.widgets.dialog.FloatingEditText)registration_dialog.findViewById(R.id.edt_dialog_confirm_password);

                validation_manager = new ValidationManager(AdminSettings.this); 
                        /*-----------------For validating each username and password fields in the registration dialog----------------------*/

                validation_manager.add("", new RegExpressionValueValidator(username_dialog, "^[a-zA-Z0-9\\-'\\s]{3,}$", "Please enter your user name"));
                validation_manager.add("", new RegExpressionValueValidator(password_dialog, "^[a-zA-Z0-9\\-'\\s]{3,}$", "Please enter your password"));
                validation_manager.add("", new RegExpressionValueValidator(confirm_password, "^[a-zA-Z0-9\\-'\\s]{3,}$","Please enter confirm password"));

                      /*-------------------For viewing passwords on clicking show passwords checkbox-------------------------------------------*/

                show_password = (CheckBox)registration_dialog.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());
                        }

                    }
                });

                        /*-----------------------Progress generator of register button------------------------------------*/

                final ProgressGenerator progressGenerator = new ProgressGenerator(AdminSettings.this);
                Registerbutton = (ActionProcessButton)registration_dialog.findViewById(R.id.Btn_Register);
                Registerbutton.setMode(ActionProcessButton.Mode.ENDLESS);
                Registerbutton.setOnClickListener(new View.OnClickListener() 
                {
                    @Override
                    public void onClick(View v) 
                    {
                        int a,b,c;  
                         dialog_user_name_string = username_dialog.getText().toString();
                         dialog_pasword_string = password_dialog.getText().toString();
                         dialog_confirm_string = confirm_password.getText().toString();
                         //dialog_seq_answer = seq_answer.getText().toString();
                        if((!dialog_user_name_string.equals("")) &&(!dialog_pasword_string.equals("")) && (!dialog_confirm_string.equals(""))){

                            a= dialog_user_name_string.length();
                            b= dialog_pasword_string.length();
                            c= dialog_confirm_string.length();

                            if((a<=username_length) && (b<=password_length) && (c<=password_length)){

                                    Toast.makeText(AdminSettings.this, "Sorry,Username and password length must be greater than 5 characters", Toast.LENGTH_LONG).show();
                                    media_player = MediaPlayer.create(AdminSettings.this, R.raw.usernameandpasswordlength);
                                    media_player.start();
                                }
                             else{
                                    stored_pass = logindatabaseadapter.checkSinlgeEntry(dialog_user_name_string);
                                    if(!stored_pass.equals("NOT EXIST")){

                                        if(dialog_pasword_string.equals(dialog_confirm_string)){

                                         logindatabaseadapter.insertEntry(dialog_user_name_string, dialog_pasword_string); //Inserting username and password into the database
                                         progressGenerator.start(Registerbutton);
                                         Registerbutton.setEnabled(false);
                                         media_player= MediaPlayer.create(AdminSettings.this, R.raw.regesteringintodatabase);
                                         media_player.start();
                                         username_dialog.setEnabled(false);
                                         password_dialog.setEnabled(false);
                                         confirm_password.setEnabled(false);
                                         //registration_dialog.setCancelable(false);
                                        }
                                        else{

                                             media_player= MediaPlayer.create(AdminSettings.this, R.raw.databasepasswordsnotmatched);
                                             media_player.start();
                                             Toast.makeText(AdminSettings.this, "Passwords did not matched please try again", Toast.LENGTH_LONG).show();

                                            }   
                                    }
                             } 
                        }

                        else {  
                                    /*------------------Calling for validation---------------------------*/
                            validation_manager.validateAllAndSetError();
                            Toast.makeText(AdminSettings.this, "please fill all the fields", Toast.LENGTH_LONG).show();
                            media_player= MediaPlayer.create(AdminSettings.this, R.raw.pleasefilallthedetails);
                            media_player.start();
                        }

                    }   


                });




                clear_Button = (ActionProcessButton)registration_dialog.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("");

                    }
                });


                registration_dialog.show();

            }
        });

    }   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.admin_settings, 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() {
        Toast.makeText(AdminSettings.this, "Account created succesfully"+" "+dialog_user_name_string,Toast.LENGTH_LONG).show();
        media_player= MediaPlayer.create(AdminSettings.this, R.raw.congratulationsdb);
        media_player.start();


    }



}

Logindatabase Adapter:

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 not null,"+USER_PASSWORD+" text not null); ";
        // 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 LoginDataBaseAdapter opentoRead() throws android.database.SQLException{

            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
            db = dbHelper.getReadableDatabase();
            return this;
        }
        public LoginDataBaseAdapter opentoWrite() throws android.database.SQLException{

            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
            db = dbHelper.getWritableDatabase();
            return this;
        }

        public void Close(){
            dbHelper.close();
        }


        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 deleteAll(){
            return db.delete(TABLE_NAME, null, null);
        }

        public void deleteEntry(int id){
            //String id=String.valueOf(ID);
            db.delete(TABLE_NAME, ID+"="+id, null);
           // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();

        }

        public Cursor queue_all(){
            String[] columns = new String[]{ID,"USERNAME","PASSWORD"};
            Cursor cursor_queue_all =db.query(TABLE_NAME, columns, null, null, null, null, null);
            return cursor_queue_all;
        }

        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 "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:05:03.100: E/AndroidRuntime(18345): FATAL EXCEPTION: main
01-02 05:05:03.100: E/AndroidRuntime(18345): Process: com.developer.milanandroid, PID: 18345
01-02 05:05:03.100: E/AndroidRuntime(18345): java.lang.NullPointerException
01-02 05:05:03.100: E/AndroidRuntime(18345):    at com.developer.milanandroid.AdminSettings$3$2.onClick(AdminSettings.java:187)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at android.view.View.performClick(View.java:4438)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at android.view.View$PerformClick.run(View.java:18422)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at android.os.Handler.handleCallback(Handler.java:733)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at android.os.Looper.loop(Looper.java:136)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at android.app.ActivityThread.main(ActivityThread.java:5017)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at java.lang.reflect.Method.invokeNative(Native Method)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at java.lang.reflect.Method.invoke(Method.java:515)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-02 05:05:03.100: E/AndroidRuntime(18345):    at dalvik.system.NativeStart.main(Native Method)

You are trying to get the following from the dialog before showing the dialog:

username_dialog = (com.milan.material.widgets.dialog.FloatingEditText)registration_dialog.findViewById(R.id.edt_dialog_username);
password_dialog = (com.milan.material.widgets.dialog.FloatingEditText)registration_dialog.findViewById(R.id.edt_dialog_password);
confirm_password = (com.milan.material.widgets.dialog.FloatingEditText)registration_dialog.findViewById(R.id.edt_dialog_confirm_password);

Try to get these views after showing the dialog or just inflate the R.layout.registrationdialog to a view object and then use the view object instead of registration_dialog .

You haven't defined the logindatabaseadapter variable.

When you call logindatabaseadapter.checkSinlgeEntry(...) you will get a NullPointerException as at that point, logindatabaseadapter = null .

You will need to add logindatabaseadapter = new LoginDataBaseAdapter(this) to your onCreate

Thanks @Ed George for posting answer i found answer by initialising database and open it

logindatabaseadapter = new Logindatabaseadapter();
logindatabaseadapter.open();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM