无法启动活动ComponentInfo可能是因为Sqlitedatabase对象

时间:2017-02-24 18:21:23

标签: java android xml

非常基本的代码。我在这里使用db1对象以便db1.rawQuery工作,但它似乎抛出了异常。我知道如果我不使用Sqlitedatabse对象,那么rawquery()就不会起作用。任何人都可以建议我更好的编码想法吗?我只是Android的初学者。所以原谅我找不到看似显而易见的错误。我只是不想谷歌nullpointerexception,因为我想我明白它是什么。但我只是不明白它是如何发生的。

     package com.example.cp.profiletoggler;
    import android.app.Dialog;
    import android.content.ContentValues;
import android.content.Context;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

   public class MainActivity extends AppCompatActivity {

    SQLiteDatabase db1;
    EditText passcode, lockcode, username, password,enterpassword;
    Button setcode, signin,enter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username=(EditText)findViewById(R.id.usernameid);
        password=(EditText)findViewById(R.id.passwordid);
        signin=(Button)findViewById(R.id.signinbutton);
        passcode=(EditText)findViewById(R.id.editpasscode);
        lockcode=(EditText)findViewById(R.id.editlockcode);
        setcode=(Button)findViewById(R.id.btncode);
        enterpassword=(EditText)findViewById(R.id.idpassword);
        enter=(Button)findViewById(R.id.btnenter);
        final DBAdapter db = new DBAdapter(getApplicationContext());

        String query = "SELECT * FROM Profile";
        Cursor cursor = db1.rawQuery(query, null);
        if (cursor.getCount() == 0)
        {
            Dialog dialogbox=new Dialog(MainActivity.this);
            dialogbox.setContentView(R.layout.profiledetails);
            dialogbox.setCancelable(false);
            signin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String name=username.getText().toString();
                    String password1=password.getText().toString();
                    if(name.trim().length()>0 || password1.trim().length()>0) {
                        db.addprofile(name, password1);
                        Toast.makeText(getApplicationContext(),"Added",Toast.LENGTH_LONG).show();
                    }
                    else {
                        Toast.makeText(getApplicationContext(),"please enter something",Toast.LENGTH_LONG).show();
                    }
                }
            });

        }
        if(cursor.getCount()!=0)
        {
            final Dialog dialogbox2=new Dialog(MainActivity.this);
            dialogbox2.setContentView(R.layout.enterpassword);
            dialogbox2.setCancelable(false);
            enter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String permpassword=enterpassword.getText().toString();
                    if(permpassword.trim().length()>0)
                    {
                        Cursor c=db1.rawQuery("SELECT * FROM Profile WHERE _PASSCODE='" + permpassword + "'",null);
                        if (c.moveToFirst()) {
                            Toast.makeText(MainActivity.this,"Login Success",Toast.LENGTH_LONG).show();
                            dialogbox2.dismiss();
                        } else {
                            Toast.makeText(MainActivity.this, "Invalid attempt",Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }
                }
            });

        }
        setcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String passcode1=passcode.getText().toString();
                String lockcode1=lockcode.getText().toString();
                if(passcode1.trim().length()>0 || lockcode1.trim().length()>0) {
                    db.insert(passcode1, lockcode1);
                    Toast.makeText(getApplicationContext(),"Added",Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(getApplicationContext(),"please enter something",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

这是继承SQliteOpenhelper类的DBAdapter.java文件

package com.example.cp.profiletoggler;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;




public class DBAdapter extends SQLiteOpenHelper{


    Context context1;
    private  static  final int Database_Version=1;
    private  static final  String Database_Name="MyDatabase";
    private  static  final String Table_Passcode="Passcode";
    public static final String COLUMN_Passcode = "_PASSCODE ";
    private  static  final String Table_Lockcode="Lockcode";
    public static final String COLUMN_Lockcode = "_LOCKCODE ";
    private  static  final String Table_Profile="Profile";
    public static final String COLUMN_Username = "_USERNAME ";
    public static final String COLUMN_Password = "_PASSWORD ";

    public   DBAdapter(Context context) {

        super(context, Database_Name,null,Database_Version);
        this.context1=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db=getWritableDatabase();
        String query="CREATE TABLE " + Table_Passcode + "(" + COLUMN_Passcode + " INTEGER NOT NULL )";
        db.execSQL(query);
        String query2="CREATE TABLE "+ Table_Lockcode + "(" + COLUMN_Lockcode + " INTEGER NOT NULL )";
        db.execSQL(query2);
        String query3="CREATE TABLE "+ Table_Profile+ "(" +COLUMN_Username + " VARCHAR NOT NULL, " + COLUMN_Password + " VARCHAR NOT NULL)" ;
        db.execSQL(query3);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+Table_Passcode);
        db.execSQL("DROP TABLE IF EXISTS "+Table_Lockcode);
        db.execSQL("DROP TABLE IF EXISTS "+Table_Profile);
        onCreate(db);
    }


    public void insert(String pass,String lock) {
        SQLiteDatabase db=getWritableDatabase();
        db.execSQL("INSERT INTO " + Table_Passcode + "VALUES" + "(" + pass + ");");

        db.execSQL("INSERT INTO " + Table_Lockcode + "VALUES" + "(" + lock + ");");
    }


    public void addprofile(String name, String pass2) {
        // ContentValues values=new ContentValues();
        SQLiteDatabase db=getWritableDatabase();
        db.execSQL("INSERT INTO Profile(_USERNAME,_PASSWORD) VALUES('"+ name + "' ,'"+ pass2+ "');");

    }


}

这是profiledetails.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="@color/colorRed" android:layout_gravity="center"
        android:orientation="vertical" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >


    <LinearLayout
        android:layout_width="250dp"
        android:layout_height="match_parent">

        <EditText
        android:layout_marginTop="50dp"
        android:layout_width="500dp"
        android:layout_height="wrap_content"
        android:hint="Username"
        android:background="@drawable/rounded_edittext"
            android:layout_weight="1"
        android:id="@+id/usernameid"/>

        <EditText
            android:layout_marginLeft="-240dp"
            android:layout_marginTop="100dp"
            android:layout_width="500dp"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:layout_weight="1"
            android:background="@drawable/rounded_edittext"
            android:id="@+id/passwordid"/>
    </LinearLayout>
        <Button

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/signinbutton"
            android:text="Sign In"

            android:textColor="@color/colorWhite"
            android:background="@color/colorBlack"/>
    </LinearLayout>

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/colorRed" android:layout_width="match_parent" android:layout_height="match_parent" >
    <TextView

        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:id="@+id/textpasscode"
        android:text="SET YOUR PASSCODE"/>
    <EditText
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/textpasscode"
        android:id="@+id/editpasscode"
        android:background="@drawable/rounded_edittext"/>
    <TextView
        android:layout_marginTop="30dp"
        android:layout_below="@id/textpasscode"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:id="@+id/textlockcode"
        android:text="SET YOUR LOCKCODE"/>
    <EditText android:layout_marginTop="20dp"
        android:layout_below="@id/editpasscode"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/textlockcode"
        android:id="@+id/editlockcode"
        android:background="@drawable/rounded_edittext"/>
    <Button android:background="@color/colorBlack"
        android:textColor="@color/colorWhite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Code"
        android:layout_marginTop="100dp"
        android:id="@+id/btncode"/>
    <Button android:background="@color/colorBlack" android:layout_marginLeft="20dp"
        android:layout_toRightOf="@id/btncode"
        android:textColor="@color/colorWhite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current Mode"
        android:layout_marginTop="100dp"
        android:id="@+id/btnmode"/>

    <Button

        android:layout_width="50dp"
        android:layout_height="20dp"
        android:background="@drawable/keyimage"
        android:layout_below="@+id/btnmode"
        android:layout_alignParentStart="true"
        android:layout_marginStart="37dp"
        android:layout_marginTop="27dp"
        android:id="@+id/keybutton" />
</RelativeLayout>

日志

        02-25 00:24:48.927 12403-12403/com.example.cp.profiletoggler 

     E/MultiWindowProxy: getServiceInstance failed!
     02-25 00:24:49.224 12403-12553/com.example.cp.profiletoggler E/GED:  
     Failed to get GED Log Buf, err(0)
     02-25 00:24:54.208 12403-12403/com.example.cp.profiletoggler 

E/MultiWindowProxy: getServiceInstance failed!
02-25 00:24:54.260 12403-12403/com.example.cp.profiletoggler E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.cp.profiletoggler, PID: 12403
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cp.profiletoggler/com.example.cp.profiletoggler.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2584)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2666)
                                                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                                   at android.os.Looper.loop(Looper.java:207)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5769)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                   at com.example.cp.profiletoggler.MainActivity.onCreate(MainActivity.java:71)
                                                                                   at android.app.Activity.performCreate(Activity.java:6583)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2531)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2666) 
                                                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:111) 
                                                                                   at android.os.Looper.loop(Looper.java:207) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5769) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 

2 个答案:

答案 0 :(得分:1)

试试这个:

在DBAdapter中添加以下方法。

public Cursor getCursorForQuery(String query) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.rawQuery(query, null);
}

从您的活动中这样打电话。

final DBAdapter db = new DBAdapter(getApplicationContext());

String query = "SELECT * FROM Profile";
Cursor cursor = db.getCursorForQuery(query);

答案 1 :(得分:-1)

在MainActivity上试试这个

SQLiteDatabase db1 = this.getWritableDatabase();