I have created one listview where I want to retrieve the items from sqlite database. So I have created one method as a List named as getrequestitems where I will map the details and add to a arraylist.
public List<Map<String, String>> getrequestitems() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
SQLiteDatabase db = dbHandler.getReadableDatabase();
String sql = "SELECT * from request WHERE time > date('now','-1 day')";
Cursor rs = db.rawQuery(sql,null);
if(rs.moveToFirst()) {
do {
Map<String, String> dtname = new HashMap<String, String>();
dtname.put("bloodgrp", rs.getString(rs.getColumnIndex("bloodgrp")));
dtname.put("date", "Date:- " + rs.getString(rs.getColumnIndex("Datetime1")));
dtname.put("time", "Time:- " + rs.getString(rs.getColumnIndex("time")));
dtname.put("name", "Name:- " + rs.getString(rs.getColumnIndex("Name")));
dtname.put("Username", rs.getString(rs.getColumnIndex("Username")));
data.add(dtname);
}
while (rs.moveToNext());
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return data;
}
But When I open that activity It doesn't displayed any records. I have debug the code but can't any exception. I have written wrong query? as "SELECT * from request WHERE time > date('now','-1 day')";
Here is my complete code.
public class request extends AppCompatActivity {
SimpleAdapter ad;
TextView list3;
private SlidrInterface slidr;
private DBHandler dbHandler;
private static ArrayList<String> arrayList = new ArrayList<>();
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
slidr = Slidr.attach(this);
slidr.unlock();
dbHandler = new DBHandler(this);
list3 = findViewById(R.id.list3);
TextView txt = findViewById(R.id.list4);
ListView lst1 = (ListView) findViewById(R.id.list2);
List<Map<String, String>> MyDataList = null;
MyDataList = getrequestitems();
String[] from = {"bloodgrp", "date", "time", "name", "Username"};
int[] to = {R.id.listt, R.id.date, R.id.time1, R.id.name3, R.id.user};
ad = new SimpleAdapter(request.this, MyDataList, R.layout.listrequest, from, to);
lst1.setAdapter(ad);
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
List<Map<String, String>> MyDataList1 = null;
MyDataList1 = getrequestitems();
String[] from = {"Username"};
int[] to = {R.id.user};
Toast.makeText(getApplicationContext(), MyDataList1.toString(), Toast.LENGTH_SHORT).show();
ad = new SimpleAdapter(request.this, MyDataList1, R.layout.listrequest, from, to);
if(ad.getCount()==0){
Toast.makeText(getApplicationContext(), "No requests are currently visible", Toast.LENGTH_SHORT).show();
}
HashMap<String, String> obj = (HashMap<String, String>) ad.getItem(i);
String name = (String) obj.get("Username");
try {
SQLiteDatabase db = dbHandler.getReadableDatabase();
String sql = "select * from request where Username = '" + name + "'";
Cursor rs = db.rawQuery(sql,null);
if (rs.moveToFirst()) {
do {
runOnUiThread(new Runnable() {
#SuppressLint("Range")
#Override
public void run() {
try {
final AlertDialog.Builder alert = new AlertDialog.Builder(request.this);
View mView = getLayoutInflater().inflate(R.layout.custom_dialog3, null);
final TextView txt_inputText = (TextView) mView.findViewById(R.id.name1);
txt_inputText.setText(rs.getString(rs.getColumnIndex("Name")));
final TextView txt_inputText2 = (TextView) mView.findViewById(R.id.contactno1);
txt_inputText2.setText(rs.getString(rs.getColumnIndex("contactNo")));
final TextView txt_inputText3 = (TextView) mView.findViewById(R.id.message1);
txt_inputText3.setText(rs.getString(rs.getColumnIndex("message")));
Button btn_cancel = (Button) mView.findViewById(R.id.btn_cancel);
Button btn_okay = (Button) mView.findViewById(R.id.btn_okay);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = txt_inputText2.getText().toString();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));// Initiates the Intent
startActivity(intent);
alertDialog.dismiss();
}
});
alertDialog.show();
alertDialog.getWindow().setLayout(730, 850); //Controlling width and height.
} catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
});
}while (rs.moveToNext());
}
} catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
});
}
#SuppressLint("Range")
public List<Map<String, String>> getrequestitems() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
SQLiteDatabase db = dbHandler.getReadableDatabase();
String sql = "SELECT * from request WHERE time > date('now','-1 day')";
Cursor rs = db.rawQuery(sql,null);
if(rs.moveToFirst()) {
do {
Map<String, String> dtname = new HashMap<String, String>();
dtname.put("bloodgrp", rs.getString(rs.getColumnIndex("bloodgrp")));
dtname.put("date", "Date:- " + rs.getString(rs.getColumnIndex("Datetime1")));
dtname.put("time", "Time:- " + rs.getString(rs.getColumnIndex("time")));
dtname.put("name", "Name:- " + rs.getString(rs.getColumnIndex("Name")));
dtname.put("Username", rs.getString(rs.getColumnIndex("Username")));
data.add(dtname);
}
while (rs.moveToNext());
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return data;
}
}
But When I open that activity It doesn't displayed any records. I have debug the code but can't any exception. I have written wrong query?
probably as it appears that you are very likely comparing the anecdotal oranges and apples (see explanation/example) that is, at a guess you are comparing the time and a date (see Possible fix below BUT this very much depends upon what you are actually storing in the time column, see Possible debug action below that would allow you to see a) if you are extracting any data and if applying the get all (no WHERE clause) to see the actual underlying data)
format is yyyy-MM-dd –
That seems unlikely or if not a waste seeing that you have a column for the date and a column for the time.
If the time contains just the time hh:mm or even hh:mm:ss, as an example then extracting the date is going to result in unintended results.
Consider the following that highlights the issues that you may encounter:-
DROP TABLE IF EXISTS request;
CREATE TABLE IF NOT EXISTS request (booldgrp TEXT, Datetime1 TEXT, time TEXT, Name TEXT, Username TEXT);
INSERT INTO request VALUES
('O','2023-01-01 10:10','2023-01-01 10:10','FRED','USER001')
,('O','2023-01-01 10:10','10:10','FRED','USER002')
,('O','2023-01-01 10:10','2023-01-01 23:11','FRED','USER003')
,('O','2023-01-01 10:10','23:59','FRED','USER004')
,('O','2023-01-01 10:10','21:59','FRED','USER005')
,('O','2023-01-01 10:10','22:00','FRED','USER006')
,('O','2023-01-01 10:10','20:00','FRED','USER007')
,('O','2023-01-01 10:10','20:01','FRED','USER008')
,('O','2023-01-01 10:10','19:59:59','FRED','USER009')
;
SELECT *, date('now','-1 day') AS comparedate, time > date('now','-1 day') AS comparison FROM request;
SELECT *, date('now','-1 day') AS comparedate, datetime1 > date('now','-1 day') AS comparison FROM request;
DROP table IF EXISTS request;
that you can run in your favourite SQLite tool (Navicat was used)
The resultant output (what would be in the Cursor) is :-
As can be seen if the time is actually stored as hh:mm or hh:mm:ss (or similar where you just have the time and not the date) then the first 2 characters are significant, so if the year of the current date - 1 day is in the 21st century that only times that are 8 pm (20:00) or greater would be selected.
Possible fix (if date column has the date only or the date and time and the time column has the time)
Perhaps you want "SELECT * from request WHERE datetime1 > date('now','-1 day')"
Possible debug action
If the above is not the fix for your situation then consider changing your code to :-
SQLiteDatabase db = dbHandler.getReadableDatabase();
String sql = "SELECT * from request /* WHERE time > date('now','-1 day') */"; // <<<<<<<<<< WHERE clause commented out to get ALL data, try also with WHERE clause */
Cursor rs = db.rawQuery(sql,null);
DatabaseUtils.dumpCursor(rs); /* ADDED FOR DEBUG, run and check the LOG */
if(rs.moveToFirst()) {
see comments
The log would include either something like (where data is extracted ):-
2022-07-19 13:21:50.995 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor#31816bf
2022-07-19 13:21:50.996 I/System.out: 0 {
2022-07-19 13:21:50.996 I/System.out: bloodgrp=O
2022-07-19 13:21:50.996 I/System.out: Datetime1=2023-01-01
2022-07-19 13:21:50.996 I/System.out: time=10:30
2022-07-19 13:21:50.996 I/System.out: Name=FRED
2022-07-19 13:21:50.996 I/System.out: Username=USER001
2022-07-19 13:21:50.996 I/System.out: }
2022-07-19 13:21:50.996 I/System.out: <<<<<
or (where no data has been extracted) :-
2022-07-19 13:24:12.216 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor#30380ea
2022-07-19 13:24:12.217 I/System.out: <<<<<
Note
The getColumnIndex index method is case sensitive (or at least was) and as such if any of the column names mismatch, even if only due to the case, then the trapped exception row 0 column -1 will also result in no result (only a short while to notice this with a Toast). I would suggest:-
using Constants for column names and ALWAYS using those Constants to refer to column names i.e. only ever hard code each column name once. Incorrect variables names will not compile. Coded incorrect column names will happily compile and may not be noticed.
consider using e.printStackTrace() as well as or even instead of the Toast
trapping and catching SQLite errors can so easily mask issues
Example
based upon your code, but with :-
DBhandler and layouts composed from what can be gleaned from your code AND
with it inserting a row when the database is created as per :-
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
REQUEST_COLUMN_BLOODGROUP + " TEXT" +
"," + REQUEST_COLUMN_DATE + " TEXT" +
"," + REQUEST_COLUMN_TIME + " TEXT" +
"," + REQUEST_COLUMN_NAME + " TEXT " +
"," + REQUEST_COLUMN_USERNAME + " TEXT" +
"," + REQUEST_COLUMN_CONTACTNo + " TEXT" +
"," + REQUEST_COLUMN_MESSAGE + " TEXT" +
")");
ContentValues cv = new ContentValues();
cv.put(REQUEST_COLUMN_BLOODGROUP,"O");
cv.put(REQUEST_COLUMN_DATE,"2023-01-01");
cv.put(REQUEST_COLUMN_TIME,"10:30");
cv.put(REQUEST_COLUMN_NAME,"FRED");
cv.put(REQUEST_COLUMN_USERNAME,"USER001");
cv.put(REQUEST_COLUMN_CONTACTNo,"0000000000");
cv.put(REQUEST_COLUMN_MESSAGE,"MESSAGE X");
db.insert(TABLE_NAME,null,cv);
}
with the Request (changed to capitalise) Activity started directly from the MainActivity
and with the possible fix applied to the WHERE clause (i.e. Datetime column used for the comparison rather than the time column)
The ListView with a Teal background (to distinguish it)
Then when run :-
and then when the item is clicked:-
and if OK is clicked :-
I'm trying to display data from firebase using dates. But I only know how to display data for the current date. I would like to change the dates so I can display data from firebase with different dates. The current code I have is only displaying the data on a recyclerView from 8-9-2020. I would like to get the data from the previous day which is 7-9-2020.
firebaseAuth= FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = sdf.format(calendar.getTime());
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(currentDate);
buttonCalendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCalendar();
}
});
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
theDate.setText(date);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
month = month +1;
String date = String.format("%02d-%02d-%d", dayOfMonth, month, year);
Intent intent = new Intent(CalendarActivity.this, Breakfast.class);
intent.putExtra("date", date);
startActivity(intent);
}
});
What I'm trying to do is it will display the current date data, then when I select a new date from the calendar, it will retrieve data of the newly selected date.
I would like to somehow update the .child(currentDate) to .child(date) in which the date contains the newly selected date.
As per your code, you're opening a calendar in the new activity I can suggest if you want to use android DatePickerDialog to get a date in the same activity.
And if you want to get a date back from a particular activity you can use a startActivityForResult(yourIntent,request_code); and get result and data in
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
And after getting a successful result you can use the below method to get your firebase data.
private void getFirebaseData(String date){
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(date);
// rest is your code
}
I figured out simple way to do it:
setDate();
String date = setDate();
if (date == null || date.equals("")){
date = currentDate;
}
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(date);
made a method for setting the new date:
public String setDate(){
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
theDate.setText(date);
return date;
}
How can I send a whatsapp message to a number at a particular time automatically from my app? is there an android intent to it?
String toNumber="91XXXXXXXXXX";
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone="+ toNumber +"&text=" + URLEncoder.encode(whatsAppMessage, "UTF-8");
intent.putExtra(Intent.EXTRA_TEXT, whatsAppMessage);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, whatsAppImage);
intent.setType("image/jpeg");
intent.setPackage("com.whatsapp");
intent.setData(Uri.parse(url));
if(Calendar.HOUR==10){
startActivity(intent);
}
}
catch (Exception e){
e.printStackTrace();
}
So, your question is really about how to execute some code at a particular time, not really about whatsapp?
The simple answer is to start a timer, have it fire every second, check the current time in the timer code. If the time is 22:00:00 (10PM) or 10:00:00 (10AM), call your function.
You don't want to just check Calendar.HOUR==10 because that will be true for every second of that hour, so, you may send out many more messages than you want to.
Keep in mind, this will only happen if the app is running, and possibly only if it is running the the foreground. If you need this to happen 24 hours a day, then you probably want to create some type of system service and have it send out the messages.
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
// Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();
// ensures we're using the same current time
Calendar cal2 = cal;
// Set time of calendar to 22:00:00.000
cal.set(Calendar.HOUR_OF_DAY, 22);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after or before 22:00:00.000 today
if ((cal2.after(cal)) || (cal2.before(cal)) {
return;
}
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone="+ toNumber +"&text=" + URLEncoder.encode(whatsAppMessage, "UTF-8");
intent.putExtra(Intent.EXTRA_TEXT, whatsAppMessage);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, whatsAppImage);
intent.setType("image/jpeg");
intent.setPackage("com.whatsapp");
intent.setData(Uri.parse(url));
startActivity(intent);
}
catch (Exception e){
e.printStackTrace();
}
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
I am having some problem when trying to do a recurring task in Android. Here is how I populate my list view:
public View getView(int position, View convertView, ViewGroup parent) {
String recurID;
if (convertView == null) {
convertView = inflater.inflate(R.layout.recur_listview_row, null);
viewHolder = new ViewHolder();
viewHolder.txt_ddate = (TextView) convertView.findViewById(R.id.txtDisplayRecurDate);
viewHolder.txt_damount = (TextView) convertView.findViewById(R.id.txtDisplayRecurAmount);
viewHolder.txt_dfrequency = (TextView) convertView.findViewById(R.id.txtDisplayFrequency);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
recurID = _recurlist.get(position).getRecurringID();
// Format and calculate the next payment date based on frequency
try {
String dateStr = _recurlist.get(position).getRecurringStartDate();
String frequencyStr = _recurlist.get(position).getFrequency();
Calendar cal = Calendar.getInstance();
cal.setTime(dateFormat.parse(dateStr));
if (frequencyStr.equals("Daily")) {
cal.add(Calendar.DAY_OF_MONTH, 1);
viewHolder.txt_ddate.setText("Next Payment On: " + dateFormat.format(cal.getTimeInMillis()));
cal.add(Calendar.DAY_OF_MONTH, -1);
} else if (frequencyStr.equals("Weekly")) {
cal.add(Calendar.WEEK_OF_YEAR, 1);
viewHolder.txt_ddate.setText("Next Payment On: " + dateFormat.format(cal.getTimeInMillis()));
cal.add(Calendar.WEEK_OF_YEAR, -1);
}
} catch (ParseException e) {
e.printStackTrace();
}
viewHolder.txt_dfrequency.setText(_recurlist.get(position).getFrequency().trim());
if (_recurlist.get(position).getRecurringType().equals("W")) {
viewHolder.txt_damount.setTextColor(Color.rgb(180, 4, 4));
viewHolder.txt_damount.setText("Credit $ " + amount);
} else if (_recurlist.get(position).getRecurringType().equals("D")) {
viewHolder.txt_damount.setTextColor(Color.rgb(8, 138, 8));
viewHolder.txt_damount.setText("Debit $ " + amount);
}
// Get current date
String currentDate = "Next Payment On: " + dateFormat.format(new Date());
// If current date matches with the next payment date, insert new
// transaction record
if (currentDate.equals(viewHolder.txt_ddate.getText())) {
DatabaseAdapter mDbHelper = new DatabaseAdapter(Recurring.this);
mDbHelper.createDatabase();
mDbHelper.open();
TransactionRecModel trm = new TransactionRecModel();
CategoryController cc = new CategoryController(mDbHelper.open());
trm.setDate(dateFormat.format(new Date()));
if (_recurlist.get(position).getRecurringType().equals("W")) {
trm.setType("W");
} else if (_recurlist.get(position).getRecurringType().equals("D")) {
trm.setType("D");
}
trm.setAmount(Float.parseFloat(formatAmount));
TransactionRecController trc = new TransactionRecController(mDbHelper.open());
if (trc.addTransactionRec(trm)) {
// After successfully insert transaction record, update the
// recurring start date
rm = new RecurringModel();
rm.setRecurringID(recurID);
rm.setRecurringStartDate(dateFormat.format(new Date()));
RecurringController rc = new RecurringController(mDbHelper.open());
if (rc.updateRecurringDate(rm)) {
mDbHelper.close();
}
}
}
return convertView;
}
From the code I tried to get the current date and compare with the next payment date computed based on frequency. However, with these code, it does not run in background.
Let's say I set a recurring event which will be repeating daily yesterday. But I did not run the application today. By right, the recurring should run in background and execute the recurring. But somehow, it does not.
I wonder do I need some service like AlarmManager to do this?
Thanks in advance.
EDIT
So what I've changed is the part when I try to compare the dates, if the dates matched, it will call the alarmManager and parse some values along the way:
if (currentDate.equals(viewHolder.txt_ddate.getText())) {
long when = new Date().getTime();
notificationCount = notificationCount + 1;
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(context, ReminderAlarm.class);
notificationIntent.putExtra("RecurID", recurID);
notificationIntent.putExtra("Date", dateFormat.format(new Date()));
notificationIntent.putExtra("Description", viewHolder.txt_ddesc.getText().toString());
notificationIntent.putExtra("Type", _recurlist.get(position).getRecurringType());
notificationIntent.putExtra("Amount", Float.parseFloat(formatAmount));
notificationIntent.putExtra("CategoryID", viewHolder.txt_dcat.getText().toString());
notificationIntent.putExtra("NotifyCount", notificationCount);
PendingIntent pi = PendingIntent.getBroadcast(context, notificationCount, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.set(AlarmManager.RTC_WAKEUP, when, pi);
}
And in my ReminderAlarm class, I am executing the insert and update SQL statement:
public class ReminderAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String recurID = intent.getStringExtra("RecurID");
String date = intent.getStringExtra("Date");
String description = intent.getStringExtra("Description");
String type = intent.getStringExtra("Type");
Float amount = Float.parseFloat(intent.getStringExtra("Amount"));
String categoryID = intent.getStringExtra("CategoryID");
DatabaseAdapter mDbHelper = new DatabaseAdapter(ReminderAlarm.this);
mDbHelper.createDatabase();
mDbHelper.open();
TransactionRecModel trm = new TransactionRecModel();
CategoryController cc = new CategoryController(mDbHelper.open());
trm.setDate(date);
trm.setTransDescription(description);
if (type.equals("W")) {
trm.setType("W");
} else if (type.equals("D")) {
trm.setType("D");
}
trm.setAmount(amount);
// Get the categoryID based on categoryName
String catID = cc.getCatIDByName(categoryID);
trm.setCategory(catID);
TransactionRecController trc = new TransactionRecController(mDbHelper.open());
if (trc.addTransactionRec(trm)) {
// After successfully insert transaction record, update the
// recurring start date
RecurringModel rm = new RecurringModel();
rm.setRecurringID(recurID);
rm.setRecurringStartDate(date);
RecurringController rc = new RecurringController(mDbHelper.open());
if (rc.updateRecurringDate(rm)) {
mDbHelper.close();
}
}
}
}
Your Adapter should receive data that is ready to be displayed. getView is called every time a ListView item comes onto screen, so you want to keep your work here to under 16ms if you hope to maintain 60fps scrolling. Because of this, you should do all heavy work before it gets to the Adapter.
Since database data is often not display-ready, you would typically use a Loader to get the data, and turn it into a list of "items" that are Adapter-ready. This should happen in your Activity or Fragment, and you fill the Adapter in onLoadFinished. This often means creating a new POJO to represent the display data.
Best place to start is the Loader tutorial.
If you want to set a recurring task, you should use the AlarmManager, as you suspected. The AlarmManager would typically trigger a BroadcastManager, which in turn would spawn a Service to do the work.
Follow the AlarmManager tutorial for more details.
I have this code from where I can set a time and date from date picker and time picker at once:
private void dialoguetime() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialogue);
dialog.setCancelable(true);
dialog.setTitle("This is Dialog 1");
dialog.show();
TimePicker time_picker = (TimePicker) dialog
.findViewById(R.id.timePicker1);
hours = time_picker.getCurrentHour();
minute = time_picker.getCurrentMinute();
time_picker.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay,
int minutes) {
// TODO Auto-generated method stub
// Toast.makeText(CustomDialog.this,
// "hourOfDay = "+hourOfDay+"minute = "+minute , 1000).show();
hours = hourOfDay;
minute = minutes;
}
});
final DatePicker date_picker = (DatePicker) dialog
.findViewById(R.id.datePicker1);
Button btn = (Button) dialog.findViewById(R.id.button2);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
xDate = date_picker.getYear() + "-"+ (date_picker.getMonth() + 1) + "-"+ date_picker.getDayOfMonth() + " " + hours+ ":" + minute + ":00";
Toast.makeText(
getApplicationContext(),
xDate, Toast.LENGTH_LONG)
.show();
dialog.cancel();
}
}
);
}
From this I can get a string as a date format like this yyyy-mm-dd hh:mm:ss, now I want to give an alert (as alarm) to the user of that selected time. I have used alarm manager for this but it didn't allow me to select that date?
How can I do this?
If you look at the API for AlarmManager (http://developer.android.com/reference/android/app/AlarmManager.html) you can see that the method
set()
requires the following parameters:
public void set (int type, long triggerAtMillis, PendingIntent operation)
where
int type = One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC or RTC_WAKEUP.
long triggerAtMillis = time in milliseconds that the alarm should go off, using the appropriate clock (depending on the alarm type).
PendingIntent operation = Action to perform when the alarm goes off
So basicly what you should do, is to get the time between the selected date (DateFormat.parse() to parse the date-formated string to date) and the current date. Something like this:
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date parsedDate = format.parse(YOUR_PICKED_DATE_AS_STRING);
long alertTime = parsedDate.getTime() - now.getTime();
Intent someIntent = new Intent(getApplicationContext(), YourClass.class);
PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), 0, someIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.