Android: Alarm Manager; Nullpointer when accessing SQLiteOpenhelper in MainActivity from Broadcastreceiver...
I am busy working on a quotes app that will show the user a new motivational quote each morning at 9:00am.
I have this method in my MainActivity to pull and show the quote in a listView that shows the single quote. I know other examples of questions of this type exist but I have not seen one using database data and cursors or cursor adapters as I need to.
public void DailyQuoteDatabaseAccess(){
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase SqlDb = sqLiteOpenHelper.getReadableDatabase();
String rawQuery = "SELECT * FROM dailyQuoteTable ORDER BY RANDOM() LIMIT 1";
Cursor cursor = SqlDb.rawQuery(rawQuery, null);
DailyQuoteCursorAdapter DQCursorAdapter = new DailyQuoteCursorAdapter(this, cursor);
this.mDailyQuoteListView.setAdapter(DQCursorAdapter);
}
I was calling this method from OnCreate and it works perfectly however it reloads each time the app is restarted. I am using AlarmManager to set the alarm to change the quote each morning at 9:00am and the alarm is firing but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class. Here is that class... blank because I can't figure out how to make it work.
package com.myapps.dailyquotes;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TodaysQuoteAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity mainActivity = new MainActivity();
mainActivity.DailyQuoteDatabaseAccess();
}
}
Any help in this arena would be very much appreciated. Should I use an intent or an object of an entirely new class and can you please provide an example?
****11/22/18****
I forgot to add my custom cursor adapter... I think this may make a difference but I'm still not sure how to integrate it with Broadcast Receiver to pass the data I need...
public class DailyQuoteCursorAdapter extends CursorAdapter{
public DailyQuoteCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.daily_quote_item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView NameTextView = (TextView) view.findViewById(R.id.name);
TextView NumberTextView = (TextView) view.findViewById(R.id.number);
TextView DateTextView = (TextView) view.findViewById(R.id.date);
TextView QuoteTextView = (TextView) view.findViewById(R.id.quote);
String name = cursor.getString(cursor.getColumnIndexOrThrow("quote_main"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
String quote = cursor.getString(cursor.getColumnIndexOrThrow("quote"));
nameTextView.setText(name + " ");
numberTextView.setText(String.valueOf(number) + ":");
dateTextView.setText(String.valueOf(date));
quoteTextView.setText(quote);
}
}
This is my log cat for the null pointer...
Process: com.myapps.dailyquotes, PID: 15024
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.myapps.dailyquotes.TodaysQuoteAlarmReceiver@d63089d
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_52497(LoadedApk.java:1323)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.$m$7(Unknown Source:4)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.run(Unknown Source:39)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:109)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:129)
at com.myapps.dailyquotes.MainActivity.DailyQuoteDatabaseAccess(MainActivity.java:403)
at com.myapps.dailyquotes.TodaysQuoteAlarmReceiver.onReceive(TodaysQuoteAlarmReceiver.java:18)
The receiver does attempt to run the method from MainActivity so I know it's making the connection but the error is coming from this line inside the DailyQuoteDatabaseAccess method inside of the MainActivity class:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);

