在sqlite数据库连接中出错

时间:2016-04-22 04:02:07

标签: java android sqlite

请帮我解决错误。我在Android Studio中收到此错误。我是android开发的新手。注册问题..无法将数据插入数据库。 错误是:

Dim lastcolumn as Long
lastcolumn = Cells(1, Columns.Count).End(xlToLeft).Column + 2

DB_Connectivity

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference

logcat的

package com.freedomkitchen.sonali.freedomkitchenAndroidApp;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;

import android.view.View;
import android.widget.Toast;
import com.freedomkitchen.sonali.freedomkitchenAndroidApp.NewUserWelcome;
import java.util.logging.Handler;
import java.util.logging.LogRecord;


public class DB_Connectivity extends AppCompatActivity {

    SQLiteDatabase myDB;
    int user_ID;

    private static final boolean AUTO_HIDE = true;


    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;


    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler() {
        @Override
        public void close() {

        }

        @Override
        public void flush() {

        }

        @Override
        public void publish(LogRecord record) {

        }
    };
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {

            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private View mControlsView;
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
            mControlsView.setVisibility(View.VISIBLE);
        }
    };
    private boolean mVisible;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        myDB = openOrCreateDatabase("FreedomKitchenDB.db", MODE_PRIVATE, null);
        myDB.execSQL("CREATE TABLE IF NOT EXISTS User_Details(User_ID INTEGER PRIMARY KEY," +
                "First_Name TEXT,Last_Name TEXT,Gender TEXT ,Age TEXT,Country TEXT);");
        myDB.execSQL("CREATE TABLE IF NOT EXISTS Login_Details(User_ID INTEGER," +
                "Username TEXT,Password TEXT,FOREIGN KEY(User_ID) REFERENCES User_Details(User_ID));");

    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

    }

    public void UserLogin(String username,String password) {

        myDB.execSQL("Select User_ID from Login_Details where Username=" + username + "and Password=" + password+");");

        Cursor cursor_one = myDB.rawQuery("Select * from User_Details", null);
        int rows = cursor_one.getCount();
        cursor_one.moveToFirst();
        if (rows == 0) {
            Toast.makeText(getApplicationContext(), "Incorrect Username or Password. Please try again.", Toast.LENGTH_SHORT).show();
        } else if (rows == 1) {
            Intent i = new Intent(getApplicationContext(), FreedomKitchenMenu.class);
            startActivity(i);
        }
    }

    public void Registration(String first_name,String last_name,String age,String gender,String country,String username,String password){
        int user_ID=0;
        Cursor cursor_one = myDB.rawQuery("Select * from User_Details", null);
        int rows = cursor_one.getCount();
        cursor_one.moveToFirst();
        user_ID=rows+1;
        myDB.execSQL("INSERT INTO User_Details(User_ID,User_FirstName,User_LastName,Gender,Age,Country)VALUES("+user_ID+"','"+first_name+"','" + last_name + "','" + gender + "','" + age + "','" + country + ");");
        myDB.execSQL("INSERT INTO Login_Details(User_ID,Username,Password)VALUES(" + user_ID + "','" + username+ "','" + password + ");");
        Intent i=new Intent(getApplicationContext(),NewUserWelcome.class);
        startActivity(i);

    }

}

点击

04-22 07:58:57.111 31243-31243/? E/Zygote: v2
04-22 07:58:57.121 31243-31243/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
04-22 07:59:08.501 31243-31243/com.freedomkitchen.sonali.freedomkitchen E/ViewRootImpl: sendUserActionEvent() mView == null
04-22 07:59:12.971 31243-31243/com.freedomkitchen.sonali.freedomkitchen E/ViewRootImpl: sendUserActionEvent() mView == null
04-22 07:59:33.221 31243-31243/com.freedomkitchen.sonali.freedomkitchen E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.freedomkitchen.sonali.freedomkitchen, PID: 31243
java.lang.IllegalStateException: Could not execute method for android:onClick
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
    at android.view.View.performClick(View.java:5076)
    at android.view.View$PerformClick.run(View.java:20279)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5910)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
    at android.view.View.performClick(View.java:5076) 
    at android.view.View$PerformClick.run(View.java:20279) 
    at android.os.Handler.handleCallback(Handler.java:739) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5910) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference
    at com.freedomkitchen.sonali.freedomkitchenAndroidApp.DB_Connectivity.Registration(DB_Connectivity.java:122)
    at com.freedomkitchen.sonali.freedomkitchenAndroidApp.Registration.Reg(Registration.java:93)
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
    at android.view.View.performClick(View.java:5076) 
    at android.view.View$PerformClick.run(View.java:20279) 
    at android.os.Handler.handleCallback(Handler.java:739) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5910) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 

