Вопрос по android, java, xml – java.lang.NullPointerException при попытке доступа к базе данных SQLite

-1

Я пытаюсь создать страницу входа, которая проверяет базу данных SQLite на предмет сведений о пользователях, и, если они присутствуют, они переходят на главную страницу приложения. Я продолжаю получать исключение java.lang.NullPointerException и не знаю, что я делаю неправильно. Подскажите пожалуйста, где проблемы в коде?

Login.java:

    package com.B00512756.angertwo;



    public class Login extends Activity implements OnClickListener{
        public static final String DATABASE_NAME = "login_database.db";
        public static final String USER_INFO_TABLE = "user_information";
        public static final String COLUMN_ID = "UserID";
        public static final String COLUMN_RATING = "UserName";
        public static final String COLUMN_NAME = "Password";


    public SQLiteDatabase regDB;





    public EditText txtUserName;
    public EditText txtPassword;
    public static Button btnLogin;
    public static Button btnCancel;



        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.loginpage);

            txtUserName=(EditText)this.findViewById(R.id.txtUname);
            txtPassword=(EditText)this.findViewById(R.id.txtPwd);
            //btnLogin=(Button)this.findViewById(R.id.btnLogin);
            Button Login = (Button) findViewById(R.id.btnLogin);
            Button Register = (Button) findViewById(R.id.btnregister);
            Button Cancel = (Button) findViewById(R.id.btnCancel);

            Register.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent myIntent = new Intent(view.getContext(), Registration.class);
                    startActivityForResult(myIntent, 0); 
                    finish();
                }
            });


            Cancel.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });

            Login.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    //String[] columns = new String[]{COLUMN_ID, COLUMN_RATING, COLUMN_NAME };

                    Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
                            COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
                    String result = "";

                    int iRow = c.getColumnIndex(COLUMN_ID);
                    int iRating = c.getColumnIndex(COLUMN_RATING);
                    int iName = c.getColumnIndex(COLUMN_NAME);

                    c.moveToLast();
                    for (int i = c.getCount() - 1; i >= 0; i--) {

                        // Get the data
                        result = result + c.getString(iRow) + " " + c.getString(iRating) + " " + c.getString(iName) + "\n" ;
                        if("select * from USER_INFO_TABLE where UserName =" + "\""+ txtUserName + "\""+" and Password="+ "\""+ txtPassword != null);
                        { Intent j = new Intent();
                        j.setClassName("com.B00512756.angertwo",
                                "com.B00512756.angertwo.AngerprototypetwoActivity");

                        startActivity(j);}

                        // Move the cursor
                        c.moveToPrevious();
                        //return result;
                    }
                    c.close();


                    }

                });

            }






        private SQLiteDatabase getWritableDatabase() {
            // TODO Auto-generated method stub
            return null;
        }






        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub


        }
}

Loginpage.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">

    <TableRow>
    <TextView 
    android:text="User Name: " 
    android:id="@+id/TextView01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
    </TextView>

    <EditText 
    android:text="" 
    android:id="@+id/txtUname" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">
    </EditText>
    </TableRow>


    <TableRow>
    <TextView 
    android:text="Password: " 
    android:id="@+id/TextView02" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
    </TextView>


    <EditText 
    android:text="" 
    android:id="@+id/txtPwd" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:password="true">
    </EditText>
    </TableRow>


    <TableRow>

    <Button
    android:text="Login" 
    android:id="@+id/btnLogin" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">
    </Button>

    <Button
    android:text="Register" 
    android:id="@+id/btnregister" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">
    </Button>

    <Button
    android:text="Cancel" 
    android:id="@+id/btnCancel" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">
    </Button>

    </TableRow>


    </TableLayout>

AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.B00512756.angertwo"
      android:versionCode="1"
      android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minSdkVersion="8" />

    <application android:name=".AppState" android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Login"
                  android:label="@string/main_title">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Login" android:label="@string/begin_label"
       android:theme="@android:style/Theme"></activity> 
      <activity android:name=".Question1" android:label="@string/question_one"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Question2" android:label="@string/question_two"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Question3" android:label="@string/question_three"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Question4" android:label="@string/question_four"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Question5" android:label="@string/question_five"
       android:theme="@android:style/Theme"></activity>
      <!-- <activity android:name=".AngerprototypetwoActivity" android:label="@string/main_title"
       android:theme="@android:style/Theme"></activity> -->
      <activity android:name=".nextQ1" android:id="@+id/next_Q1_button"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Strategies" android:label="@string/strategies_label"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Contact" android:label="@string/begin_label"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Strat_What_Is_Anger" android:label="@string/strategies_label_what_is_anger"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Strat_Use_Distraction" android:label="@string/strategies_label_distraction"
       android:theme="@android:style/Theme"></activity>
      <activity android:name=".Registration" android:label="@string/registration"
       android:theme="@android:style/Theme"></activity>

    </application>