add a comment |
I am busy working on a quotes app that will show the user a new motivational quote each morning at 9:00am.
I have this method in my MainActivity to pull and show the quote in a listView that shows the single quote. I know other examples of questions of this type exist but I have not seen one using database data and cursors or cursor adapters as I need to.
public void DailyQuoteDatabaseAccess(){
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase SqlDb = sqLiteOpenHelper.getReadableDatabase();
String rawQuery = "SELECT * FROM dailyQuoteTable ORDER BY RANDOM() LIMIT 1";
Cursor cursor = SqlDb.rawQuery(rawQuery, null);
DailyQuoteCursorAdapter DQCursorAdapter = new DailyQuoteCursorAdapter(this, cursor);
this.mDailyQuoteListView.setAdapter(DQCursorAdapter);
}
I was calling this method from OnCreate and it works perfectly however it reloads each time the app is restarted. I am using AlarmManager to set the alarm to change the quote each morning at 9:00am and the alarm is firing but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class. Here is that class... blank because I can't figure out how to make it work.
package com.myapps.dailyquotes;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TodaysQuoteAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity mainActivity = new MainActivity();
mainActivity.DailyQuoteDatabaseAccess();
}
}
Any help in this arena would be very much appreciated. Should I use an intent or an object of an entirely new class and can you please provide an example?
****11/22/18****
I forgot to add my custom cursor adapter... I think this may make a difference but I'm still not sure how to integrate it with Broadcast Receiver to pass the data I need...
public class DailyQuoteCursorAdapter extends CursorAdapter{
public DailyQuoteCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.daily_quote_item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView NameTextView = (TextView) view.findViewById(R.id.name);
TextView NumberTextView = (TextView) view.findViewById(R.id.number);
TextView DateTextView = (TextView) view.findViewById(R.id.date);
TextView QuoteTextView = (TextView) view.findViewById(R.id.quote);
String name = cursor.getString(cursor.getColumnIndexOrThrow("quote_main"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
String quote = cursor.getString(cursor.getColumnIndexOrThrow("quote"));
nameTextView.setText(name + " ");
numberTextView.setText(String.valueOf(number) + ":");
dateTextView.setText(String.valueOf(date));
quoteTextView.setText(quote);
}
}
This is my log cat for the null pointer...
Process: com.myapps.dailyquotes, PID: 15024
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.myapps.dailyquotes.TodaysQuoteAlarmReceiver@d63089d
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_52497(LoadedApk.java:1323)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.$m$7(Unknown Source:4)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.run(Unknown Source:39)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:109)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:129)
at com.myapps.dailyquotes.MainActivity.DailyQuoteDatabaseAccess(MainActivity.java:403)
at com.myapps.dailyquotes.TodaysQuoteAlarmReceiver.onReceive(TodaysQuoteAlarmReceiver.java:18)
The receiver does attempt to run the method from MainActivity so I know it's making the connection but the error is coming from this line inside the DailyQuoteDatabaseAccess method inside of the MainActivity class:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);

1
"but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class" - please Elaborate more.
– DarShan
Nov 22 '18 at 4:57
@DarShan thank you for your reply. one problem I had was I created an object of my mainactivity in the onReceive method in the TodaysQuoteAlarmReceiver class and tried to run it from there on the alarm firing but when the alarm fired it crashed the app with a null pointer exception... I tried making the methods static to pass data via intent but I had problems with that in the way of "this" not being about to be used plus I know passing a cursor or cursor adapter is bad practice and really I don't see how it's possible anyway so I wasn't sure what to pass to the MainActivity to make it work.
– Stark
Nov 22 '18 at 5:10
1
why not simply start the MainActivity via startActivity(); to show the Quote from the BroadcastReceiver?
– DarShan
Nov 22 '18 at 5:15
1
@stark better go for Room Persistance library while playing with database,
– Suresh Maidaragi
Nov 22 '18 at 6:55
add a comment |
I am busy working on a quotes app that will show the user a new motivational quote each morning at 9:00am.
I have this method in my MainActivity to pull and show the quote in a listView that shows the single quote. I know other examples of questions of this type exist but I have not seen one using database data and cursors or cursor adapters as I need to.
public void DailyQuoteDatabaseAccess(){
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase SqlDb = sqLiteOpenHelper.getReadableDatabase();
String rawQuery = "SELECT * FROM dailyQuoteTable ORDER BY RANDOM() LIMIT 1";
Cursor cursor = SqlDb.rawQuery(rawQuery, null);
DailyQuoteCursorAdapter DQCursorAdapter = new DailyQuoteCursorAdapter(this, cursor);
this.mDailyQuoteListView.setAdapter(DQCursorAdapter);
}
I was calling this method from OnCreate and it works perfectly however it reloads each time the app is restarted. I am using AlarmManager to set the alarm to change the quote each morning at 9:00am and the alarm is firing but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class. Here is that class... blank because I can't figure out how to make it work.
package com.myapps.dailyquotes;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TodaysQuoteAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity mainActivity = new MainActivity();
mainActivity.DailyQuoteDatabaseAccess();
}
}
Any help in this arena would be very much appreciated. Should I use an intent or an object of an entirely new class and can you please provide an example?
****11/22/18****
I forgot to add my custom cursor adapter... I think this may make a difference but I'm still not sure how to integrate it with Broadcast Receiver to pass the data I need...
public class DailyQuoteCursorAdapter extends CursorAdapter{
public DailyQuoteCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.daily_quote_item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView NameTextView = (TextView) view.findViewById(R.id.name);
TextView NumberTextView = (TextView) view.findViewById(R.id.number);
TextView DateTextView = (TextView) view.findViewById(R.id.date);
TextView QuoteTextView = (TextView) view.findViewById(R.id.quote);
String name = cursor.getString(cursor.getColumnIndexOrThrow("quote_main"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
String quote = cursor.getString(cursor.getColumnIndexOrThrow("quote"));
nameTextView.setText(name + " ");
numberTextView.setText(String.valueOf(number) + ":");
dateTextView.setText(String.valueOf(date));
quoteTextView.setText(quote);
}
}
This is my log cat for the null pointer...
Process: com.myapps.dailyquotes, PID: 15024
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.myapps.dailyquotes.TodaysQuoteAlarmReceiver@d63089d
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_52497(LoadedApk.java:1323)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.$m$7(Unknown Source:4)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.run(Unknown Source:39)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:109)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:129)
at com.myapps.dailyquotes.MainActivity.DailyQuoteDatabaseAccess(MainActivity.java:403)
at com.myapps.dailyquotes.TodaysQuoteAlarmReceiver.onReceive(TodaysQuoteAlarmReceiver.java:18)
The receiver does attempt to run the method from MainActivity so I know it's making the connection but the error is coming from this line inside the DailyQuoteDatabaseAccess method inside of the MainActivity class:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);

