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.
Related
I have used this code with json object. Now I'm with sqlite, and it has NPE error.
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
EDIT
07-13 09:05:29.763 13314-13351/com.example.arlene.capsmobile E/libdataflow_monitor: open error=Operation not permitted
07-13 09:05:31.542 13314-13314/com.example.arlene.capsmobile E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.arlene.capsmobile, PID: 13314
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.example.arlene.capsmobile.translistTab.loadTransList(translistTab.java:135)
at com.example.arlene.capsmobile.translistTab.onCreate(translistTab.java:72)
Error at the line of productTransList.add(product);
Initialize the productTransList first and then add objects to the list.
productTransList = new ArrayList<>();
This will fix the issue.
In your SQLiteHelper Class you need to initialize the List:
public List<Product> getAllProducts() {
try {
List<Product > listProducts = new ArrayList<>();
String selectQuery = "SELECT * FROM " + dbSchema.table_name;
SQLiteDatabase mDb = this.getWritableDatabase();
Cursor cursor = mDb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Product product = new
Product(Integer.parseInt(cursor.getString(0).toString()),
Integer.parseInt(cursor.getString(1).toString()),
cursor.getString(2).toString(),
cursor.getString(3).toString(),
cursor.getString(4).toString(),
cursor.getString(5).toString(),
Double.parseDouble(cursor.getString(6).toString()),
cursor.getString(7).toString());
listProducts.add(mRecord);
} while (cursor.moveToNext());
}
return listProducts;
} catch (Exception ex) {
return null;
}
}
Here is a reference for SQLite:
SQLite Demo
From your activity, use the helper method getAllProducts asynchronously and pass an empty list to it as an input param.
First Initialize a ArrayList
productTransList = new ArrayList<>();
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
Hope this may help you
I have two objects: MailBox and Email. Each Receiver has many Emails.
public class MailBoxRealmModel extends RealmObject {
#PrimaryKey
private long id;
private String name;
private String mailboxId;
private RealmList<EmailRealmModel> emails;
}
public class EmailRealmModel extends RealmObject {
#PrimaryKey
private long EmailId;
private String Name;
private String Text;
private String Tag;
private int Type;
private String Time;
private int Status;
}
How can one use **realm.insertOrUpdate**when adding email to MailBoxRealmModel?
EmailRealmModel email = new EmailRealmModel();
email.setMessageId(emailID);
realm.insertOrUpdate(email );
mailBoxRealmModel.getEmails().add(email);
I am getting a null pointer exception email on this line:
mailBoxRealmModel.getEmails().add(email);
Exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean io.realm.RealmList.add(io.realm.RealmModel)' on a null object reference
at com.koa.mailbox.MailBoxActivity$1.execute(MailBoxActivity.java:123)
at io.realm.Realm.executeTransaction(Realm.java:1253)
at com.koa.mailbox.MailBoxActivity.test(MailBoxActivity.java:88)
at com.koa.mailbox.MailBoxActivity.onCreate(MailBoxActivity.java:71)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
at android.app.ActivityThread.access$1100(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
Proper way to create a new RealmObject with existing primary key is usage realm.createObject(EmailRealmModel.class, emailID)method.
Full code fragment:
realm.beginTransaction();
EmailRealmModel email = realm.createObject(EmailRealmModel.class, emailID);
mailBoxRealmModel.getEmails().add(email);
realm.commitTransaction();
Or, if you wish update stored in realm object using one of inmemory instances, you should call realm.copyToRealmOrUpdate(obj).
Example from documentation:
// For create managed proxy, you should wrap EmailRealmModel object by call copyToRealmXXX
EmailRealmModel email = realm.copyToRealmOrUpdate(new EmailRealmModel(id));
mailBoxRealmModel.getEmails().add(email);
On an unmanaged RealmObject, the RealmList fields must be initialized manually.
EmailRealmModel email = new EmailRealmModel();
email.setMessageId(emailID);
mailBoxRealmModel.setEmails(new RealmList<MailBoxRealmModel>());
mailBoxRealmModel.getEmails().add(email);
realm.insertOrUpdate(mailBoxRealmModel);
I need to use a text recognition API from google to recognize text using the camera. I download the code, and it works perfectly. But I am developing a project that need to identifying a certain word, which is saved in a global variable. I am having a problem to start another activity when the word is identified. Here is the part of the code that makes the Text Recognition :
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import com.google.android.gms.samples.vision.ocrreader.ui.camera.GraphicOverlay;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
/**
* A very simple Processor which gets detected TextBlocks and adds them to the overlay
* as OcrGraphics.
* TODO: Make this implement Detector.Processor<TextBlock> and add text to the GraphicOverlay
*/
public final class OcrDetectorProcessor extends Activity implements Detector.Processor<TextBlock> {
private GraphicOverlay<OcrGraphic> mGraphicOverlay;
OcrDetectorProcessor(GraphicOverlay<OcrGraphic> ocrGraphicOverlay, String word) {
// System.out.println("VARIAVEIL GLOBAL no detector:" + word);
// System.out.println("VARIAVEIL GLOBAL no detector da classe:" +s);
mGraphicOverlay = ocrGraphicOverlay;
// String lala = receiveDetections(ocrGraphicOverlay);
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
mGraphicOverlay.clear();
System.out.println("CLEAR : " + mGraphicOverlay);
SparseArray<TextBlock> items = detections.getDetectedItems();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
if (item != null && item.getValue() != null) {
Log.d("Processor", "Text detected! " + item.getValue());
String letra = item.getValue();
// get
// String s = ((MyApplication) this.getApplication()).getSomeVariable();
// System.out.println("Variavei global : "+s);
/*if(letra.equals(palavra))
{
System.out.println("LETRA : " +letra);
System.out.println("LETRA IDENTIFICADA");
}*/
Intent intent = new Intent(getApplicationContext(),Resultado.class);
startActivity(intent);
}
OcrGraphic graphic = new OcrGraphic(mGraphicOverlay, item);
mGraphicOverlay.add(graphic);
}
}
private String PalavraGerada() {
System.out.println("Veio no palavra gerada");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
return s;
}
#Override
public void release() {
mGraphicOverlay.clear();
}
}
When i try to start another activity, i get the following error:
11-03 13:23:14.347 21422-21852/com.google.android.gms.samples.vision.barcodereader E/OpenCameraSource: Exception thrown from receiver.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at com.google.android.gms.samples.vision.ocrreader.OcrDetectorProcessor.receiveDetections(OcrDetectorProcessor.java:76)
at com.google.android.gms.vision.Detector.receiveFrame(Unknown Source)
at com.google.android.gms.samples.vision.ocrreader.ui.camera.CameraSource$FrameProcessingRunnable.run(CameraSource.java:1209)
at java.lang.Thread.run(Thread.java:818)
I don't actually need to start another activity, i need to compare the text recognition with the certain word.
Also, when i try to get the value of the global variable, I get the following error:
11-03 13:29:18.029 23276-23495/com.google.android.gms.samples.vision.barcodereader E/OpenCameraSource: Exception thrown from receiver.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.android.gms.samples.vision.ocrreader.MyApplication.getSomeVariable()' on a null object reference
at com.google.android.gms.samples.vision.ocrreader.OcrDetectorProcessor.receiveDetections(OcrDetectorProcessor.java:66)
at com.google.android.gms.vision.Detector.receiveFrame(Unknown Source)
at com.google.android.gms.samples.vision.ocrreader.ui.camera.CameraSource$FrameProcessingRunnable.run(CameraSource.java:1209)
at java.lang.Thread.run(Thread.java:818)
I really don't know how to fix it, and I appreciate any help.
Thanks
The problem is that you cannot get the Context. Try pass the Context Object as a parameter to the constructor method, like
private Context mContext;
OcrDetectorProcessor(GraphicOverlay<OcrGraphic> ocrGraphicOverlay, String word. Context context) {
mGraphicOverlay = ocrGraphicOverlay;
mContext = context;
}
Then in your method
private String PalavraGerada() {
System.out.println("Veio no palavra gerada");
//String s = ((MyApplication) this.getApplication()).getSomeVariable();
String s = ((MyApplication)mContext).getSomeVariable();
// or try some other way to get your application.
return s;
}
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.
I am making an android app and have to save JSON to an SQLite database.
The app already has a function to get JSON and display this in a listview and a function to save data to a database. Now I want to combine those, but I am a little lost.
public void get_data(String data) {
try {
JSONArray data_array=new JSONArray(data);
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
Courses add=new Courses();
add.name = obj.getString("name");
add.ects = obj.getString("ects");
add.grade = obj.getString("grade");
add.period = obj.getString("period");
courses.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
This loops through the JSON so I think this is where is should save to the database.
public boolean insertCourse(String course, int ects, int period, int grade) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COURSE_COLUMN_COURSE, course);
contentValues.put(COURSE_COLUMN_ECTS, ects);
contentValues.put(COURSE_COLUMN_PERIOD, period);
contentValues.put(COURSE_COLUMN_GRADE, grade);
db.insert(COURSE_TABLE_NAME, null, contentValues);
return true;
}
This is in a DBHelper.class should be able to use this I think.
I was hoping to reuse the code which i used to save input fields to the database but no luck so far.
else {
if(dbHelper.insertCourse(courseEditText.getText().toString(),
Integer.parseInt(ectsEditText.getText().toString()),
Integer.parseInt(periodEditText.getText().toString()),
Integer.parseInt(gradeEditText.getText().toString()))) {
Toast.makeText(getApplicationContext(), "Course Inserted", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Could not Insert course", Toast.LENGTH_SHORT).show();
}
Does anyone have a suggestion how to integrate both (if possible at all).
Thnx in advance
EDIT:
the logcat crash report:
04-09 17:45:37.204 12244-12244/com.stefspakman.progress2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.stefspakman.progress2, PID: 12244
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.stefspakman.progress2.ProgressDBHelper.insertCourse(java.lang.String, int, int, int)' on a null object reference
at com.stefspakman.progress2.gradingActivity.get_data(gradingActivity.java:60)
at com.stefspakman.progress2.Download_data$1.handleMessage(Download_data.java:58)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
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)
You need to instantiate your DBHelper class before using the insertCourse Method .
DBHelper helper = new DBHelper(this);
helper.insertCourse(Course course);
Also , its better if you use your Model class object as paramater for database queries .
public boolean insertCourse(Courses courses) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COURSE_COLUMN_COURSE, courses.getCourse());
contentValues.put(COURSE_COLUMN_ECTS, courses.getEcts());
contentValues.put(COURSE_COLUMN_PERIOD, courses.getPeriod());
contentValues.put(COURSE_COLUMN_GRADE, courses.getGrade());
db.insert(COURSE_TABLE_NAME, null, contentValues);
return true;
}
In this way you can save your data from JSON as
db.insert(courses);
The exception says that your ProgressDBHelper is null, please make sure that you are creating an instance of ProgressDBHelper before calling its methods. Creating an instance is just calling ProgressDBHelper dbHelper = new ProgressDBHelper() and you have to call it before calling dbHelper.insertCourse(...)