Android数据库问题

时间:2014-02-11 16:33:21

标签: java android sqlite

我是Android新手,在这里我希望在点击按钮时向数据库添加一些数据,但是当我这样做时,应用程序崩溃并且日志cat返回“无法实例化活动,空指针异常” 。
我出了什么问题?

MainActivity.java

package com.example.lockerbox;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

final Context context=this;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


public void faq(View view)
{
    Intent intent2 = new Intent(context,faq.class);
    intent2.setAction("com.example.lockerbox.faq");
    startActivity(intent2);
}

public void question(View arg0)
{
    Intent intent1 = new Intent(context,questions.class);
    intent1.setAction("com.example.lockerbox.questions");
    startActivity(intent1);
}       

}

questions.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class questions extends Activity {
String questiontext=findViewById(R.id.qtext).toString();
String answertext=findViewById(R.id.atext).toString();      
Button button;
final Context context=this;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.questionplace);


}

public void Done(View view)   //when i remove this the app works by showing me the 
                                  //graphic layout defined in questionplace.xml
{
    DatabaseClass db=new DatabaseClass(this);

    // Inserting Questions and Answers
    Log.d("Insert: ", "Inserting .."); 
    db.addQuestionAnswer(questiontext,answertext);    

}

}

DatabaseClass.java

package com.example.lockerbox;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseClass extends SQLiteOpenHelper{

private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "LockerBox_DB";

// Contacts table name
private static final String TABLE_LOCKERBOX="LockerBox_T";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_Q = "question";
private static final String KEY_A = "answer";

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

//Creating Tables
@Override
    public void onCreate(SQLiteDatabase db) {
    String CREATE_QUERY = "CREATE TABLE " + TABLE_LOCKERBOX + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_Q + " TEXT,"
            + KEY_A + " TEXT" + ")";
    db.execSQL(CREATE_QUERY);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCKERBOX);

    // Create tables again
    onCreate(db);

}
// Adding new question and answer
public void addQuestionAnswer(String question,String answer){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues value=new ContentValues();
    value.put(KEY_Q,question);
    value.put(KEY_A,answer);

    db.insert(TABLE_LOCKERBOX,null,value);
    db.close();

}

}

questionplace.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >

<EditText
    android:id="@+id/qtext"
    android:layout_width="285dp"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/Question_Here"
    android:inputType="textMultiLine" />

<EditText
    android:id="@+id/atext"
    android:layout_width="285dp"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/Answer_Here"
    android:inputType="textPassword"
    />

<Button
    android:id="@+id/Done_Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/QFinish" 
     android:onClick="Done"
    />

<Button
    android:id="@+id/AnotherQ"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Another_Question"
     android:onClick="AnotherQ" />

</LinearLayout>

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lockerbox"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.lockerbox.MainActivity"
        android:label="@string/app_name"

         >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".questions"
        android:label="@string/app_name"
    />

    <activity
        android:name=".faq"
        android:label="@string/app_name"
    />
</application>

</manifest>

创建日志

02-11 10:55:19.861: I/Choreographer(1326): Skipped 72 frames!  The application may     be doing too much work on its main thread.
02-11 10:55:36.451: D/gralloc_goldfish(1369): Emulator without GPU emulation detected.
02-11 10:55:38.281: I/Choreographer(1369): Skipped 52 frames!  The application may be doing too much work on its main thread.
02-11 10:55:38.591: D/AndroidRuntime(1369): Shutting down VM
02-11 10:55:38.591: W/dalvikvm(1369): threadid=1: thread exiting with uncaught exception (group=0xaf683b90)
02-11 10:55:38.711: E/AndroidRuntime(1369): FATAL EXCEPTION: main
02-11 10:55:38.711: E/AndroidRuntime(1369): Process: com.example.lockerbox, PID: 1369
02-11 10:55:38.711: E/AndroidRuntime(1369): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.lockerbox/com.example.lockerbox.questions}: java.lang.NullPointerException
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2102)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.os.Looper.loop(Looper.java:137)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.ActivityThread.main(ActivityThread.java:4998)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at java.lang.reflect.Method.invokeNative(Native Method)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at java.lang.reflect.Method.invoke(Method.java:515)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at dalvik.system.NativeStart.main(Native Method)
02-11 10:55:38.711: E/AndroidRuntime(1369): Caused by: java.lang.NullPointerException
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.Activity.findViewById(Activity.java:1883)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at com.example.lockerbox.questions.<init>(questions.java:13)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at java.lang.Class.newInstanceImpl(Native Method)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at java.lang.Class.newInstance(Class.java:1208)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
02-11 10:55:38.711: E/AndroidRuntime(1369):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
02-11 10:55:38.711: E/AndroidRuntime(1369):     ... 11 more
02-11 10:55:42.551: I/Process(1369): Sending signal. PID: 1369 SIG: 9
02-11 10:55:46.261: D/gralloc_goldfish(1403): Emulator without GPU emulation detected.
02-11 11:00:48.971: I/Choreographer(1403): Skipped 113 frames!  The application may be doing too much work on its main thread.

我想要的是当我点击/点击按钮“完成”时应该在表格中输入一个条目,但我相信我在questions.java中处理按钮“完成”以执行查询的方式是错误的。

1 个答案:

答案 0 :(得分:2)

初始化上下文如下

  final Context context;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  context =this; 

以下内容应位于onCreate之后的setContentView

  String questiontext=findViewById(R.id.qtext).toString();
  String answertext=findViewById(R.id.atext).toString();