我有一个Android项目(在模拟器中运行),其中单击主菜单上的“Novels”按钮应该导致SQL数据库中'pieceTable'中typeField = 0(即false)的片段值通过ArrayList显示在ListActivity中。
然而,当点击Novels按钮时,应用程序停止并显示一个对话框,说明'不幸的是,EnglishLitRevision已经停止'。没有LogCat输出。
如果这是一个非常基本的错误,我不会感到惊讶,但如果有人能够发现问题,我将不胜感激。
更新 - 在LogCat上,过滤器未设置为“错误”!
LogCat输出如下所示:
01-02 18:26:06.344: E/AndroidRuntime(548): FATAL EXCEPTION: main
01-02 18:26:06.344: E/AndroidRuntime(548): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lawson.englishlitrevision/com.lawson.englishlitrevision.Novel}: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.os.Looper.loop(Looper.java:137)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-02 18:26:06.344: E/AndroidRuntime(548): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 18:26:06.344: E/AndroidRuntime(548): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 18:26:06.344: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-02 18:26:06.344: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-02 18:26:06.344: E/AndroidRuntime(548): at dalvik.system.NativeStart.main(Native Method)
01-02 18:26:06.344: E/AndroidRuntime(548): Caused by: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ListView.setAdapter(ListView.java:460)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ListActivity.setListAdapter(ListActivity.java:265)
01-02 18:26:06.344: E/AndroidRuntime(548): at com.lawson.englishlitrevision.Novel.onCreate(Novel.java:24)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.Activity.performCreate(Activity.java:4465)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-02 18:26:06.344: E/AndroidRuntime(548): ... 11 more
如果有人能够确定错误的原因,我将不胜感激。
以下是三个相关课程的代码。
主菜单:
/**
* Main Menu (launcher item)
* @author Daniel Lawson
* @Version 29/12/13
*/
package com.lawson.englishlitrevision;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainMenu extends Activity {
/** Button for accessing novels area */
private Button novelBut;
/** Button for accessing plays area */
private Button playBut;
/** Button for viewing progress/statistics */
private Button progressBut;
/** Button for viewing about screen */
private Button aboutBut;
/** Button for exiting the application */
private Button exitBut;
/**
* Method called when activity is started. Sets up required data.
*
* @param savedInstanceState
* : The saved state of the application
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sets up layout
setContentView(R.layout.main_menu_layout);
createButton();
}
/** Sets up the buttons */
public void createButton() {
novelBut = (Button) findViewById(R.id.novelBut);
playBut = (Button) findViewById(R.id.playBut);
progressBut = (Button) findViewById(R.id.addNovBut);
aboutBut = (Button) findViewById(R.id.aboutBut);
exitBut = (Button) findViewById(R.id.exitBut);
}
/**
* Method called when novel button is clicked. Starts novel activity.
*
* @param novBut
* : The view of the novel button, which has been clicked.
*/
public void goNovel(View novBut) {
startActivity(new Intent(this, Novel.class));
}
/**
* Method called when play button is clicked. Starts play activity.
*
* @param playBut
* : The view of the play button, which has been clicked.
*/
public void goPlay(View playBut) {
startActivity(new Intent(this, Play.class));
}
/**
* Method called when progress button is clicked. Starts stats activity.
*
* @param progBut
* : The view of the progress button, which has been clicked.
*/
public void goStats(View progBut) {
startActivity(new Intent(this, Stats.class));
}
/**
* Method called when abpit button is clicked. Starts about activity.
*
* @param aboutBut
* : The view of the about button, which has been clicked.
*/
public void goAbout(View aboutBut) {
startActivity(new Intent(this, About.class));
}
/**
* Method called when exit button is clicked. Quits application.
*
* @param closeBut
* : The view of the exit button, which has been clicked.
*/
public void goClose(View closeBut) {
this.finish();
}
}
小说:
package com.lawson.englishlitrevision;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Context;
public class Novel extends ListActivity {
ArrayList<String> novels = new ArrayList<String>();
@Override
public void onCreate(Bundle icicle) {
ManipulateDatabase md = new ManipulateDatabase(this);
super.onCreate(icicle);
novels = md.getPieces("0");
setContentView(R.layout.novel_layout);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, novels));
}
public void addNovel() {
// show text input
// add the String put in to database as new novel
// update list
}
public void deleteNovel() {
// show checkboxes
// allow selection
// delete selected records from database
// update list
}
}
ManipulateDatabase:
/**
* Contains SQL statements and manages connections
*
* @author Daniel Lawson
* @version 29/12/13
*/
package com.lawson.englishlitrevision;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import java.util.ArrayList;
import java.util.Scanner;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class ManipulateDatabase {
/** String representing the name of the database */
private static final String databaseName = "EnglishDatabase.db";
/** Int representing the current version of the database */
private static final int databaseVersion = 1;
// ----------------------------------------------------------------------------------
/**
* String representing the table that stores the name of the piece and
* whether it is a play or not.
*/
private static final String pieceTable = "pieceTable";
/**
* String representing the table that stores the name of the point made,
* which piece it belongs to, and which element it pertains to.
*/
private static final String specificTable = "specificTable";
/**
* String representing the table that stores the element, the piece it
* belongs to, and whether or not it is a character.
*/
private static final String elementTable = "elementTable";
/**
* String representing the table that stores the quote and the point it
* links to.
*/
private static final String quoteTable = "quoteTable";
/**
* String representing the table that stores the piece and the
* correct/incorrect responses on various dates
*/
private static final String statsTable = "statsTable";
// ----------------------------------------------------------------------------------
/** String representing the piece field of the piece table */
private static final String pieceField = "piece";
/** String representing the type field of the piece table */
private static final String typeField = "isPlay";
/** String representing the point field of the specific table */
private static final String pointField = "point";
/** String representing the element field of the element table */
private static final String elementField = "element";
/** String representing the elType field of the element table */
private static final String elTypeField = "isCharacter";
/** String representing the quote field of the quote table */
private static final String quoteField = "quote";
/** String representing the ID field of the stats table */
private static final String idField = "statId";
/** String representing the correct field of the stats table */
private static final String correctField = "correct";
/** String representing the incorrect field of the stats table */
private static final String incorrectField = "incorrect";
/** String representing the date field of the stats table */
private static final String dateField = "date";
// ----------------------------------------------------------------------------------
/** String array representing all the fields of the piece table */
private static final String[] pieceTableFields = { pieceField, typeField };
/** String array representing all the fields of the specific table */
private static final String[] specificTableFields = { pointField,
pieceField, elementField };
/** String array representing all the fields of the quote table */
private static final String[] quoteTableFields = { quoteField, pointField };
/** String array representing all the fields of the element table */
private static final String[] elementTableFields = { elementField,
pieceField, elTypeField };
/** String array representing all the fields of the stats table */
private static final String[] statsTableFields = { idField, pieceField,
correctField, incorrectField, dateField };
// ----------------------------------------------------------------------------------
/** SQL statement to create the piece table. */
private static final String createPieceTable = "CREATE TABLE " + pieceTable
+ " (" + pieceField + " TEXT NOT NULL PRIMARY KEY, " + typeField
+ " INTEGER);";
/** SQL statement to create the specific table. */
private static final String createSpecificTable = "CREATE TABLE "
+ specificTable + "(" + pointField + " TEXT NOT NULL PRIMARY KEY,"
+ pieceField + " TEXT NOT NULL," + elementField + " TEXT NOT NULL)";
/** SQL statement to create the quotes table. */
private static final String createQuoteTable = "CREATE TABLE " + quoteTable
+ "(" + quoteField + " TEXT NOT NULL PRIMARY KEY," + pointField
+ " TEXT NOT NULL PRIMARY KEY)";
/** SQL statement to create the element table. */
private static final String createElementTable = "CREATE TABLE "
+ elementTable + "(" + elementField + " TEXT NOT NULL PRIMARY KEY,"
+ pieceField + " TEXT NOT NULL," + elTypeField + " INTEGER)";
/** SQL statement to create the stats table. */
private static final String createStatsTable = "CREATE TABLE " + statsTable
+ "(" + idField + " INTEGER PRIMARY KEY," + pieceField
+ " TEXT NOT NULL," + correctField + " INTEGER," + incorrectField
+ " INTEGER," + dateField + " DATE)";
// ----------------------------------------------------------------------------------
/**
* SQL statement to search the piece table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchPieceTable = "SELECT * FROM "
+ pieceTable + " WHERE [columnName] = '[value]';";
/**
* SQL statement to search the specific table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchSpecificTable = "SELECT * FROM "
+ specificTable + " WHERE [columnName] = '[value]'";
/**
* SQL statement to search the quote table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchQuoteTable = "SELECT * FROM "
+ quoteTable + " WHERE [columnName] = '[value]'";
/**
* SQL statement to search the element table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchElementTable = "SELECT * FROM "
+ elementTable + " WHERE [columnName] = '[value]'";
/**
* SQL statement to search the stats table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchStatsTable = "SELECT * FROM "
+ statsTable + " WHERE [columnName] = '[value]'";
// ----------------------------------------------------------------------------------
/**
* SQL statement to update the piece table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updatePieceTable = "UPDATE " + pieceTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the specific table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateSpecificTable = "UPDATE " + specificTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the quote table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateQuoteTable = "UPDATE " + quoteTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the element table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateElementTable = "UPDATE " + elementTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the stats table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateStatsTable = "UPDATE " + statsTable
+ " SET [assignValues] WHERE [condition]";
// ----------------------------------------------------------------------------------
/**
* SQL statement to delete from the piece table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromPieceTable = "DELETE FROM "
+ pieceTable + " WHERE [condition]";
/**
* SQL statement to delete from the specific table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromSpecificTable = "DELETE FROM "
+ specificTable + " WHERE [condition]";
/**
* SQL statement to delete from the quote table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromQuoteTable = "DELETE FROM "
+ quoteTable + " WHERE [condition]";
/**
* SQL statement to delete from the element table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromElementTable = "DELETE FROM "
+ elementTable + " WHERE [condition]";
/**
* SQL statement to delete from the stats table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromStatsTable = "DELETE FROM "
+ statsTable + " WHERE [condition]";
// ----------------------------------------------------------------------------------
/**
* SQL statement to insert into the piece table - replace [values] with the
* values to be inserted.
*/
private static final String insertIntoPieceTable = "INSERT INTO "
+ pieceTable + " VALUES ([values])";
/**
* SQL statement to insert into the specific table - replace [values] with
* the values to be inserted.
*/
private static final String insertIntoSpecificTable = "INSERT INTO "
+ specificTable + " VALUES ([values])";
/**
* SQL statement to insert into the quote table - replace [values] with the
* values to be inserted.
*/
private static final String insertIntoQuoteTable = "INSERT INTO "
+ quoteTable + " VALUES ([values])";
/**
* SQL statement to insert into the element table - replace [values] with
* the values to be inserted.
*/
private static final String insertIntoElementTable = "INSERT INTO "
+ elementTable + " VALUES ([values])";
/**
* SQL statement to insert into the quote table - replace [values] with the
* values to be inserted.
*/
private static final String insertIntoStatsTable = "INSERT INTO "
+ statsTable + " VALUES ([values])";
// ----------------------------------------------------------------------------------
/**
* SQLiteDatabase representing the English database
*/
private SQLiteDatabase dataBase;
/**
* Instance of DatabaseHelper class utilised to 'access' database
*/
private DatabaseHelper baseHelper;
/**
* Content of the Database Manipulator (ManipulateDatabase class)
*/
private Activity context;
/**
* Boolean to store whether or not this is the first time this base/version
* has been launched
*/
private boolean initialLaunch = false;
/**
* Scanners to read the .txt lists to to input to database
*/
private Scanner pieceScan = new Scanner("pieceList.txt");
private Scanner specificScan = new Scanner("specificList.txt");
private Scanner elementScan = new Scanner("elementList.txt");
private Scanner quoteScan = new Scanner("quoteList.txt");
/**
* Method to open the database
*/
private void openSesame() {
try {
dataBase = baseHelper.getWritableDatabase();
} catch (SQLiteException e) {
System.out.println("Database couldn't be opened");
e.printStackTrace();
}
}
/**
* Method to close the database
*/
private void closeSesame() {
baseHelper.close();
}
public ArrayList<String> getPieces(String typePiece) {
try {
openSesame();
ArrayList<String> pieces = new ArrayList<String>();
String command = searchPieceTable
.replace("[columnName]", typeField);
command = command.replace("[value]", typePiece);
Cursor cursor = dataBase.rawQuery(command, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
pieces.add(cursor.getString(cursor.getColumnIndex(pieceField)));
cursor.moveToNext();
}
closeSesame();
return pieces;
} catch (SQLiteException e) {
e.printStackTrace();
System.out.println("SQL Problem");
return null;
}
}
/**
* Constructor
*
* @param contextIn
* Context of the MainpulateDatabase class
*/
public ManipulateDatabase(Activity contextIn) {
baseHelper = new DatabaseHelper(contextIn);
context = contextIn;
openSesame();
String line;
String pieceName;
String isDrama;
String point;
String element;
String quote;
String isCharacter;
int commaPoint;
int commaPoint2;
if (initialLaunch) {
while (pieceScan.hasNext()) {
line = pieceScan.nextLine();
commaPoint = line.indexOf(",");
pieceName = line.substring(0, commaPoint);
isDrama = line.substring(commaPoint + 1, line.length() - 1);
ContentValues pv = new ContentValues();
pv.put(pieceField, pieceName);
pv.put(typeField, isDrama);
dataBase.insert(pieceTable, null, pv);
System.out.println("DAMN YOU MORONIC CRETIN!!");
}
while (specificScan.hasNext()) {
line = specificScan.nextLine();
commaPoint = line.indexOf(",");
point = line.substring(0, commaPoint);
commaPoint2 = (line
.substring(commaPoint + 1, line.length() - 1)
.indexOf(","));
pieceName = line.substring(commaPoint + 1, commaPoint2);
element = line.substring(commaPoint2 + 1, line.length() - 1);
ContentValues sv = new ContentValues();
sv.put(pointField, point);
sv.put(pieceField, pieceName);
sv.put(elementField, element);
dataBase.insert(specificTable, null, sv);
}
while (elementScan.hasNext()) {
line = elementScan.nextLine();
commaPoint = line.indexOf(",");
element = line.substring(0, commaPoint);
commaPoint2 = (line
.substring(commaPoint + 1, line.length() - 1)
.indexOf(","));
pieceName = line.substring(commaPoint + 1, commaPoint2);
isCharacter = line
.substring(commaPoint2 + 1, line.length() - 1);
ContentValues ev = new ContentValues();
ev.put(elementField, element);
ev.put(pieceField, pieceName);
ev.put(elTypeField, isCharacter);
dataBase.insert(elementTable, null, ev);
}
while (quoteScan.hasNext()) {
line = quoteScan.nextLine();
commaPoint = line.indexOf(",");
quote = line.substring(0, commaPoint);
point = line.substring(commaPoint + 1, line.length() - 1);
ContentValues qv = new ContentValues();
qv.put(quoteField, quote);
qv.put(pointField, point);
dataBase.insert(quoteTable, null, qv);
}
}
}
// ----------------------------------------------------------------------------------
/**
* Database helper - Three basic methods - required database tasks
*
* @author Daniel Lawson
* @version 30/12/13
*/
private class DatabaseHelper extends SQLiteOpenHelper {
private DatabaseHelper(Context theContext) {
super(theContext, databaseName, null, databaseVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(createPieceTable);
/*
* db.execSQL(createSpecificTable);
* db.execSQL(createQuoteTable); db.execSQL(createElementTable);
* db.execSQL(createStatsTable);
*/
// initialLaunch = true;
} catch (SQLiteException e) {
System.out.println("Failed to create table(s)");
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + pieceTable);
db.execSQL("DROP TABLE IF EXISTS " + specificTable);
db.execSQL("DROP TABLE IF EXISTS " + quoteTable);
db.execSQL("DROP TABLE IF EXISTS " + elementTable);
db.execSQL("DROP TABLE IF EXISTS " + statsTable);
onCreate(db);
}
}
}
答案 0 :(得分:0)
这是你应该在logcat中查看的地方:
01-02 18:26:06.344: E/AndroidRuntime(548): Caused by: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
可能是这个电话:
novels = md.getPieces("0");
返回null值,但是从我看到的情况来看,只有在内部存在异常时才会发生这种情况:
public ArrayList<String> getPieces(String typePiece) {
所以在这个函数中寻找问题。
答案 1 :(得分:0)
novels
ArrayList为空
Caused by: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
ArrayAdapter.java:330
328
329 public int getCount() {
330 return mObjects.size();
331 }
ArrayAdapter
使用getCount返回列表大小,表示novels
为空,这意味着你应该看看
novels = md.getPieces("0");