1 个答案:

答案 0 :(得分:0)

您必须使用以下代码

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "FreedomKitchenDB.db";
private static final int DATABASE_VERSION =1;
//********** LOGIN TABLE COLUMNS *************

public static final String LOGIN_TABLE_NAME = "login_details";
public static final String LOGIN_COLUMN_ID = "user_id";
public static final String LOGIN_COLUMN_USERNAME = "username";
public static final String LOGIN_COLUMN_PASSWORD = "password";

//********** REGISTRATION TABLE COLUMNS *************

public static final String REG_TABLE_NAME = "user_details";
public static final String REG_COLUMN_ID = "user_id";
public static final String REG_COLUMN_FIRST_NAME = "first_name";
public static final String REG_COLUMN_LAST_NAME = "last_name";
public static final String REG_COLUMN_GENDER = "gender";
public static final String REG_COLUMN_AGE = "age";
public static final String REG_COLUMN_COUNTRY = "country";


public DBHelper(Context context)
{
    super(context, DATABASE_NAME, null,DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    String CREATE_REG_TABLE="CREATE TABLE " +REG_TABLE_NAME+"("+REG_COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+REG_COLUMN_FIRST_NAME+" TEXT,"+REG_COLUMN_LAST_NAME+" TEXT,"+REG_COLUMN_GENDER+" TEXT,"+REG_COLUMN_AGE+" TEXT,"+REG_COLUMN_COUNTRY+" TEXT)";
    db.execSQL(CREATE_REG_TABLE);
    String CREATE_LOGIN_TABLE="CREATE TABLE " + LOGIN_TABLE_NAME + "(" + LOGIN_COLUMN_ID + " INTEGER," + LOGIN_COLUMN_USERNAME + " TEXT," + LOGIN_COLUMN_PASSWORD + " TEXT,FOREIGN KEY(" + LOGIN_COLUMN_ID + ") REFERENCES " + REG_TABLE_NAME + "(" + REG_COLUMN_ID + "))";
    db.execSQL(CREATE_LOGIN_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS contacts");
    onCreate(db);
}



public boolean insertUserDetail (String first_name,String last_name,String age,String gender,String country,String username,String password)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(REG_COLUMN_FIRST_NAME, first_name);
    contentValues.put(REG_COLUMN_LAST_NAME, last_name);
    contentValues.put(REG_COLUMN_GENDER, gender);
    contentValues.put(REG_COLUMN_AGE, age);
    contentValues.put(REG_COLUMN_COUNTRY, country);
    ContentValues mContentValues1=new ContentValues();
    mContentValues1.put(LOGIN_COLUMN_USERNAME,username);
    mContentValues1.put(LOGIN_COLUMN_PASSWORD,password);
    db.insert(LOGIN_TABLE_NAME, null, mContentValues1);
    db.insert(REG_TABLE_NAME, null, contentValues);
    return true;
}

public boolean Login(String username, String password) throws SQLException
{
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor mCursor = db.rawQuery("SELECT * FROM " + LOGIN_TABLE_NAME + " WHERE "+LOGIN_COLUMN_USERNAME+"=? AND "+LOGIN_COLUMN_PASSWORD+"=?", new String[]{username,password});
    if (mCursor != null) {
        if(mCursor.getCount() > 0)
        {
            return true;
        }
    }
    return false;
}}