This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have created a method which takes data from SQLite and displays in a textview but when l press a button show the app crashes. The Code:
public void ViewData(){
btnControler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor data = peopleDB.showData();
if (data.getCount() == 0) {
display("","");
return;
}
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
while (data.moveToNext()) {
display(buffer.append("Name:\t " + data.getString(1) + "\n").toString(),buffer2.append("Email:\t " + data.getString(2) + "\n").toString());
}
}
});
}
public void display(String name, String email){
TVusername.append(name);
rphone.append(email);
}
The error is appointed to the fifth line Cursor data = peopleDB.showData();
05-25 23:37:03.439 916-916/info.devexchanges.googlelocation E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.devexchanges.googlelocation, PID: 916
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor info.devexchanges.googlelocation.DatabaseHelper.showData()' on a null object reference
at info.devexchanges.googlelocation.LocationActivity$5.onClick(LocationActivity.java:473)
at android.view.View.performClick(View.java:5184)
at android.view.View$PerformClick.run(View.java:20910)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
You might be missing getting the SQLiteDatabase reference with:
DatabaseHelper databasehelper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase peopleDB = databasehelper.getWritableDatabase();
You can see an example in this link.
Related
I am using python script running for some calculations and saving the results to SQLite database. Python operation takes time to process, so i put that part in an asyncTask. And database insertion is written inside the onPostExecute() method. Data inserion is happening and returning the row id as well. These datas displayed on another activity, while i am trying to open that record screen app crashes and that db data row also warnished from db. I tried this by removing that python part and it's working fine. I can see the record list as well.
see below complete error log
2020-11-25 21:03:35.602 3997-3997/com.ust.step_count_directions E/SQLiteLog: (522) statement aborts at 2: [select * from GaitStatisticsDatas WHERE Category = 0] disk I/O error - SQLITE_IOERR_SHORT_READ
2020-11-25 21:03:35.602 3997-3997/com.ust.step_count_directions E/SQLiteQuery: exception: disk I/O error - SQLITE_IOERR_SHORT_READ (Sqlite code 522 SQLITE_IOERR_SHORT_READ), (OS error - 11:Try again); query: select * from GaitStatisticsDatas WHERE Category = 0
2020-11-25 21:03:35.603 3997-3997/com.ust.step_count_directions D/AndroidRuntime: Shutting down VM
2020-11-25 21:03:35.607 3997-3997/com.ust.step_count_directions E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ust.step_count_directions, PID: 3997
android.database.sqlite.SQLiteDiskIOException: disk I/O error - SQLITE_IOERR_SHORT_READ (Sqlite code 522 SQLITE_IOERR_SHORT_READ), (OS error - 11:Try again)
at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method)
at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:904)
at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:851)
at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:137)
at com.ust.step_count_directions.acitvities.ui.home.RecordList.onCreateView(RecordList.java:140)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
see my code
class BackgroundRunner extends AsyncTask<String,String,String>{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(TestScreen.this, R.style.MyTheme);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Large);
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
PyObject pyObject1 = null;
Log.d("array_time..","array_time.."+mStartTestTime+" "+endTestTime);
if (!Python.isStarted()) {
Log.d("Py..", "Py..");
Python.start(new AndroidPlatform(mcontext));
Python py = Python.getInstance();
PyObject pyObject = py.getModule("app");
pyObject1 = pyObject.callAttr("score", mStartTestTime, endTestTime);
p_step_count = pyObject1.asList().get(0).toInt();
p_total_time = pyObject1.asList().get(1).toDouble();
p_stride_time = pyObject1.asList().get(2).toDouble();
p_stance_time = pyObject1.asList().get(3).toDouble();
p_swing_time = pyObject1.asList().get(4).toDouble();
p_cadence = pyObject1.asList().get(5).toDouble();
p_gait_score = pyObject1.asList().get(6).toDouble();
}
return "null";
}
#Override
protected void onPostExecute(String s) {
dbManager.insertStatistics2("s",helper.TABLE_STEP_STATISTICS,p_stride_time,p_cadence,
p_stance_time, p_swing_time,p_total_time,Category,p_step_count,p_gait_score);
progressDialog.dismiss();
mAlertDialogView = ViewUtils.showResultDialog(TestScreen.this, strideTime, stanceTime, swingTime, cadenceTime, totalSteps, totalTime, view -> {
if (mAlertDialogView != null) {
mAlertDialogView.dismiss();
resetTimer();
crpv.setPercent(0);
static_img.setVisibility(View.VISIBLE);
static_img.setImageResource(R.drawable.walk_static);
gifImageView.setVisibility(View.GONE);
test_t2.setText(discription);
test_t1.setText(heading);
}
});
}
}
And error is throwing on cursor.getCount() > 0 on below code which is another fragment.
helper = new DatabaseHelper(getContext());
dbManager = new DBManager(getContext());
dbManager.open();
Cursor cursor = dbManager.fetchNormal();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
gait_cycle.add(cursor.getString(cursor.getColumnIndex(helper.COLUMN_CADENCE)));
stride_time.add(cursor.getString(cursor.getColumnIndex(helper.COLUMN_STRIDE_TIME)));
stance_time.add(cursor.getString(cursor.getColumnIndex(helper.COLUMN_STANCE_TIME)));
cursor.moveToNext();
}
}
I am developing and Android app and want to save to a local SQLite Database and then want it to sync with Firebase, I have gotten the Firebase sync working I am only having the problem saving to the local database, the app crashes when I click save however the data gets stored in firebase but not in the local SQLite. I have included my code below if anyone can assist.
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
ref.keepSynced(true);
//Getting values to store
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
String venue = editVenue.getText().toString().trim();
String DateTime = editDateTime.getText().toString().trim();
//Creating Person object
final MeetingUser person = new MeetingUser();
//Adding values
person.setName(name);
person.setAddress(address);
person.setVenue(venue);
person.setDateTime(DateTime);
//Storing values to firebase
ref.push().setValue(person);
//Write to local SQL database
boolean isInserted = DB.SaveUserMeetings(editTextName.getText().toString(),
editDateTime.getText().toString(),
editVenue.getText().toString(),
editTextAddress.getText().toString());
if (isInserted == true)
Toast.makeText(Capture_Meetings.this, "Data Not Saved", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Capture_Meetings.this, "Data Saved", Toast.LENGTH_SHORT).show();
//Value event listener for realtime data update
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
MeetingUser person = postSnapshot.getValue(MeetingUser.class);
//Adding it to a string
String string = "Name of School: " + person.getName() + "\n Date:" + person.getDateTime() + "\n Venue:" + person.getVenue() + "\nMeeting Notes: " + person.getAddress() + "\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
});
}
My Error log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pooveshin.saica_sgb, PID: 10770
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.pooveshin.saica_sgb.DatabaseHelper.SaveUserMeetings(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.pooveshin.saica_sgb.Capture_Meetings$3.onClick(Capture_Meetings.java:114)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Have you considered using Firebase offline capabilities (https://firebase.google.com/docs/database/android/offline-capabilities) ...enabled by calling following
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
public class ques1 extends AppCompatActivity {
SQLiteDatabase sql2;
TextView txtv2;
RadioButton rb1,rb2;
Button btn2;
Cursor c;
String Ans="";
these are my 3 array list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ques1);
ArrayList<String> q = new ArrayList<String>(3);
q.add("1.who is the fastest man on Earth?");
q.add("2.how many days are there in a leap year?");
q.add("3.what is the national animal of India");
ArrayList<String> options1 = new ArrayList<String>(3);
options1.add("Nikhil sudan");
options1.add("365");
options1.add("Lion");
ArrayList<String> options2 = new ArrayList<String>(3);
options2.add("Usain Bolt");
options2.add("366");
options2.add("Tiger");
ArrayList<String> answer = new ArrayList<String>(3);
answer.add("Usain BOlt");
answer.add("365");
answer.add("Tiger");
and this how i am inserting it into my table
sql2 = openOrCreateDatabase("ddb", MODE_PRIVATE, null);
sql2.execSQL("create table if not exists bank(question varchar,option1 varchar,option2 varchar,answ varchar)");
for (int i = 0; i < q.size(); i++){
sql2.execSQL("insert into bank values('" + q.get(i) + "','" + options1.get(i) + "','" + options2.get(i) + "','"+answer.get(i)+"')");
}
and the raw query to add the question and options to my android activity and submit button to check the value of text of radio buttons with the Ans
c=sql2.rawQuery("Select * from bank where q="+q.get(1).charAt(1),null);
c.moveToFirst();
txtv2.setText(c.getString(c.getColumnIndex("question")));
rb1.setText(c.getString(c.getColumnIndex("option1")));
rb2.setText(c.getString(c.getColumnIndex("option2")));
Ans=c.getString(c.getColumnIndex("answ"));
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (rb1.isChecked()){
if (rb1.getText().equals(Ans)){
Toast.makeText(ques1.this,"Right answer",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(ques1.this,"wrong choice",Toast.LENGTH_SHORT).show();
}
if (rb2.isChecked()){
if (rb1.getText().equals(Ans)){
Toast.makeText(ques1.this,"right Ans",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(ques1.this,"Wrong choice",Toast.LENGTH_SHORT).show();
}
}
});
my log(updated) :
FATAL EXCEPTION: main
Process: com.nikhil.dingdong, PID: 26739
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nikhil.dingdong/com.nikhil.dingdong.ques1}: android.database.sqlite.SQLiteException: near ".": syntax error (code 1): , while compiling: Select * from bank where question=.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.sqlite.SQLiteException: near ".": syntax error (code 1): , while compiling: Select * from bank where question=.
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at com.nikhil.dingdong.ques1.onCreate(ques1.java:67)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
First correct your answer's arraylist so it will not give arrayindexoutofboundexception
ArrayList<String> answer = new ArrayList<String>(3);
answer .add("Usain BOlt");
answer .add("365");
answer .add("Tiger");
Edit as below:
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (rb1.isChecked()){
if (rb1.getText().equals(Ans)){
Toast.makeText(ques1.this,"Right answer",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(ques1.this,"wrong choice",Toast.LENGTH_SHORT).show();
}
if (rb2.isChecked()){
if (rb2.getText().equals(Ans)){
Toast.makeText(ques1.this,"right Ans",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(ques1.this,"Wrong choice",Toast.LENGTH_SHORT).show();
}
}
});
In your rawQuery remove .charAt(1)
Replace q=q.get(1) with question=q.get(1) in rawquery
This question already has answers here:
Proper way to avoid parseInt throwing a NumberFormatException for input string: ""
(7 answers)
Closed 6 years ago.
I've tried lot of things found here, but it keeps crashing. I wanna know what do i need to add in order to show a Toast message when button is clicked and EditText is empty.
INFO: The app is supposed to send the two values in the EditText's to another activity, showing Toast's in the following exceptions:the first value higher than 6; the second value higher than (firstvalue*14); and if the fields are empty (which is my problem)
Here's my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView saludo_bienvenida;
EditText et1_creditos;
EditText et2_faltas;
Button boton_ingresar;
Button boton_info;
String numero_creditos;
String numero_faltas_actuales;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saludo_bienvenida = (TextView) findViewById(R.id.saludo_bienvenida);
et1_creditos = (EditText) findViewById(R.id.edittext1_numero_creditos);
et2_faltas = (EditText) findViewById(R.id.edittext2_numero_faltas);
boton_ingresar = (Button) findViewById(R.id.boton_ingresar);
boton_info = (Button) findViewById(R.id.boton_info);
if (boton_ingresar != null) {
boton_ingresar.setOnClickListener(this);
}
if (boton_info != null) {
boton_info.setOnClickListener(this);
}
et1_creditos.setInputType(InputType.TYPE_CLASS_NUMBER);
et2_faltas.setInputType(InputType.TYPE_CLASS_NUMBER);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.boton_ingresar:
numero_creditos = et1_creditos.getText().toString();
numero_faltas_actuales = et2_faltas.getText().toString();
int numero_creditos1 = Integer.parseInt(numero_creditos);
int numero_faltas_actuales1 = Integer.parseInt(numero_faltas_actuales);
int o = numero_creditos1 * 14;
if (numero_creditos1>6) {
Toast.makeText(getApplicationContext(), "Ingrese un número válido de créditos", Toast.LENGTH_LONG).show();
}else if (numero_faltas_actuales1 > o){
Toast.makeText(getApplicationContext(), "El número de faltas ingresadas es mayor que el número de horas del curso", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(MainActivity.this,Resultados.class);
intent.putExtra("numero_creditos",numero_creditos);
intent.putExtra("numero_faltas_actuales",numero_faltas_actuales);
startActivity(intent);
}
break;
case R.id.boton_info:
Intent informacion = new Intent(MainActivity.this,Informacion.class);
startActivity(informacion);
break;
}
}
}
This is the log:
06-17 01:36:17.419 2738-2738/absence_counter.app.jorgepasco.com.absencecounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: absence_counter.app.jorgepasco.com.absencecounter, PID: 2738
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at absence_counter.app.jorgepasco.com.absencecounter.MainActivity.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
So thanks you for your log !
You can see on your log that you have a problem when you parseInt. You try to parseInt an empty String.
So when the user do not write anything, you have to set a default value yourself.
You can do something like that before your parse:
if(numero_creditos.equals(""))
numero_creditos = "0";
But if I were you, I would force the user to right directly an integer
Please, show us your log box.
Perhaps the app crash because you don't have any default case in your switch case. So if v.getId() is not what you think, it will crash.
Simply, add that at the end of your switch case:
switch(v.getId()){
case: ...
case: ...
default: Toast.makeText(getApplicationContext(),"v.getId = " + v.getId());
}
But I would be easier for me to solve your problem with your log box !
et1_creditos.getText() can maybe send a null value. Then null.toString() has no sense because null does not have toString().
try:
String creditos = et1_creditos.getText()
if(creditos != null){
//stuff here
}
It is failing on this line.
int numero_creditos1 = Integer.parseInt(numero_creditos);
If your numeor_creditos is empty it won't be integer.
Try
int numero_creditos1;
if(TextUtils.isEmpty(numero_creditos){
numero_creditos1 = 0;
} else {
numero_creditos1 = Integer.parseInt(numero_creditos);
}
I am having error in this for past couple of days, have tried using breakpoints to figure why is it giving null pointer exception, but i am not able to understand which value is getting stuck. How can i make db be not null, so as to run this code.
I have an abstract class that calls this method on certain conditional statement. It has to return a long value. Which is to be used for some other method.
This method long save is implemented in another class which returns a value after calling db.insert, but i am getting Null Pointer Exception
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
I have following doubts :
Why is this giving error when i am using it in Fragment, but when i am using with Activity it's working fine. What can be the reason.
Also How is getWritableDatabase gets called when i pass db as an argument.
long save(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
long now = System.currentTimeMillis();
cv.put(COL_CREATEDTIME, now);
cv.put(COL_MODIFIEDTIME, now);
//cv.putNull(COL_MODIFIEDTIME);
cv.put(COL_NAME, name==null ? "" : name);
//if (fromDate != null)
cv.put(COL_FROMDATE, fromDate==null ? "" :fromDate);
//if (toDate != null)
cv.put(COL_TODATE, toDate==null ? "" :toDate);
//if (rule != null)
cv.put(COL_RULE, rule==null ? "" :rule);
//if (interval != null)
cv.put(COL_INTERVAL, interval==null ? "" :interval);
cv.put(COL_SOUND, sound ? 1 : 0);
//if (sound != null)
//Log.e(TAG, "Error inserting " + now);
return db.insert(TABLE_NAME,null, cv);}
public class DosageDB extends Application {
public static DBHelper dbHelper;
public static SQLiteDatabase db;
public static final String TIME_OPTION = "time_option";
public static final String DATE_RANGE = "date_range";
public static final String DATE_FORMAT = "date_format";
public static final String TIME_FORMAT = "time_format";
public static final String VIBRATE_PREF = "vibrate_pref";
public static final String RINGTONE_PREF = "ringtone_pref";
public static final String DEFAULT_DATE_FORMAT = "yyyy-M-d";
#Override
public void onCreate() {
super.onCreate();
PreferenceManager.setDefaultValues(this,R.xml.settings, false);
sp = PreferenceManager.getDefaultSharedPreferences(this);
dbHelper = new DBHelper(this);
db = dbHelper.getWritableDatabase();
}
}
Stacktrace :
09-10 15:05:39.582 2423-2423/healerkart.com.dosage E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: healerkart.com.dosage, PID: 2423
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 healerkart.com.dosage.Delta.Alarm.save(Alarm.java:65)
at healerkart.com.dosage.Delta.AbstractModel.persist(AbstractModel.java:54)
at healerkart.com.dosage.Delta.Alarm.persist(Alarm.java:10)
at healerkart.com.dosage.Alpha.dosageFrag$2.onClick(dosageFrag.java:134)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Since DosageDB was extending Application, i forgot to mention the Application name attribute in the AndroidManifest.xml
Thanks anyways.