I have two tables, one is loading fine without error and I can retrieve the data. The other one will be used to store user data. I have pre-populated the first table with data, but want to populate the user data table based on user creating an account. I'm using a DialogFragment to obtain the username and password. I've tried inserting the data into the user table using an sql insert string, and using Content values. Both times I get the error. I've been looking at this for 3 days and cannot find the problem. As soon as I enter a user name and password, and click on "sign in", I get the exception when it calls the addNewUser() method in the DBHandler class. Can someone please point me in the right direction? Here is the error message I am receiving when trying to invoke addNewUser:
11-27 11:11:23.548 22712-22712/com.rasmussenandroid.sandra.edutrivia I/ContentValues: addNewUser start, DBhandler-addNewUser 11-27 11:11:23.554 22712-22712/com.rasmussenandroid.sandra.edutrivia E/AndroidRuntime: FATAL EXCEPTION: main Process: com.rasmussenandroid.sandra.edutrivia, PID: 22712 java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
Here is my code:
DBHandler:
public class DBHandler extends SQLiteOpenHelper{
//Database Version
private static final int DATABASE_VERSION=1;
//Database Name
private static final String DATABASE_NAME ="eduTrivia";
//table names
private static final String TABLE_QUESTION="question";
private static final String TABLE_USERDATA = "userData";
//question table column names
private static final String KEY_QUESTIONID = "questionID";
private static final String KEY_QUESTION="questionName";
private static final String KEY_OPTIONA="optionA";
private static final String KEY_OPTIONB="optionB";
private static final String KEY_OPTIONC="optionC";
private static final String KEY_ANSWER="answer";
private static final String KEY_LEVEL = "questionLevelID";
private static final String KEY_CATEGORYID="categoryID";
//userData table column names
private static final String KEY_USERID = "userID";
private static final String KEY_USERNAME = "userName";
private static final String KEY_USERPASSWORD = "userPassword";
private static final String KEY_USERSCORE = "userScore";
private static final String KEY_USERLEVEL = "userLevel";
private SQLiteDatabase dbase;
public DBHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
dbase=db;
Log.i(TAG,"DB create start, DBHandler-onCreate");
String CREATE_TABLE_QUESTION ="CREATE TABLE IF NOT EXISTS "
+ TABLE_QUESTION +"("
+ KEY_QUESTIONID +" INTEGER PRIMARY KEY,"
+ KEY_QUESTION + " TEXT,"
+ KEY_OPTIONA + " TEXT,"
+ KEY_OPTIONB + " TEXT,"
+ KEY_OPTIONC + " TEXT,"
+ KEY_ANSWER + " TEXT,"
+ KEY_LEVEL + " INTEGER,"
+ KEY_CATEGORYID + " INTEGER"+")";
String CREATE_TABLE_USERDATA = "CREATE TABLE IF NOT EXISTS "
+ TABLE_USERDATA + "("
+ KEY_USERID +" INTEGER PRIMARY KEY,"
+ KEY_USERNAME + " TEXT,"
+ KEY_USERPASSWORD + " TEXT,"
+ KEY_USERSCORE + " INTEGER,"
+ KEY_USERLEVEL + " INTEGER"+ ")";
db.execSQL(CREATE_TABLE_QUESTION);
db.execSQL(CREATE_TABLE_USERDATA);
Log.i(TAG,"db create stop, DBHandler-onCreate");
Log.i(TAG,"addQuestion start, DBHnadler-onCreate");
addQuestion();
}
private String addQuestions(int qt) {
//SQLiteDatabase db = this.getWritableDatabase();
String query = "";
Integer q = qt;
switch (q) {
case 0:
query = "INSERT INTO question VALUES(0," +
"'How do you write this number using words? 752'," +
"'five hudnred sixty-two','seven hundred sixty-two', 'seven hundred fifty-two'," +
"'C',1,1)";
return query;
case 1:
query = "INSERT INTO question VALUES(1, " +
"'Round 5,764,438 to the nearest hundred thousand','6,200,000'," +
"'5,800,000','5,700,000','B',1,1)";
return query;
case 2:
query = "INSERT INTO question VALUES(2, " +
"'Which equation shows the associative property of addition','5+4=3+6'," +
"'7+(4+3)=(7+4)+3', '0+8=8','B',1,1)";
return query;
case 3:
query = "INSERT INTO question VALUES(3," +
"'Select the adjective in this sentence: Nina is a strong worker','Nina'," +
"'strong','worker', 'B',1,2)";
return query;
case 4:
query = "INSERT INTO question VALUES(4," +
"'Select the adjective in this sentence: The twon has three banks'," +
"'The','town','three','C', 1,2)";
return query;
case 5:
query = "INSERT INTO question VALUES(5," +
"'Complete the sentence with the correct form of the adjective " +
"The bark of this tree is _____than the bark of an oak tree', " +
"'smoother','smoothest', 'null','A',1,2)";
return query;
}
/* Question q7 = new Question(6, "In 1800, where did most Americans live?", "near the Atlantic Coast",
"along the Mississippi River", "along the Gulf of Mexico", "A", 1, 3);
Question q8 = new Question(7, "Which president arranfed the Lewis and Clark expedition?",
"James Madison", "Andrew Jackson", "Thomas Jefferson", "C", 1, 3);
Question q9 = new Question(8, "President Jefferson hoped the Lewis and Clark" +
"expedition could find the Northwest Passage. What was the Northwest Passage?",
"the Oregon Trail", "a secret tunnel through the Rocky Mountains",
"a water route across North America to the Pacific Ocean", "C", 1, 3);*/
return query;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//DROP older table if it exists
db.execSQL("DROP TABLE IF EXISTS "+TABLE_QUESTION);
db.execSQL("DROP TABLE IF EXISTS "+TABLE_USERDATA);
//RECREATE table
onCreate(db);
}
//constructor and getInstance() method
private static DBHandler mDBHANDLER;
public static synchronized DBHandler getInstance(Context context) {
if (mDBHANDLER==null){
mDBHANDLER=new DBHandler(context.getApplicationContext());
}
return mDBHANDLER;
}
//inserting records
public void addQuestion(){
String quests;
// SQLiteDatabase db = this.getWritableDatabase();
for (int i =0; i<6; i++){
quests=addQuestions(i);
dbase.execSQL(quests);
}
Log.i(TAG,"addQuestion ended, DBhandler-addQuestion");
}
public Integer getLastID(){
// SQLiteDatabase db = getReadableDatabase();
Cursor cursor=null;
Integer uID=0;
try {
cursor =dbase.rawQuery("SELECT max(userID) FROM userData",null);
if (cursor != null)
if (cursor.moveToFirst()) {
uID = cursor.getInt(0);
return uID;
}
else {
uID = 0;
cursor.close();
return uID;
}
} catch(Exception e){
return -1;
}
Log.i(TAG,"getLastID ended, DBhandler-getLastID");
return uID;
}
public void addNewUser(String name, String pword){
Log.i(TAG,"addNewUser start, DBhandler-addNewUser");
//dbase = getWritableDatabase();
ContentValues values = new ContentValues();
String uPword = pword;
String uName = name;
//String uName = "test";
//String uPword = "test";
Integer userid=0;
Integer userLev = 1;
Integer score = 0;
userid=(this.getLastID()+1);
values.put(KEY_USERID,userid);
values.put(KEY_USERNAME,uName);
values.put(KEY_USERPASSWORD,uPword);
values.put(KEY_USERSCORE, score);
values.put(KEY_USERLEVEL,userLev);
dbase.insert(TABLE_USERDATA,null,values);
//String sqlString = "INSERT INTO TABLE_USERDATA VALUES('"+userid+"',''"+uName+"','"+uPword+"'," +
// "'"+score+"','"+userLev+"')";
//dbase.execSQL(sqlString);
}
//reading records
/* public Question getQuestion(int id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_QUESTION, new String[]{
KEY_QUESTIONID, KEY_QUESTION
},KEY_QUESTIONID + "=?",
new String[]{
String.valueOf(id)},null,null,null,null);
//Integer.parseInt(cursor.getString(0));
if (cursor !=null)
cursor.moveToFirst();
assert cursor != null;
Question question = new Question(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2), cursor.getString(3),
cursor.getString(4),cursor.getString(5),Integer.parseInt(cursor.getString(6)),
Integer.parseInt(cursor.getString(7)));
return question;
}*/
/* public UserData getUser(int id){
//// TODO: 11/10/2016
UserData user = new UserData();
return user;
}
*/
public List<Question> getAllQuestions(){
//Select all questions query
List<Question> questionList = new ArrayList<Question>();
String selectAll = "SELECT * FROM "+TABLE_QUESTION;
Cursor cursor =getReadableDatabase().rawQuery(selectAll,null);
//loop through all rows and add to the list
if (cursor.moveToFirst()) {
do {
try {
Question question = new Question();
question.setqID(cursor.getInt(0));
question.setqName(cursor.getString(1));
question.setqOptA(cursor.getString(2));
question.setqOptB(cursor.getString(3));
question.setqOptC(cursor.getString(4));
question.setqAns(cursor.getString(5));
question.setQLevel(cursor.getInt(6));
question.setqcatID(cursor.getInt(7));
//adding to list
questionList.add(question);
} catch (Exception e) {
Log.e("DBHandler", "exception: " + e.getMessage());
Log.e("DBHandler", "exception: " + e.toString());
} finally {
// dbase.close();
//cursor.close();
Log.i(TAG,"getAllQuestions(),value of ID "+questionList);
}
} while (cursor.moveToNext());
}
// cursor.close();
return questionList;
}
public int rowCount(){
int row=0;
String selectQuery = "SELECT * FROM "+ TABLE_QUESTION;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
row=cursor.getCount();
return row;
}
public boolean databaseExist(String dbName){
boolean isExist=false;
//SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor =getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where" +
" tbl_name = '" + TABLE_QUESTION + "'", null);
if (cursor != null){
if (cursor.getCount()>0) {
isExist = true;
}
else {
isExist=false;
}
//cursor.close();
}
return isExist;
}
public void closeDB(){
SQLiteDatabase db=this.getReadableDatabase();
if (db!= null && db.isOpen())
db.close();
}
//// TODO: 11/10/2016
//update records
//delete records
}
UserData class:
public class UserData {
private Integer userID;
private String userName;
private Integer userScore;
private String userPassword;
private Integer userLevel;
public UserData(){
//// TODO: 11/5/2016
}
public UserData(Integer userID, String userName, Integer userScore, String userPassword,
Integer userLevel){
this.userID = userID;
this.userName=userName;
this.userScore = userScore;
this.userPassword = userPassword;
this.userLevel = userLevel;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getUserScore() {
return userScore;
}
public void setUserScore(Integer userScore) {
this.userScore = userScore;
}
public String getUserPassword(){
return userPassword;
}
public void setUserPassword(){
this.userPassword= userPassword;
}
public Integer getUserLevel() {
return userLevel;
}
public void setUserLevel(Integer userLevel) {
this.userLevel = userLevel;
}
}
Main Activity
public class EduTriviaMain extends AppCompatActivity
implements NoticeDialogFragment.NoticeDialogListener{
Button dialogButton;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_trivia_main);
imageView = (ImageView) findViewById(R.id.imageView);
final Animation swapimage=AnimationUtils.loadAnimation(this,R.anim.rotate);
imageView.startAnimation(swapimage);
showNoticeDialog();
}
public void showNoticeDialog(){
//creating instance of the dialog fragment and showing it
final Context context = this;
dialogButton=(Button) findViewById(R.id.signInButton);
dialogButton.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment dialog = new NoticeDialogFragment();
dialog.show(getFragmentManager(), "NoticeDialogFragment");
}
}));
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
//positive button touched // TODO: 11/25/2016
}
@Override
public void onDialogNegativeClick(DialogFragment dialog) {
//negative button touched // // TODO: 11/25/2016
}
public String onCheckedChanged(View view) {
boolean checked = ((RadioButton) view).isChecked();
String category = "";
switch (view.getId()) {
case R.id.englishRadioButton:
if (checked) {
category = "english";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.historyRadioButton:
if (checked) {
category = "history";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.mathRadioButton:
if (checked) {
category = "math";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
default:
break;
}
return category;
}
}
Notice Dialog Fragment Class:
public class NoticeDialogFragment extends DialogFragment {
Context context;
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
//used to deliver action events
NoticeDialogListener myListener;
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
myListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//getting layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final View textEntered = inflater.inflate(R.layout.signin, null);
final DBHandler handler = new DBHandler(this.context);
//inflating and setting the layout for the dialog
//passing null as the parent view since its going in the dialog layout
builder.setView(inflater.inflate(R.layout.signin, null));
builder.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
final EditText userInput = (EditText)textEntered.findViewById(R.id.username);
final EditText uPass = (EditText)textEntered.findViewById(R.id.password);
String nameInput;
String pwordInput;
nameInput = userInput.getText().toString();
pwordInput = uPass.getText().toString();
handler.addNewUser(nameInput,pwordInput);
dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
NoticeDialogFragment.this.getDialog().cancel();
dismiss();
}
});
return builder.create();
}
}