在下面的代码中,getPieceTextFile()
方法采用Activity上下文参数,但是在使用时,传入的上下文似乎为null并导致NPE。任何建议为什么会非常感激。
LogCat输出和代码清单如下所示。
logcat的
01-03 13:48:47.223: I/dalvikvm(571): threadid=3: reacting to signal 3
01-03 13:48:47.233: I/dalvikvm(571): Wrote stack traces to '/data/anr/traces.txt'
01-03 13:49:30.073: I/System.out(571): Asset Manager/IS not work.
01-03 13:49:30.073: W/System.err(571): java.io.FileNotFoundException: pieceText.txt
01-03 13:49:30.073: W/System.err(571): at android.content.res.AssetManager.openAsset(Native Method)
01-03 13:49:30.073: W/System.err(571): at android.content.res.AssetManager.open(AssetManager.java:315)
01-03 13:49:30.073: W/System.err(571): at android.content.res.AssetManager.open(AssetManager.java:289)
01-03 13:49:30.073: W/System.err(571): at com.lawson.englishlitrevision.ManipulateDatabase.getPieceTextFile(ManipulateDatabase.java:389)
01-03 13:49:30.073: W/System.err(571): at com.lawson.englishlitrevision.ManipulateDatabase.<init>(ManipulateDatabase.java:500)
01-03 13:49:30.082: W/System.err(571): at com.lawson.englishlitrevision.Novel.onCreate(Novel.java:22)
01-03 13:49:30.082: W/System.err(571): at android.app.Activity.performCreate(Activity.java:4465)
01-03 13:49:30.082: W/System.err(571): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-03 13:49:30.082: W/System.err(571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-03 13:49:30.082: W/System.err(571): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-03 13:49:30.082: W/System.err(571): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-03 13:49:30.082: W/System.err(571): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-03 13:49:30.092: W/System.err(571): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 13:49:30.092: W/System.err(571): at android.os.Looper.loop(Looper.java:137)
01-03 13:49:30.092: W/System.err(571): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-03 13:49:30.092: W/System.err(571): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 13:49:30.092: W/System.err(571): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 13:49:30.092: W/System.err(571): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-03 13:49:30.092: W/System.err(571): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-03 13:49:30.102: W/System.err(571): at dalvik.system.NativeStart.main(Native Method)
01-03 13:49:30.102: W/dalvikvm(571): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-03 13:49:30.123: E/AndroidRuntime(571): FATAL EXCEPTION: main
01-03 13:49:30.123: E/AndroidRuntime(571): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lawson.englishlitrevision/com.lawson.englishlitrevision.Novel}: java.lang.NullPointerException
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.os.Looper.loop(Looper.java:137)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-03 13:49:30.123: E/AndroidRuntime(571): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 13:49:30.123: E/AndroidRuntime(571): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 13:49:30.123: E/AndroidRuntime(571): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-03 13:49:30.123: E/AndroidRuntime(571): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-03 13:49:30.123: E/AndroidRuntime(571): at dalvik.system.NativeStart.main(Native Method)
01-03 13:49:30.123: E/AndroidRuntime(571): Caused by: java.lang.NullPointerException
01-03 13:49:30.123: E/AndroidRuntime(571): at java.io.Reader.<init>(Reader.java:64)
01-03 13:49:30.123: E/AndroidRuntime(571): at java.io.InputStreamReader.<init>(InputStreamReader.java:79)
01-03 13:49:30.123: E/AndroidRuntime(571): at com.lawson.englishlitrevision.ManipulateDatabase.<init>(ManipulateDatabase.java:500)
01-03 13:49:30.123: E/AndroidRuntime(571): at com.lawson.englishlitrevision.Novel.onCreate(Novel.java:22)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.Activity.performCreate(Activity.java:4465)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-03 13:49:30.123: E/AndroidRuntime(571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-03 13:49:30.123: E/AndroidRuntime(571): ... 11 more
01-03 13:49:30.553: I/dalvikvm(571): threadid=3: reacting to signal 3
01-03 13:49:30.563: I/dalvikvm(571): Wrote stack traces to '/data/anr/traces.txt'
01-03 13:49:30.683: I/dalvikvm(571): threadid=3: reacting to signal 3
01-03 13:49:30.693: I/dalvikvm(571): Wrote stack traces to '/data/anr/traces.txt'
代码
/**
* 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 android.content.res.AssetManager;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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;
/**
* File for the BufferedReader to read into Database
*/
private File pieceList;
/**
* Method to get pieceText file from assets for BufferedReader to use
*
* @param ctx
* @throws IOException
*/
private InputStream getPieceTextFile(Activity ctx) throws IOException {
try {
AssetManager manager = ctx.getAssets();
InputStream is = manager.open("pieceText.txt");
return is;
} catch (Exception e) {
System.out.println("Asset Manager/IS not work.");
e.printStackTrace();
return null;
}
}
/*
* private File specificList = new File("specificList.txt");
*
* private BufferedReader specificScan = new BufferedReader(new FileReader(
* "specificList.txt"));
*
* private File elementList = new File("elementList.txt");
*
* private BufferedReader elementScan = new BufferedReader(new FileReader(
* "elementList.txt"));
*
* private File quoteList = new File("quoteList.txt");
*
* private BufferedReader quoteScan = new BufferedReader(new FileReader(
* "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");
ArrayList<String> defaultReturn = new ArrayList<String>();
defaultReturn.add("There is is default item.");
defaultReturn.add("Because the proper ArrayList");
defaultReturn.add("Wasn't filled properly");
return defaultReturn;
}
}
public ArrayList<String> getAllPieces() {
try {
openSesame();
ArrayList<String> allPieces = new ArrayList<String>();
String instruction = "SELECT * FROM pieceTable";
Cursor cursor = dataBase.rawQuery(instruction, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
allPieces.add(cursor.getString(cursor
.getColumnIndex(pieceField)));
cursor.moveToNext();
}
closeSesame();
return allPieces;
} catch (Exception e) {
e.printStackTrace();
ArrayList<String> defaultList = new ArrayList<String>();
defaultList.add("Catch default");
return defaultList;
}
}
/**
* Constructor
*
* @param contextIn
* Context of the MainpuxlateDatabase class
* @throws IOException
*/
public ManipulateDatabase(Activity contextIn) throws IOException {
baseHelper = new DatabaseHelper(contextIn);
context = contextIn;
BufferedReader pieceScan = new BufferedReader(new InputStreamReader(
getPieceTextFile(context), "UTF-8"));
openSesame();
String line;
String x;
String pieceName;
String isDrama;
String point;
String element;
String quote;
String isCharacter;
int commaPoint;
int commaPoint2;
if (true) {
while ((x = pieceScan.readLine()) != null) {
line = pieceScan.readLine();
System.out.println(line);
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 ((x = specificScan.readLine()) != null) { line =
* specificScan.readLine(); System.out.println(line); 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 ((x =
* elementScan.readLine()) != null) { line = elementScan.readLine();
* System.out.println(line); 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 ((x = quoteScan.readLine()) != null) { line =
* quoteScan.readLine(); System.out.println(line); 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 :(得分:1)
这不是因为您的上下文为空。
getPieceTextFile返回null(可能已从异常部分返回),而BufferReaderCreation也在第500行失败。
确保资产文件夹中有pieceText.txt文件