This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to create a graph from my sqlite values for example here Date vs Weight. Later on I will add Date vs Fat etc. But the apps forced close by the phone with these Logcat:
08-19 21:58:50.313 25858-25858/example.christopher.bd E/AndroidRuntime: FATAL EXCEPTION: main Process: example.christopher.bd, PID: 25858 java.lang.RuntimeException: Unable to start activity ComponentInfo{example.christopher.bd/example.christopher.bd.VIewGraph}: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference at com.jjoe64.graphview.series.DataPoint.(DataPoint.java:45) at example.christopher.bd.VIewGraph.onCreate(VIewGraph.java:48) at android.app.Activity.performCreate(Activity.java:7136) at android.app.Activity.performCreate(Activity.java:7127) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
activity to show the graph:
package example.christopher.bd;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class VIewGraph extends AppCompatActivity {
LineGraphSeries<DataPoint> series;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_graph);
mDatabaseHelper = new DatabaseHelper(this);
String y;
Float z;
Date d1;
Cursor data = mDatabaseHelper.readEntry();
int rows = data.getCount();
data.moveToFirst();
GraphView graph = (GraphView) findViewById(R.id.graph11);
series = new LineGraphSeries<DataPoint>();
for(int i = 0; i <rows; i++){
data.moveToNext();
String x = data.getString(2);
y = data.getString(3);
z = Float.parseFloat(y);
Date date1 = null;
try {
date1 = new SimpleDateFormat("dd/MM/yyyy").parse(x);
} catch (Exception e) {
e.printStackTrace();
}
series.appendData(new DataPoint(date1, z), true, 25);
}
graph.addSeries(series);
graph.getGridLabelRenderer().setNumHorizontalLabels(3);
graph.getGridLabelRenderer().setHumanRounding(false);
}
}
Here is the code for databasehelper
package example.christopher.bd;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.util.Calendar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class DatabaseHelper extends SQLiteOpenHelper{
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "BodyData";
private static final String COL1 = "ID";
private static final String COL2 = "tdate";
private static final String COL2a = "ttime";
private static final String COL3 = "weight";
private static final String COL4 = "fat";
private static final String COL5 = "hydration";
private static final String COL6 = "muscle";
private static final String COL7 = "bone";
//private static final String COL8 = "time";
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = " CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, tdate string, ttime string, weight float, fat float, hydration float, muscle float, bone float)";
//String createTable = " CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, tday integer, tmonth integer, tyear integer, weight float, fat float, hydration float, muscle float, bone float)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String tdate, String ttime, String weight, String fat, String hydration, String muscle, String bone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, tdate);
contentValues.put(COL2a, ttime);
contentValues.put(COL3, weight);
contentValues.put(COL4, fat);
contentValues.put(COL5, hydration);
contentValues.put(COL6, muscle);
contentValues.put(COL7, bone);
//contentValues.put(COL8, time);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
db.execSQL("delete from "+ TABLE_NAME);
db.close();
}
public Cursor readEntry(){
SQLiteDatabase db = this.getWritableDatabase();
String[] allColumns = new String[]{
DatabaseHelper.COL1,
DatabaseHelper.COL2,
DatabaseHelper.COL2a,
DatabaseHelper.COL3,
DatabaseHelper.COL4,
DatabaseHelper.COL5,
DatabaseHelper.COL6,
DatabaseHelper.COL7,
};
Cursor c = db.query(DatabaseHelper.TABLE_NAME, allColumns, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
activity to log the data (date, weight etc)
package example.christopher.bd;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class Logging extends AppCompatActivity {
private static final String TAG = "Logging";
DatabaseHelper mDatabaseHelper;
EditText editWeight, editFat, editHydration, editMuscle, editBone, editTime, editASD;
private Button button2;
private TextView mDisplayDate, mDisplayTime;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private TimePickerDialog.OnTimeSetListener mTimeSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logging);
button2 = (Button) findViewById(R.id.button2);
mDisplayDate = (TextView) findViewById(R.id.tvDate);
mDatabaseHelper = new DatabaseHelper(this);
mDisplayTime = (TextView) findViewById(R.id.tvTime);
editWeight = (EditText) findViewById(R.id.editWeight);
editFat = (EditText) findViewById(R.id.editFat);
editHydration = (EditText) findViewById(R.id.editHydration);
editMuscle = (EditText) findViewById(R.id.editMuscle);
editBone = (EditText) findViewById(R.id.editBone);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
Logging.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: mm/dd/yyyy: " + day + "/" + month + "/" + year);
String date = day + "/" + month + "/" + year;
mDisplayDate.setText(date);
}
};
mDisplayTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar mTime = Calendar.getInstance();
int mHour = mTime.get(Calendar.HOUR_OF_DAY);
int mMinute = mTime.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(Logging.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
mDisplayTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, true);
timePickerDialog.show();
}
});
LogData();
}
public void LogData(){
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = mDatabaseHelper.addData(
mDisplayDate.getText().toString(),
mDisplayTime.getText().toString(),
editWeight.getText().toString(),
editFat.getText().toString(),
editHydration.getText().toString(),
editMuscle.getText().toString(),
editBone.getText().toString()
);
if (isInserted == true)
Toast.makeText(Logging.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(Logging.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
});
}
}
Can anyone help me?
java.lang.NullPointerException: Attempt to invoke virtual method 'long
java.util.Date.getTime()' on a null object reference
means that you are calling/the code you are using is calling getTime() on a Date object that is null.
In more detail
Attempt to invoke virtual method 'long java.util.Date.getTime()' on a
null object reference at
com.jjoe64.graphview.series.DataPoint.(DataPoint.java:45) at
example.christopher.bd.VIewGraph.onCreate(VIewGraph.java:48)
means that this was initiated in VIewGraph.java on line 48.
Just above that there is a try-catch block to catch problems in parsing a date, but you don't check was the Date object non-null in the end. Any error is just ignored. You then feed this null Date object to series in series.appendData(new DataPoint(date1, z), true, 25);
A quick fix would be to change
try {
date1 = new SimpleDateFormat("dd/MM/yyyy").parse(x);
} catch (Exception e) {
e.printStackTrace();
}
series.appendData(new DataPoint(date1, z), true, 25);
..to...
try {
date1 = new SimpleDateFormat("dd/MM/yyyy").parse(x);
series.appendData(new DataPoint(date1, z), true, 25);
} catch (Exception e) {
e.printStackTrace();
}
It looks like you have made changes to the columns of the table (COL2a instead of COL8) If this is the case, did you uninstall the app from the device/emulator where you test it? If not you must.
The table schema dos not change every time you make changes in onCreate() of DatabaseHelper class. onCreate() is executed when the db does not exist.
Now a logical problem:
In your activity's onCreate() you execute:
data.moveToFirst();
So the cursor data is pointing at its 1st row.
Then in the 1st line of the for loop you execute:
data.moveToNext();
So the cursor data is pointing at its 2nd row (if there is a 2nd row).
So you miss the 1st row's data for sure.
But since the number of iterations is equal as the number of rows the last iteration will fetch null data!
Suggestion move data.moveToNext(); as the last statement of the for loop.
Related
Hello I'm a student and doing my final year project using sql and android studio. I want to create multiple table and I've trying to follow the example but it doesn't work. the error was no table created. Here my coding
DatabaseHelper.java
package com.example.multipletable;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import androidx.annotation.Nullable;
import static android.content.ContentValues.TAG;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MultipleTable";
private static final int DATABASE_VERSION = 3;
private static final String TABLE_1 = "register";
private static final String TABLE_2 = "activity";
private static final String TABLE_3 = "reward";
String table_1 = "CREATE TABLE "+TABLE_1+" (matricno TEXT PRIMARY KEY, password TEXT, email TEXT)";
String table_2 = "CREATE TABLE "+TABLE_2+" (id INTEGER PRIMARY KEY AUTOINCREMENT, t_question TEXT, date DEFAULT CURRENT_DATE)";
String table_3 = "CREATE TABLE "+TABLE_3+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, badge_green TEXT, badge_purple TEXT, badge_maroon TEXT)";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(table_1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Current version"+db.getVersion());
for (int version=oldVersion+1; version<=newVersion; version++) {
switch (version) {
case 2:
db.execSQL(table_2);
case 3:
db.execSQL(table_3);
}
}
// Log.e("DATABASE VERSION", db.getVersion()+" ");
//
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_1);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_2);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_3);
//
// onCreate(db);
}
public boolean insert(String matNo, String pswd, String email) {
SQLiteDatabase db_1 = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put("MatricNo", matNo);
contentValues1.put("Password", pswd);
contentValues1.put("Email", email);
db_1.insert(TABLE_1, null, contentValues1);
return true;
}
public boolean insert2(String question) {
SQLiteDatabase db_2 = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put("Question", question);
contentValues2.put("Date", getDate());
db_2.insert(TABLE_2, null, contentValues2);
return true;
}
public boolean insert3(String green, String purple, String maroon) {
SQLiteDatabase db_3 = this.getWritableDatabase();
ContentValues contentValues3 = new ContentValues();
contentValues3.put("Reward1", green);
contentValues3.put("Reward2", purple);
contentValues3.put("Reward3", maroon);
db_3.insert(TABLE_3, null, contentValues3);
return true;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
MainActiviti.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name, pswd, email;
Button btn_1;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.txt_name);
pswd = findViewById(R.id.txt_password);
email = findViewById(R.id.txt_email);
btn_1 = findViewById(R.id.btn_next_1);
db = new DatabaseHelper(this);
btn_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String person = name.getText().toString();
String pass = pswd.getText().toString();
String mail = email.getText().toString();
Boolean insert = db.insert(person, pass, mail);
if (insert==true) {
Toast.makeText(getApplicationContext(), "Data 1 saved", Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
startActivity(intent1);
}
else {
Toast.makeText(getApplicationContext(), "Data 1 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity2.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity2 extends AppCompatActivity {
EditText question;
Button btn2;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
question = findViewById(R.id.txt_question);
btn2 = findViewById(R.id.btn_next_2);
db = new DatabaseHelper(this);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ques = question.getText().toString();
Boolean insert2 = db.insert2(ques);
if (insert2==true) {
Toast.makeText(getApplicationContext(), "Data 2 saved", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Activity2.this, Activity3.class);
startActivity(intent2);
}
else {
Toast.makeText(getApplicationContext(), "Data 2 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity3.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity3 extends AppCompatActivity {
EditText green, purple, maroon;
Button btn3;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
green = findViewById(R.id.txt_green);
purple = findViewById(R.id.txt_purple);
maroon = findViewById(R.id.txt_maroon);
btn3 = findViewById(R.id.btn_next_3);
db = new DatabaseHelper(this);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String grn = green.getText().toString();
String ppl = purple.getText().toString();
String mrn = maroon.getText().toString();
Boolean insert3 = db.insert3(grn, ppl, mrn);
if (insert3==true) {
Toast.makeText(getApplicationContext(), "Data 3 saved", Toast.LENGTH_SHORT).show();
Intent intent3 = new Intent(Activity3.this, FINISH.class);
startActivity(intent3);
}
else {
Toast.makeText(getApplicationContext(), "Data 3 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Can you please help me find the solution and tell me what is wrong :(
I am not sure where your error comes from but, I am assuming its on launch or when you insert the data.
I create my SQL table like below.
However, I did encounter a really annoying issue of if I change my table my app would crash as it would not find it. The fix was I needed to uninstall the app on my phone before uploading the application from android studio to my phone. Hope it helps
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="TESTING.db";
// Database Version
private static final int DATABASE_VERSION = 1;
public static final String TABLE_1 = "T1";
public static final String TABLE_2 = "T2";
public static final String TABLE_3 = "T3";
public static final String COL1 = "ID";
public static final String COL2 = "D1";
public static final String COL3 = "D2";
public static final String COL4 = "D3";
public static final String COL5 = "D4";
public static final String COL6 = "D5";
public static final String COL7 = "D6";
public static final String COL8 = "time";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
String Created_TABLE_1= "CREATE TABLE " + TABLE_1 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_2= "CREATE TABLE " + TABLE_2 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_3= "CREATE TABLE " + TABLE_3 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
db.execSQL(Created_TABLE_1);
db.execSQL(Created_TABLE_2);
db.execSQL(Created_TABLE_3);
}
Ps Stay safe all
Thank you Eugene Troyanskii, forpas and Thomas Morris. I've solved the problem. Supposed to be assign with correct name for column according to create table statement at inserting data code, but I write it different.
Again thanks guys!
I'm trying to insert some values into an SQLite Database which are entered by the user, however when I press the button to save the values it crashes and a NullPointer exception is thrown:
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 at com.example.w4e74.farmanimalfinal.DatabaseHelper.insertRecord(DatabaseHelper.java:61)at com.example.w4e74.farmanimalfinal.Activity_item.onOptionsItemSelected(Activity_item.java:66)
I do not know what is causing the exception. My code is below, any help would be very appreciated.
Activity_item.java
package com.example.w4e74.farmanimalfinal;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewDebug;
import android.widget.EditText;
import android.widget.ListView;
public class Activity_item extends AppCompatActivity {
EditText editText_item;
boolean newItem;
long item_index;
private SQLiteDatabase db;
private Cursor cursor;
CustomCursorAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
DatabaseHelper db = new DatabaseHelper(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_item);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
item_index = intent.getLongExtra("item_index", -1);
if(item_index == -1) {
newItem = true;
} else {
newItem = false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_item:
DatabaseHelper.insertRecord(db, (R.id.editText_date),(R.id.editText_time), Integer.toString(R.id.editText_staff),(R.id.editText_animal),Integer.toString(R.id.editText_activity),Integer.toString(R.id.editText_details));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabaseHelper.java
package com.example.w4e74.farmanimalfinal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "farmanimals";
private static final int DB_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE RECORD ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "DATE INTEGER, "
+ "TIME INTEGER, "
+ "STAFF TEXT,"
+ "ANIMAL INTEGER,"
+ "ACTIVITY TEXT,"
+ "DETAIL TEXT);"
);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
#Override
public void onDowngrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public static long insertRecord(SQLiteDatabase db, int date, int time, String staff, int animal, String activity, String detail ) {
ContentValues recordValues = new ContentValues();
recordValues.put("DATE", date);
recordValues.put("TIME", time);
recordValues.put("STAFF", staff);
recordValues.put("ANIMAL", animal);
recordValues.put("ACTIVITY", activity);
recordValues.put("DETAIL", detail);
long newRecordID = db.insert("RECORD", null, recordValues);
return newRecordID;
}
public static String getDatabaseContentsAsString(SQLiteDatabase db) {
Cursor cursor = db.query("RECORD",
new String[]{"_id", "DATE", "TIME", "STAFF", "ANIMAL", "ACTIVITY", "DETAIL"},
null, null, null, null, "_id ASC");
String databaseAsString = System.getProperty("line.separator");
if(cursor.getCount() != 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
for (int i=0; i < cursor.getColumnCount() - 1; i++) {
databaseAsString += cursor.getString(i) + " ";
}
databaseAsString += System.getProperty("line.separator");
cursor.moveToNext();
}
if(cursor != null) cursor.close();
}
return databaseAsString;
}
public static void deleteRecord(SQLiteDatabase db, Long id) {
db.delete("RECORD", "_id=?", new String[] {Long.toString(id)});
}
public static void deleteAllRecords(SQLiteDatabase db) {
db.delete("RECORD", null, null);
db.delete("SQLITE_SEQUENCE","NAME = ?",new String[]{"RECORD"});
}
}
Edit: Error message received:
Incompatible types.
Required:
android.database.sqlite.SQLiteDatabase
Found:
com.example.w4e74.farmanimalfinal.DatabaseHelper
Your problem is the scope of db In onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
DatabaseHelper db = new DatabaseHelper(this);
...
}
You have this instance of db declared as a local variable, effectively creating two variables, both called db but operating at different scopes. This means that as soon as onCreate() is finished, this reference to db will be lost and garbage collected.
Your two instances of db are also of different types - SQLiteDatabase and DatabaseHelper, so a better variable naming strategy would help avoid problems like this in the future. As we'll be using the SQLiteDatabase version of db, we'll need to grab a writable instance of your database to use with the helper in future:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
db = new DatabaseHelper(this).getWritableDatabase();
...
}
This will ensure that you're setting the member variable rather than a local variable.
This is the code for getting the table RECORD from the SQLiteDatebase. In the try block something goes wrong and it always throws the SQLiteException. All I am trying to do here is to convert each row of the table "RECORD" into a string and add it to an ArrayList, subsequently connect the array to the ArrayAdapter, and finally use ListView to display the array.
package com.example.tommy.stop_watch_real;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import java.util.ArrayList;
public class RecordList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_list);
ListView temp = (ListView) findViewById(R.id.recordList);
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
**try {
SQLiteOpenHelper dataBaseHelper = new DataBaseHelper(this);
SQLiteDatabase db = dataBaseHelper.getReadableDatabase();
Cursor cursor = db.query("RECORD", new String[] {"_id, DATE, MINUTES"}, null, null,null,null,null);
while (cursor.moveToFirst()){
String id = Integer.toString(cursor.getInt(0));
String date = cursor.getString(1);
String minutes = Integer.toString(cursor.getInt(2));
String finalValue = id + "|" + date + "|" + minutes;
arrayList.add(finalValue);
}
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList);
temp.setAdapter(adapter);
cursor.close();
db.close();}**
catch (SQLiteException e) {
Toast.makeText(RecordList.this, "Database not available", Toast.LENGTH_LONG).show();
}
}
}
This is the code for my datebaseHelper:
class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Record"; // name of the database
private static final int DB_VERSION = 1; //Version
DataBaseHelper (Context context){
super(context, DB_NAME, null, DB_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE RECORD ("
+ "_id INTEGER PRIMARY KEY AUTOINCERMENT, "
+ "DATE STRING," //careful
+ "MINUTES INTEGER" + ");"
);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//no need to worry about this yet.
}
}
The toast always shows up, meaning something is wrong in the try block. I just started android development a week ago and I don't know what went wrong in my code. It would be great if you could give me some direction.
Thank you in advance.
This part seems wrong to me.
while (cursor.moveToFirst()){
String id = Integer.toString(cursor.getInt(0));
String date = cursor.getString(1);
String minutes = Integer.toString(cursor.getInt(2));
String finalValue = id + "|" + date + "|" + minutes;
arrayList.add(finalValue);
}
I am not sure what you are trying to achieve but the right way to get data from data base is like this:
cursor.moveToFirst()
while (cursor.isAfterLast()){
String id = Integer.toString(cursor.getInt(0));
String date = cursor.getString(1);
String minutes = Integer.toString(cursor.getInt(2));
String finalValue = id + "|" + date + "|" + minutes;
arrayList.add(finalValue);
}
I'm not entirely sure what could be happening, I know that there is a mismatch when I try to insert, but when I double check my code I can't see why it would spit that error out. I am simply trying to insert a username and password (both are Strings).
CONTEXT:
In my RegisterLoginActivity.java I made it when the user taps the TextView "Create account" it will grab the username and password and turn them into strings.
Then in my DatabaseOperations.java I use the function putInformation() to insert the data.
My TableData.java simply contains my table information.
RegisterLoginActivity.java;
package com.example.envy.energyvue;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RegisterLoginActivity extends AppCompatActivity {
EditText USER_NAME, USER_PASS;
TextView REG;
String user_name, user_pass;
Context ctx = this;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
//getActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_login);
USER_NAME = (EditText) findViewById(R.id.userText);
USER_PASS = (EditText) findViewById(R.id.passText);
REG = (TextView) findViewById(R.id.createAccount);
REG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_PASS.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB,user_name, user_pass);
}
});
// IGNORE THIS PORTION, IT IS FOR LOGGING IN AFTER I REGISTER
//********************************************
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_NAME.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
Cursor CR = DB.getInformation(DB);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do{
if(user_name.equals(CR.getString(0)) && user_pass.equals(CR.getString(1))){
loginstatus = true;
}
}while(CR.moveToFirst());
if(loginstatus){
Toast.makeText(getBaseContext(), "Login Success", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Login Failed", Toast.LENGTH_LONG).show();
}
}
});
}
}
DatabaseOperations.java;
package com.example.envy.energyvue;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Envy on 7/13/2016.
*
* private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
*/
public class DatabaseOperations extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserData.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME;
public DatabaseOperations(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void putInformation(DatabaseOperations dop, String user_id, String password){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.COLUMN_NAME_USER_ID, user_id);
cv.put(TableData.TableInfo.COLUMN_NAME_PASSWORD, password);
System.out.print("LOLOLSDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
long newRowId;
newRowId = SQ.insert(
TableData.TableInfo.TABLE_NAME,
null,
cv);
}
public Cursor getInformation(DatabaseOperations dop){
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] projection = {
TableData.TableInfo._ID,
TableData.TableInfo.COLUMN_NAME_USER_ID,
TableData.TableInfo.COLUMN_NAME_PASSWORD
};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, projection, null, null, null, null, null);
return CR;
}
}
TableData.java;
package com.example.envy.energyvue;
import android.provider.BaseColumns;
/**
* Created by Envy on 7/13/2016.
*/
public class TableData {
public TableData(){}
public static abstract class TableInfo implements BaseColumns {
public static final String TABLE_NAME = "login_information";
public static final String COLUMN_NAME_USER_ID = "user_id";
public static final String COLUMN_NAME_PASSWORD = "password";
}
}
Error:
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteLog: (20) statement aborts at 5: [INSERT INTO login_information(password,user_id) VALUES (?,?)] datatype mismatch
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteDatabase: Error inserting password= bbb user_id=bbb
android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
#################################################################
Error Code : 20 (SQLITE_MISMATCH)
Caused By : Data type mismatch.
(datatype mismatch (code 20))
#################################################################
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:915)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1609)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.envy.energyvue.DatabaseOperations.putInformation(DatabaseOperations.java:59)
at com.example.envy.energyvue.RegisterLoginActivity$1.onClick(RegisterLoginActivity.java:37)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Alright guys.. after many hours, I figured it out ....I put my database name with a ".db" extension which was messing things up.
i got nullPointerException when trying to fetch some data from database with rawQuery.
Here's an error:
03-11 18:09:01.522: E/AndroidRuntime(2057): Uncaught handler: thread
main exiting due to uncaught exception 03-11 18:09:01.532:
E/AndroidRuntime(2057): java.lang.NullPointerException 03-11
18:09:01.532: E/AndroidRuntime(2057): at
com.math.scan.FormulaModel.setFormulaList(FormulaModel.java:27)
Look at my code:
DbHelper
package com.math.scan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "formulas";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_UNKNOWN = "unknown";
public static final String COLUMN_FORMULA = "formula";
public static final String COLUMN_CTG = "ctg";
private static final String DB_NAME = "formulas.db";
private static int DB_VERSION = 1;
private static final String DB_CREATE = "CREATE TABLE "+TABLE_NAME+
"("+COLUMN_ID+" integer primary key autoincrement,"
+COLUMN_UNKNOWN+" text not null,"
+COLUMN_FORMULA+" text not null,"
+COLUMN_CTG+" text not null );";
public Context mCtx;
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mCtx = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DB_CREATE);
// reading formulas
AssetManager asset = mCtx.getAssets();
try {
InputStream input = asset.open("formulas");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
String content = new String(buffer);
Scanner scan = new Scanner(content);
String current;
String[] f = new String[2];
String[] formula = new String[2];
while(scan.hasNextLine()) {
current = scan.nextLine();
// get category
f = current.split("!!");
formula = f[1].split(" = ");
database.execSQL("INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
Log.d("DB", "INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DbHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
FormulaModel
package com.math.scan;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class FormulaModel {
private SQLiteDatabase database;
private DbHelper dbHelper;
public FormulaModel(Context context) {
dbHelper = new DbHelper(context);
}
public void open() throws SQLException {
dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void setFormulaList(String ctg) {
open();
// app stops working here
Cursor cursor = database.rawQuery("SELECT unknown, formula FROM formulas WHERE ctg = '"+ctg+"'", null);
int results = cursor.getCount();
cursor.moveToFirst();
Global.FormuleResult = new String[results];
Global.FormuleTable = new String[results];
for(int i = 0; i < results; i++) {
Global.FormuleTable[i] = cursor.getString(1);
Global.FormuleResult[i] = cursor.getString(0);
}
close();
}
}
This is activity, where I call setFormulaList() method in FormulaModel class.
package com.math.scan;
import net.sourceforge.jeval.EvaluationException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ProblemActivity extends Activity {
private EditText prob;
private Button solve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
// text field
prob = (EditText) findViewById(R.id.problem);
// confirm btn
solve = (Button) findViewById(R.id.solve);
// check if confirm button was pressed
solve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get text from the field
String problem = prob.getText().toString();
// check if expression is not empty
if(problem.length() == 0) {
// string is empty!
Toast.makeText(ProblemActivity.this, getString(R.string.empty_field), Toast.LENGTH_SHORT).show();
} else {
FormulaModel f = new FormulaModel(ProblemActivity.this);
f.setFormulaList("mech");
pears.doMagic(problem);
try {
String str = Global.eval.getVariableValue(Global.UNKNOWN);
TextView answ = (TextView) findViewById(R.id.answer);
answ.setText(getString(R.string.prob_answ) + str);
} catch (EvaluationException e) {
Toast.makeText(ProblemActivity.this, getString(R.string.prob_error), Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
I can't figure out what is wrong here.
Any ideas?
You have to set your database variable in open():
database = dbHelper.getWritableDatabase();