</manifest>

Logcat:

    05-19 17:08:17.111: ERROR/AndroidRuntime(27481): FATAL EXCEPTION: main
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481): java.lang.NullPointerException
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at  com.B00512756.angertwo.Login$3.onClick(Login.java:76)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at android.view.View.performClick(View.java:2408)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at android.view.View$PerformClick.run(View.java:8816)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at android.os.Handler.handleCallback(Handler.java:587)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at android.os.Handler.dispatchMessage(Handler.java:92)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at android.os.Looper.loop(Looper.java:123)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at android.app.ActivityThread.main(ActivityThread.java:4627)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at java.lang.reflect.Method.invokeNative(Native Method)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at java.lang.reflect.Method.invoke(Method.java:521)
    05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
     05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
     05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at dalvik.system.NativeStart.main(Native Method)
    05-19 17:08:17.121: WARN/ActivityManager(58):   Force finishing activity com.B00512756.angertwo/.Login
    05-19 17:08:17.641: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{4505c768 com.B00512756.angertwo/.Login}
    05-19 17:08:19.731: INFO/Process(27481): Sending signal. PID: 27481 SIG: 9
    05-19 17:08:19.751: INFO/WindowManager(58): WIN DEATH: Window{4507d5b0 com.B00512756.angertwo/com.B00512756.angertwo.Login paused=false}
    05-19 17:08:19.751: INFO/ActivityManager(58): Process com.B00512756.angertwo (pid 27481) has died.
     05-19 17:08:19.921: WARN/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 27481 uid 10045
    05-19 17:08:20.341: DEBUG/dalvikvm(117): GC_EXTERNAL_ALLOC freed 484 objects / 27832 bytes in 383ms
    05-19 17:08:24.590: DEBUG/dalvikvm(197): GC_EXPLICIT freed 100 objects / 4336 bytes in 127ms
    05-19 17:08:28.610: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{4505c768 com.B00512756.angertwo/.Login}
    05-19 17:08:29.650: DEBUG/dalvikvm(264): GC_EXPLICIT freed 58 objects / 2800 bytes in 140ms
    05-19 17:08:33.513: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol

Дополнительная информация:

Login.setOnClickListener(new View.OnClickListener() {

            @SuppressWarnings("null")
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String name = txtUserName.getText().toString();
                String pwd = txtPassword.getText().toString();
                SQLiteDatabase regDB = null;



                //String[] columns = new String[]{COLUMN_ID, COLUMN_RATING, COLUMN_NAME };


                Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
                        COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
                if(null!=c){

                      c.moveToFirst();

                     System.out.println("Cursor Size"+c.getCount());

                    }

                String result = "";

                int iRow = c.getColumnIndex(COLUMN_ID);
                int iRating = c.getColumnIndex(COLUMN_RATING);
                int iName = c.getColumnIndex(COLUMN_NAME);

                c.moveToLast();
                for (int i = c.getCount() - 1; i >= 0; i--) {

                    // Get the data
                    result = result + c.getString(iRow) + " " + c.getString(iRating) + " " + c.getString(iName) + "\n" ;
                    if("select * from USER_INFO_TABLE where UserName =" + "\""+ name + "\""+" and Password="+ "\""+ pwd != null );
                    { Intent j = new Intent();
                    j.setClassName("com.B00512756.angertwo",
                            "com.B00512756.angertwo.AngerprototypetwoActivity");

                    startActivity(j);}

                    // Move the cursor
                    c.moveToPrevious();
                    //return result;
                }
                c.close();


                }

            });

В этой строке выдается нулевая ошибка:

Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
                        COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);

Ваша помощь очень ценится :)

Спасибо, добрый сэр :) Richy
вonClick метод, который вы установилиregDB  вnull а затем вызвать запрос по этомуnull ссылка. Как я уже сказал в своем ответе это броситNullPointerException, Где \ как вы создали базу данных? (Самый простой способ - этоSQLiteOpenHelper и позвонитьgetWritableDatabase() на эту реализацию) Luksprog

Ваш Ответ

1   ответ
0

 05-19 17:08:17.111: ERROR/AndroidRuntime(27481):     at  com.B00512756.angertwo.Login$3.onClick(Login.java:76)

Найдите источник для Login.java, перейдите к строке 76 и посмотрите, на какие экземпляры объектов обращаются ссылки. Один из них является нулевым.

Error: User Rate Limit Exceeded Richy
Error: User Rate Limit ExceededregDBError: User Rate Limit ExceededLoginError: User Rate Limit ExceededifError: User Rate Limit ExceedednullError: User Rate Limit ExceededStringError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded Richy
Error: User Rate Limit Exceeded

Похожие вопросы