I am busy working on a quotes app that will show the user a new motivational quote each morning at 9:00am.
I have this method in my MainActivity to pull and show the quote in a listView that shows the single quote. I know other examples of questions of this type exist but I have not seen one using database data and cursors or cursor adapters as I need to.
public void DailyQuoteDatabaseAccess(){
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase SqlDb = sqLiteOpenHelper.getReadableDatabase();
String rawQuery = "SELECT * FROM dailyQuoteTable ORDER BY RANDOM() LIMIT 1";
Cursor cursor = SqlDb.rawQuery(rawQuery, null);
DailyQuoteCursorAdapter DQCursorAdapter = new DailyQuoteCursorAdapter(this, cursor);
this.mDailyQuoteListView.setAdapter(DQCursorAdapter);
}
I was calling this method from OnCreate and it works perfectly however it reloads each time the app is restarted. I am using AlarmManager to set the alarm to change the quote each morning at 9:00am and the alarm is firing but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class. Here is that class... blank because I can't figure out how to make it work.
package com.myapps.dailyquotes;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TodaysQuoteAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity mainActivity = new MainActivity();
mainActivity.DailyQuoteDatabaseAccess();
}
}
Any help in this arena would be very much appreciated. Should I use an intent or an object of an entirely new class and can you please provide an example?
****11/22/18****
I forgot to add my custom cursor adapter... I think this may make a difference but I'm still not sure how to integrate it with Broadcast Receiver to pass the data I need...
public class DailyQuoteCursorAdapter extends CursorAdapter{
public DailyQuoteCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.daily_quote_item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView NameTextView = (TextView) view.findViewById(R.id.name);
TextView NumberTextView = (TextView) view.findViewById(R.id.number);
TextView DateTextView = (TextView) view.findViewById(R.id.date);
TextView QuoteTextView = (TextView) view.findViewById(R.id.quote);
String name = cursor.getString(cursor.getColumnIndexOrThrow("quote_main"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
String quote = cursor.getString(cursor.getColumnIndexOrThrow("quote"));
nameTextView.setText(name + " ");
numberTextView.setText(String.valueOf(number) + ":");
dateTextView.setText(String.valueOf(date));
quoteTextView.setText(quote);
}
}
This is my log cat for the null pointer...
Process: com.myapps.dailyquotes, PID: 15024
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.myapps.dailyquotes.TodaysQuoteAlarmReceiver@d63089d
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_52497(LoadedApk.java:1323)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.$m$7(Unknown Source:4)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.run(Unknown Source:39)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:109)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:129)
at com.myapps.dailyquotes.MainActivity.DailyQuoteDatabaseAccess(MainActivity.java:403)
at com.myapps.dailyquotes.TodaysQuoteAlarmReceiver.onReceive(TodaysQuoteAlarmReceiver.java:18)
The receiver does attempt to run the method from MainActivity so I know it's making the connection but the error is coming from this line inside the DailyQuoteDatabaseAccess method inside of the MainActivity class:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);


