2017-02-24 54 views
0

漂亮的基本代碼。我在這裏使用了db1對象,讓db1.rawQuery工作,但它似乎拋出了異常。我知道如果我不使用Sqlitedatabse對象,那麼rawquery()將不起作用。任何人都可以提出更好的編碼思想嗎?我只是Android的初學者。所以原諒我無法找到看似明顯的錯誤。我只是不想谷歌nullpointerexception,因爲我想我明白它是什麼。但我不明白它是如何發生在這裏的。無法啓動活動ComponentInfo可能是因爲Sqlitedatabase對象

 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類

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> 

日誌中DBAdapter.java文件

 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)  
+0

錯誤在這一行。 '遊標cursor = db1.rawQuery(query,null);',在這裏你的db1沒有被初始化,因此它是空的。 –

+0

提示:您必須將Java代碼中的R.id值與Activity佈局xml中的android:id值進行比較。該方法沒有命名爲'findViewById()':如果運行時無法找到您的ID,那麼您將得到'null' – 0X0nosugar

回答

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); 
+0

嗨,它與返回db.rawQuery(查詢,空)。謝謝。 –

+0

如果有幫助,請接受並提出答案。 –

+0

nullpointerexception現在發生在enter.setOnClickListener(MainActivity上的新View.OnClickListener()。當我引用實際的id已更新logcat時,對象'enter'如何爲null?你可以看看嗎? –

-1

試試這個在MainActivity

SQLiteDatabase db1 = this.getWritableDatabase(); 
+0

無法找到符號方法get WritableDatabase。 Sqlitehelper類必須被繼承才能工作,對吧? –

+0

他不能從MainActivity執行this.getWritableDatabase(),因爲MainActivity不是他擴展SQLiteOpenHelper的類。 –

+0

嗨,@Rabbit先生您能告訴我應該如何初始化Sqlitedatabase對象? –

相關問題