java - Android 数据库问题

标签 java android sqlite

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

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);
}       

}

问题.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 中处理按钮“完成”来执行查询的方式是错误的。

最佳答案

初始化上下文如下

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

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

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

关于java - Android 数据库问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21707553/

相关文章:

java - 我的 JSONobject 正在替换以前的 JSONobject

java - 将依赖项目添加到类路径的更好方法?

java - redis.clients.jedis.exceptions.JedisConnectionException : Could not get a resource from the pool while connecting to redis cluster

java - 大九片拉伸(stretch)

android - 如何使用Android Studio导出jar文件?

安卓 SQLite fts3 : What should I insert: null values OR empty strings?

java - 表情符号字符序列👇打破了旧的 XML 过程

java - LoginActivity.AttemptLogin 不是抽象的,不会覆盖 AsyncTask 中的抽象方法 doInBackground(Object...)

mysql - 将mysql数据库复制到sqlite数据库

python - Ubuntu 中的 PySide 或 PyQT SQLite 支持