edited Nov 30 '18 at 17:49
Stark
asked Nov 22 '18 at 4:07


StarkStark
409
409
1
"but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class" - please Elaborate more.
– DarShan
Nov 22 '18 at 4:57
@DarShan thank you for your reply. one problem I had was I created an object of my mainactivity in the onReceive method in the TodaysQuoteAlarmReceiver class and tried to run it from there on the alarm firing but when the alarm fired it crashed the app with a null pointer exception... I tried making the methods static to pass data via intent but I had problems with that in the way of "this" not being about to be used plus I know passing a cursor or cursor adapter is bad practice and really I don't see how it's possible anyway so I wasn't sure what to pass to the MainActivity to make it work.
– Stark
Nov 22 '18 at 5:10
1
why not simply start the MainActivity via startActivity(); to show the Quote from the BroadcastReceiver?
– DarShan
Nov 22 '18 at 5:15
1
@stark better go for Room Persistance library while playing with database,
– Suresh Maidaragi
Nov 22 '18 at 6:55
add a comment |
1
"but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class" - please Elaborate more.
– DarShan
Nov 22 '18 at 4:57
@DarShan thank you for your reply. one problem I had was I created an object of my mainactivity in the onReceive method in the TodaysQuoteAlarmReceiver class and tried to run it from there on the alarm firing but when the alarm fired it crashed the app with a null pointer exception... I tried making the methods static to pass data via intent but I had problems with that in the way of "this" not being about to be used plus I know passing a cursor or cursor adapter is bad practice and really I don't see how it's possible anyway so I wasn't sure what to pass to the MainActivity to make it work.
– Stark
Nov 22 '18 at 5:10
1
why not simply start the MainActivity via startActivity(); to show the Quote from the BroadcastReceiver?
– DarShan
Nov 22 '18 at 5:15
1
@stark better go for Room Persistance library while playing with database,
– Suresh Maidaragi
Nov 22 '18 at 6:55
1
1
"but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class" - please Elaborate more.
– DarShan
Nov 22 '18 at 4:57
"but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class" - please Elaborate more.
– DarShan
Nov 22 '18 at 4:57
@DarShan thank you for your reply. one problem I had was I created an object of my mainactivity in the onReceive method in the TodaysQuoteAlarmReceiver class and tried to run it from there on the alarm firing but when the alarm fired it crashed the app with a null pointer exception... I tried making the methods static to pass data via intent but I had problems with that in the way of "this" not being about to be used plus I know passing a cursor or cursor adapter is bad practice and really I don't see how it's possible anyway so I wasn't sure what to pass to the MainActivity to make it work.
– Stark
Nov 22 '18 at 5:10
@DarShan thank you for your reply. one problem I had was I created an object of my mainactivity in the onReceive method in the TodaysQuoteAlarmReceiver class and tried to run it from there on the alarm firing but when the alarm fired it crashed the app with a null pointer exception... I tried making the methods static to pass data via intent but I had problems with that in the way of "this" not being about to be used plus I know passing a cursor or cursor adapter is bad practice and really I don't see how it's possible anyway so I wasn't sure what to pass to the MainActivity to make it work.
– Stark
Nov 22 '18 at 5:10
1
1
why not simply start the MainActivity via startActivity(); to show the Quote from the BroadcastReceiver?
– DarShan
Nov 22 '18 at 5:15
why not simply start the MainActivity via startActivity(); to show the Quote from the BroadcastReceiver?
– DarShan
Nov 22 '18 at 5:15
1
1
@stark better go for Room Persistance library while playing with database,
– Suresh Maidaragi
Nov 22 '18 at 6:55
@stark better go for Room Persistance library while playing with database,
– Suresh Maidaragi
Nov 22 '18 at 6:55
add a comment |
1 Answer
1
active
oldest
votes
For Daily Quotes, I have do something....
public void setAlarm() {
// Quote in Morning at 08:32:00 AM
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 32);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
now make function in database class to get random quote in database class
public String getAlarmQuote(int id, String table) {
String quote = "", author = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table, new String{QUOTE_ID, QUOTE_QUOTE, QUOTE_AUTHOR}, QUOTE_ID + "=?", new String{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
quote = cursor.getString(cursor.getColumnIndex(QUOTE_QUOTE));
author = cursor.getString(cursor.getColumnIndex(QUOTE_AUTHOR));
}
}
db.close();
return quote;
}
and to get this reciver
public class DailyReceiver extends BroadcastReceiver {
DatabaseHelper databaseHelper;
@Override
public void onReceive(Context context, Intent intent) {String quote ;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, DailySpecialActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// get your quote here
int max = databaseHelper.getTotalQuotes(); // here you have to put total number of quotes in your database table
Random r = new Random();
int randomNumber = r.nextInt(max - 1 + 1) + 1;
quote = databaseHelper.getAlarmQuote(randomNumber, YourTableName);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Quotes")
.setContentText(quote).setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setStyle(new NotificationCompat.BigTextStyle().bigText(quote))
.setContentIntent(pendingIntent)
.setVibrate(new long{1000, 1000, 1000, 1000, 1000}); // Declair VIBRATOR Permission in AndroidManifest.xml
notificationManager.notify(5, mNotifyBuilder.build());
}
}
Here when you reboot your phone you also need to restart your alarm, so I have do
public class WakeUpAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Quote in Morning
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
Finally here is your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nils.myquotesapp">
<!--you must need this three permissions-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name="com.nils.myquotesapp.QuotesApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.nils.myquotesapp.Activity.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.nils.myquotesapp.DailyReceiver"
android:enabled="true" />
<receiver
android:name="com.nils.myquotesapp.WakeUpAlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</manifest>
thank you very much for your detailed reply. I am going to review this and attempt to integrate the logic into my app. I wonder if it will make a difference that you are using query and I am using rawQuery to fetch the data. If will let you know. Thanks again.
– Stark
Nov 22 '18 at 13:44
Can you please take a look at the code for my custom cursor adapter? I added it. I forgot to add it when I originally posted the question because I am using that in my query to populate the listView properly.
– Stark
Nov 22 '18 at 14:18
1
just try this code and tell me
– Developer_ rahul
Nov 23 '18 at 11:38
Thank you Rahul. That looks like good code that you wrote and seems related to my issue however I can't make it work for my exact issue. I have added some details in my post and my logcat and an explaination of the error that I am getting now.
– Stark
Nov 30 '18 at 15:05
Thank you Rahul. I upvoted your answer because, although it did not completely solve my unique issue, I got something out of it and you took the time to post it.
– Stark
Dec 8 '18 at 0:26
|
show 1 more comment
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53423749%2fandroid-alarm-manager-nullpointer-when-accessing-sqliteopenhelper-in-mainactiv%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
For Daily Quotes, I have do something....
public void setAlarm() {
// Quote in Morning at 08:32:00 AM
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 32);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
now make function in database class to get random quote in database class
public String getAlarmQuote(int id, String table) {
String quote = "", author = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table, new String{QUOTE_ID, QUOTE_QUOTE, QUOTE_AUTHOR}, QUOTE_ID + "=?", new String{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
quote = cursor.getString(cursor.getColumnIndex(QUOTE_QUOTE));
author = cursor.getString(cursor.getColumnIndex(QUOTE_AUTHOR));
}
}
db.close();
return quote;
}
and to get this reciver
public class DailyReceiver extends BroadcastReceiver {
DatabaseHelper databaseHelper;
@Override
public void onReceive(Context context, Intent intent) {String quote ;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, DailySpecialActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// get your quote here
int max = databaseHelper.getTotalQuotes(); // here you have to put total number of quotes in your database table
Random r = new Random();
int randomNumber = r.nextInt(max - 1 + 1) + 1;
quote = databaseHelper.getAlarmQuote(randomNumber, YourTableName);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Quotes")
.setContentText(quote).setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setStyle(new NotificationCompat.BigTextStyle().bigText(quote))
.setContentIntent(pendingIntent)
.setVibrate(new long{1000, 1000, 1000, 1000, 1000}); // Declair VIBRATOR Permission in AndroidManifest.xml
notificationManager.notify(5, mNotifyBuilder.build());
}
}
Here when you reboot your phone you also need to restart your alarm, so I have do
public class WakeUpAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Quote in Morning
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
Finally here is your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nils.myquotesapp">
<!--you must need this three permissions-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name="com.nils.myquotesapp.QuotesApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.nils.myquotesapp.Activity.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.nils.myquotesapp.DailyReceiver"
android:enabled="true" />
<receiver
android:name="com.nils.myquotesapp.WakeUpAlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</manifest>
thank you very much for your detailed reply. I am going to review this and attempt to integrate the logic into my app. I wonder if it will make a difference that you are using query and I am using rawQuery to fetch the data. If will let you know. Thanks again.
– Stark
Nov 22 '18 at 13:44
Can you please take a look at the code for my custom cursor adapter? I added it. I forgot to add it when I originally posted the question because I am using that in my query to populate the listView properly.
– Stark
Nov 22 '18 at 14:18
1
just try this code and tell me
– Developer_ rahul
Nov 23 '18 at 11:38
Thank you Rahul. That looks like good code that you wrote and seems related to my issue however I can't make it work for my exact issue. I have added some details in my post and my logcat and an explaination of the error that I am getting now.
– Stark
Nov 30 '18 at 15:05
Thank you Rahul. I upvoted your answer because, although it did not completely solve my unique issue, I got something out of it and you took the time to post it.
– Stark
Dec 8 '18 at 0:26
|
show 1 more comment
For Daily Quotes, I have do something....
public void setAlarm() {
// Quote in Morning at 08:32:00 AM
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 32);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
now make function in database class to get random quote in database class
public String getAlarmQuote(int id, String table) {
String quote = "", author = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table, new String{QUOTE_ID, QUOTE_QUOTE, QUOTE_AUTHOR}, QUOTE_ID + "=?", new String{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
quote = cursor.getString(cursor.getColumnIndex(QUOTE_QUOTE));
author = cursor.getString(cursor.getColumnIndex(QUOTE_AUTHOR));
}
}
db.close();
return quote;
}
and to get this reciver
public class DailyReceiver extends BroadcastReceiver {
DatabaseHelper databaseHelper;
@Override
public void onReceive(Context context, Intent intent) {String quote ;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, DailySpecialActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// get your quote here
int max = databaseHelper.getTotalQuotes(); // here you have to put total number of quotes in your database table
Random r = new Random();
int randomNumber = r.nextInt(max - 1 + 1) + 1;
quote = databaseHelper.getAlarmQuote(randomNumber, YourTableName);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Quotes")
.setContentText(quote).setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setStyle(new NotificationCompat.BigTextStyle().bigText(quote))
.setContentIntent(pendingIntent)
.setVibrate(new long{1000, 1000, 1000, 1000, 1000}); // Declair VIBRATOR Permission in AndroidManifest.xml
notificationManager.notify(5, mNotifyBuilder.build());
}
}
Here when you reboot your phone you also need to restart your alarm, so I have do
public class WakeUpAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Quote in Morning
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
Finally here is your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nils.myquotesapp">
<!--you must need this three permissions-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name="com.nils.myquotesapp.QuotesApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.nils.myquotesapp.Activity.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.nils.myquotesapp.DailyReceiver"
android:enabled="true" />
<receiver
android:name="com.nils.myquotesapp.WakeUpAlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</manifest>
thank you very much for your detailed reply. I am going to review this and attempt to integrate the logic into my app. I wonder if it will make a difference that you are using query and I am using rawQuery to fetch the data. If will let you know. Thanks again.
– Stark
Nov 22 '18 at 13:44
Can you please take a look at the code for my custom cursor adapter? I added it. I forgot to add it when I originally posted the question because I am using that in my query to populate the listView properly.
– Stark
Nov 22 '18 at 14:18
1
just try this code and tell me
– Developer_ rahul
Nov 23 '18 at 11:38
Thank you Rahul. That looks like good code that you wrote and seems related to my issue however I can't make it work for my exact issue. I have added some details in my post and my logcat and an explaination of the error that I am getting now.
– Stark
Nov 30 '18 at 15:05
Thank you Rahul. I upvoted your answer because, although it did not completely solve my unique issue, I got something out of it and you took the time to post it.
– Stark
Dec 8 '18 at 0:26
|
show 1 more comment
For Daily Quotes, I have do something....
public void setAlarm() {
// Quote in Morning at 08:32:00 AM
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 32);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
now make function in database class to get random quote in database class
public String getAlarmQuote(int id, String table) {
String quote = "", author = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table, new String{QUOTE_ID, QUOTE_QUOTE, QUOTE_AUTHOR}, QUOTE_ID + "=?", new String{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
quote = cursor.getString(cursor.getColumnIndex(QUOTE_QUOTE));
author = cursor.getString(cursor.getColumnIndex(QUOTE_AUTHOR));
}
}
db.close();
return quote;
}
and to get this reciver
public class DailyReceiver extends BroadcastReceiver {
DatabaseHelper databaseHelper;
@Override
public void onReceive(Context context, Intent intent) {String quote ;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, DailySpecialActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// get your quote here
int max = databaseHelper.getTotalQuotes(); // here you have to put total number of quotes in your database table
Random r = new Random();
int randomNumber = r.nextInt(max - 1 + 1) + 1;
quote = databaseHelper.getAlarmQuote(randomNumber, YourTableName);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Quotes")
.setContentText(quote).setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setStyle(new NotificationCompat.BigTextStyle().bigText(quote))
.setContentIntent(pendingIntent)
.setVibrate(new long{1000, 1000, 1000, 1000, 1000}); // Declair VIBRATOR Permission in AndroidManifest.xml
notificationManager.notify(5, mNotifyBuilder.build());
}
}
Here when you reboot your phone you also need to restart your alarm, so I have do
public class WakeUpAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Quote in Morning
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
Finally here is your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nils.myquotesapp">
<!--you must need this three permissions-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name="com.nils.myquotesapp.QuotesApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.nils.myquotesapp.Activity.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.nils.myquotesapp.DailyReceiver"
android:enabled="true" />
<receiver
android:name="com.nils.myquotesapp.WakeUpAlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</manifest>
For Daily Quotes, I have do something....
public void setAlarm() {
// Quote in Morning at 08:32:00 AM
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 32);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
now make function in database class to get random quote in database class
public String getAlarmQuote(int id, String table) {
String quote = "", author = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table, new String{QUOTE_ID, QUOTE_QUOTE, QUOTE_AUTHOR}, QUOTE_ID + "=?", new String{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
quote = cursor.getString(cursor.getColumnIndex(QUOTE_QUOTE));
author = cursor.getString(cursor.getColumnIndex(QUOTE_AUTHOR));
}
}
db.close();
return quote;
}
and to get this reciver
public class DailyReceiver extends BroadcastReceiver {
DatabaseHelper databaseHelper;
@Override
public void onReceive(Context context, Intent intent) {String quote ;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, DailySpecialActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// get your quote here
int max = databaseHelper.getTotalQuotes(); // here you have to put total number of quotes in your database table
Random r = new Random();
int randomNumber = r.nextInt(max - 1 + 1) + 1;
quote = databaseHelper.getAlarmQuote(randomNumber, YourTableName);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Quotes")
.setContentText(quote).setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setStyle(new NotificationCompat.BigTextStyle().bigText(quote))
.setContentIntent(pendingIntent)
.setVibrate(new long{1000, 1000, 1000, 1000, 1000}); // Declair VIBRATOR Permission in AndroidManifest.xml
notificationManager.notify(5, mNotifyBuilder.build());
}
}
Here when you reboot your phone you also need to restart your alarm, so I have do
public class WakeUpAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Quote in Morning
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Calendar cur = Calendar.getInstance();
if (cur.after(calendar)) {
calendar.add(Calendar.DATE, 1);
}
Intent myIntent = new Intent(context, DailyReceiver.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
Finally here is your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nils.myquotesapp">
<!--you must need this three permissions-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name="com.nils.myquotesapp.QuotesApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.nils.myquotesapp.Activity.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.nils.myquotesapp.DailyReceiver"
android:enabled="true" />
<receiver
android:name="com.nils.myquotesapp.WakeUpAlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</manifest>
answered Nov 22 '18 at 5:40


Developer_ rahulDeveloper_ rahul
262
262
thank you very much for your detailed reply. I am going to review this and attempt to integrate the logic into my app. I wonder if it will make a difference that you are using query and I am using rawQuery to fetch the data. If will let you know. Thanks again.
– Stark
Nov 22 '18 at 13:44
Can you please take a look at the code for my custom cursor adapter? I added it. I forgot to add it when I originally posted the question because I am using that in my query to populate the listView properly.
– Stark
Nov 22 '18 at 14:18
1
just try this code and tell me
– Developer_ rahul
Nov 23 '18 at 11:38
Thank you Rahul. That looks like good code that you wrote and seems related to my issue however I can't make it work for my exact issue. I have added some details in my post and my logcat and an explaination of the error that I am getting now.
– Stark
Nov 30 '18 at 15:05
Thank you Rahul. I upvoted your answer because, although it did not completely solve my unique issue, I got something out of it and you took the time to post it.
– Stark
Dec 8 '18 at 0:26
|
show 1 more comment
thank you very much for your detailed reply. I am going to review this and attempt to integrate the logic into my app. I wonder if it will make a difference that you are using query and I am using rawQuery to fetch the data. If will let you know. Thanks again.
– Stark
Nov 22 '18 at 13:44
Can you please take a look at the code for my custom cursor adapter? I added it. I forgot to add it when I originally posted the question because I am using that in my query to populate the listView properly.
– Stark
Nov 22 '18 at 14:18
1
just try this code and tell me
– Developer_ rahul
Nov 23 '18 at 11:38
Thank you Rahul. That looks like good code that you wrote and seems related to my issue however I can't make it work for my exact issue. I have added some details in my post and my logcat and an explaination of the error that I am getting now.
– Stark
Nov 30 '18 at 15:05
Thank you Rahul. I upvoted your answer because, although it did not completely solve my unique issue, I got something out of it and you took the time to post it.
– Stark
Dec 8 '18 at 0:26
thank you very much for your detailed reply. I am going to review this and attempt to integrate the logic into my app. I wonder if it will make a difference that you are using query and I am using rawQuery to fetch the data. If will let you know. Thanks again.
– Stark
Nov 22 '18 at 13:44
thank you very much for your detailed reply. I am going to review this and attempt to integrate the logic into my app. I wonder if it will make a difference that you are using query and I am using rawQuery to fetch the data. If will let you know. Thanks again.
– Stark
Nov 22 '18 at 13:44
Can you please take a look at the code for my custom cursor adapter? I added it. I forgot to add it when I originally posted the question because I am using that in my query to populate the listView properly.
– Stark
Nov 22 '18 at 14:18
Can you please take a look at the code for my custom cursor adapter? I added it. I forgot to add it when I originally posted the question because I am using that in my query to populate the listView properly.
– Stark
Nov 22 '18 at 14:18
1
1
just try this code and tell me
– Developer_ rahul
Nov 23 '18 at 11:38
just try this code and tell me
– Developer_ rahul
Nov 23 '18 at 11:38
Thank you Rahul. That looks like good code that you wrote and seems related to my issue however I can't make it work for my exact issue. I have added some details in my post and my logcat and an explaination of the error that I am getting now.
– Stark
Nov 30 '18 at 15:05
Thank you Rahul. That looks like good code that you wrote and seems related to my issue however I can't make it work for my exact issue. I have added some details in my post and my logcat and an explaination of the error that I am getting now.
– Stark
Nov 30 '18 at 15:05
Thank you Rahul. I upvoted your answer because, although it did not completely solve my unique issue, I got something out of it and you took the time to post it.
– Stark
Dec 8 '18 at 0:26
Thank you Rahul. I upvoted your answer because, although it did not completely solve my unique issue, I got something out of it and you took the time to post it.
– Stark
Dec 8 '18 at 0:26
|
show 1 more comment
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53423749%2fandroid-alarm-manager-nullpointer-when-accessing-sqliteopenhelper-in-mainactiv%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
"but the problem lies in being able to run that intent in my MainActivity from the Broadcast Receiver class" - please Elaborate more.
– DarShan
Nov 22 '18 at 4:57
@DarShan thank you for your reply. one problem I had was I created an object of my mainactivity in the onReceive method in the TodaysQuoteAlarmReceiver class and tried to run it from there on the alarm firing but when the alarm fired it crashed the app with a null pointer exception... I tried making the methods static to pass data via intent but I had problems with that in the way of "this" not being about to be used plus I know passing a cursor or cursor adapter is bad practice and really I don't see how it's possible anyway so I wasn't sure what to pass to the MainActivity to make it work.
– Stark
Nov 22 '18 at 5:10
1
why not simply start the MainActivity via startActivity(); to show the Quote from the BroadcastReceiver?
– DarShan
Nov 22 '18 at 5:15
1
@stark better go for Room Persistance library while playing with database,
– Suresh Maidaragi
Nov 22 '18 at 6:55