SMS scheduling not sending sms - java

i am trying to send Message at a scheduled time in my app
here is my activty
public class Lenditem extends Activity {
Context mContext;
private int mHour;
private int mMin;
private int mYear;
private int mMonth;
private int mDay;
Button b1, b2, b3;
EditText et1, et2,et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Full screen code
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.lenditem);
b1 = (Button)findViewById(R.id.bselectcontactlenditem);
b3 = (Button)findViewById(R.id.bcancellenditem);
et1 = (EditText)findViewById(R.id.etdesclenditem);
et2 = (EditText)findViewById(R.id.etamountlenditem);
et3 = (EditText)findViewById(R.id.lietentercontact);
Button dateSet=(Button) findViewById(R.id.limyDatePickerButton);
Button timeSet=(Button) findViewById(R.id.limyTimePickerButton);
b3.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
boolean diditWork = true;
try {
String Desc1 = et1.getText().toString();
String Amt1 = et2.getText().toString();
Databaselentitem entry = new Databaselentitem(Lenditem.this);
entry.open();
entry.createEntry1(Desc1, Amt1);
entry.close();
} catch (Exception e) {
diditWork = false;
Toast.makeText(getApplicationContext(), "Something's Wrong.!!", Toast.LENGTH_LONG).show();
} finally {
if (diditWork) {
Toast.makeText(getApplicationContext(), "Reminder saved successfully.!!", Toast.LENGTH_LONG).show();
}
}
}
});
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// user BoD suggests using Intent.ACTION_PICK instead of
// .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
dateSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent localIntent1 = new Intent();
localIntent1.setClass(Lenditem.this.mContext, TimePickerActivity.class);
Lenditem.this.startActivityForResult(localIntent1, 0);
return;
/* DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
// TODO Auto-generated method stub
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
mMonth=monthofyear;
mYear=year;
mDay=dayofmonth;
Toast.makeText(getBaseContext(), "Date Set is :"+mDay+"/"+(mMonth+1)+"/"+mYear, Toast.LENGTH_SHORT).show();
}
};
// TODO Auto-generated method stub
new DatePickerDialog(Lenditem.this,d,Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH).show();
*/ }
});
timeSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view2, int hour, int min) {
// TODO Auto-generated method stub
mHour = hour;
mMin = min;
if (mHour >= 12)
mHour = mHour - 12;
Log.d("MYAPP", "hh:" + mHour + "\nmm:" + mMin);
Toast.makeText(getBaseContext(),
"Time Set is:" + mHour + ":" + mMin + ":00",
Toast.LENGTH_SHORT).show();
}
};
Calendar cal = Calendar.getInstance();
new TimePickerDialog(Lenditem.this, t, cal
.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
true).show();
}
});
Button saveAndClearBtn = (Button) findViewById(R.id.bSubmitlenditem);
saveAndClearBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Calendar myCal = Calendar.getInstance();
long timeToTrigger;
myCal.set(Calendar.YEAR, mYear);
myCal.set(Calendar.MONTH, mMonth);
myCal.set(Calendar.DAY_OF_MONTH, mDay);
myCal.set(Calendar.HOUR, mHour);
myCal.set(Calendar.MINUTE, mMin);
myCal.set(Calendar.SECOND, 0);
long setTime = myCal.getTimeInMillis();
if (setTime > System.currentTimeMillis()) {
timeToTrigger = setTime - System.currentTimeMillis();
EditText edt1 = (EditText) findViewById(R.id.bselectcontactlenditem);
EditText edt2 = (EditText) findViewById(R.id.litxtMessage);
String msg = edt2.getText().toString();
String telno = edt1.getText().toString();
int count = 0;
SQLiteDatabase db = openOrCreateDatabase("MYDBli",
MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS mySmsSchedulerli(SlNo VARCHAR,Number VARCHAR,Msg VARCHAR);");
String s = "INSERT INTO mySmsSchedulerli VALUES ('" + count
+ "','" + telno + "','" + msg + "');";
db.execSQL(s);
Log.d("MYREC", "Insertion of data successfull");
db.close();
edt1.setText("");
edt2.setText("");
Intent intent = new Intent();
intent.setClass(Lenditem.this, MyBroadcastRecieverli.class);
Bundle b = new Bundle();
b.putString("index", Integer.toString(count));
intent.putExtras(b);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
Lenditem.this, (int) Math.random(), intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + timeToTrigger,
pendingIntent);
count++;
Toast.makeText(
getBaseContext(),
"Sms Scheduled after:" + (timeToTrigger / (1000*60*60))+" Hours "+(timeToTrigger/(1000*60))+" Minutes "
+(timeToTrigger/1000)+ " sec.", Toast.LENGTH_SHORT).show();
Log.d("MYAPP", "Set Time:" + (setTime / 1000) + "Sec. \n"
+ "Cur time:" + System.currentTimeMillis() / 1000);
Log.d("MYAPP", "Time to trigger:" + (timeToTrigger / 1000)
+ "sec.");
} else {
Toast.makeText(getBaseContext(),
"Please Enter a valid time", Toast.LENGTH_SHORT)
.show();
Calendar calendar = Calendar.getInstance();
int h = calendar.get(Calendar.HOUR);
int m = calendar.get(Calendar.MINUTE);
Log.d("MYAPP", "cur HH:" + h + "\ncur MM:" + m);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
et3.setText(number);
}
}
this is broadcast class
public class MyBroadcastRecieverli extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int myCount;
String cnt=intent.getStringExtra("index");
if(cnt==null)
Log.d("MYAPP","Data not received");
Log.d("MYAPP", "Count:"+cnt);
myCount=Integer.parseInt(cnt);
Log.d("MYAPP","Broadcast receiver called...");
SQLiteDatabase db=arg0.openOrCreateDatabase("MYDB",Context.MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT Number, Msg FROM mySmsSchedulerli WHERE SlNo=="+myCount, null);
Log.d("MYAPP", "Cursor reference obtained...");
if(c!=null)
{
c.moveToFirst();
}
else
Log.d("MYAPP", "cursor is null");
/* c.moveToFirst();*/
String num=c.getString(c.getColumnIndex("Number"));
String myMsg=c.getString(c.getColumnIndex("Msg"));
Log.d("MYAPP", "number:"+num+"\nMsg:"+myMsg);
SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(num, null, myMsg, null, null);
Log.d("MYAPP", "Message Sent");
Toast.makeText(arg0, "Msg sent successfully", Toast.LENGTH_LONG).show();
String table="mySmsSchedulerli";
String whereClause = "SlNo = ?";
String[] whereArgs = new String[] { Integer.toString(Sms.count) };
db.delete(table, whereClause, whereArgs);
db.close();
Log.d("MYAPP", "Entry deleted..");
}
}
it is showing the toast that your msg will be send after xxxx seconds but not sending msg at scheduled time.
can anybody help me plzzz

Try to use Broadcast Receive first and then start a service.
Something like that:
create a function:
public static void setRecurringAlarm(Context context, Class<?> cls, int time, int minute) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getDefault());
updateTime.set(Calendar.HOUR_OF_DAY, time);
updateTime.set(Calendar.MINUTE, minute);
Intent alarm = new Intent(context, cls);
PendingIntent recurringAlarm = PendingIntent.getBroadcast(context, 654789, alarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringAlarm);
}
If you don't want to set a recurring alarm, just change setRepeating to set.
In your code, you need to call:
// to start the receiver at 9:00am
setRecurringAlarm(this, AlarmManagerReceiver.class, 9, 0);
So, you need to create the AlarmManagerReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmManagerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent alarmService = new Intent(context, AlarmManagerService.class);
context.startService(alarmService);
}
}
And now, you need the service:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
public class AlarmManagerService extends Service {
private Context context;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
context = this.getApplicationContext();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// Do what you need to do.
stopSelf();
}
}
In manifest:
<receiver android:name=".AlarmManagerReceiver" >
<intent-filter>
<action android:name=".AlarmManagerReceiver" />
</intent-filter>
</receiver>
<service
android:name=".AlarmManagerService"
android:enabled="true" >
<intent-filter>
<action android:name=".AlarmManagerService" />
</intent-filter>
</service>

Related

AlarmScheduler not working/setting off alarm in Android Studio

I am a bit new to android studio, and i am making an app where the user can select the date and time, and it will schedule and alarm to go off at that time. However, when i set the alarm it does not go off. Does anyone know where i went wrong? Or what it is i can change within my code.
CustomDialogClass
public Activity c;
public Dialog d;
public CircleButton CalendarBtn, TimeBtn;
public Button CancelBtn, ProceedBtn;
public TextView CalendarTxt, TimeTxt;
public EditText ReminderTxt;
//FOR CALENDAR
final Calendar myCalendar = Calendar.getInstance();
//FOR CALENDAR
private void updateLabel(TextView edittext) {
String myFormat = "dd/MM/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
edittext.setText(sdf.format(myCalendar.getTime()));
}
//FOR CALENDAR
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel(CalendarTxt);
}
};
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
CalendarTxt = (TextView) findViewById(R.id.CurrentDateSelect);
TimeTxt = (TextView) findViewById(R.id.CurrentTimeSelect);
CancelBtn = (Button) findViewById(R.id.CancelBtn);
ProceedBtn = (Button) findViewById(R.id.ProceedBtn);
CancelBtn.setOnClickListener(this);
ProceedBtn.setOnClickListener(this);
CalendarBtn = (CircleButton) findViewById(R.id.calendarBtn);
TimeBtn = (CircleButton) findViewById(R.id.timeBtn);
CalendarBtn.setOnClickListener(this);
TimeBtn.setOnClickListener(this);
ReminderTxt = (EditText) findViewById(R.id.ReminderTxt);
}
#Override
public void onClick(View v) {
//On click method for buttons
switch (v.getId()) {
case R.id.calendarBtn:
new DatePickerDialog(getContext(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
case R.id.CancelBtn:
dismiss();
break;
case R.id.timeBtn:
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String curTime = String.format("%02d:%02d", selectedHour, selectedMinute);
TimeTxt.setText(curTime);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
break;
case R.id.ProceedBtn:
String TimeVal = TimeTxt.getText().toString();
String DateVal = CalendarTxt.getText().toString();
String RemindVal = ReminderTxt.getText().toString();
if ((TimeVal + DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + DateVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else {
String FinalAlarmVal = DateVal + " " + " " + TimeVal;
String AlarmHour = TimeVal.substring(0, 2);
String AlarmMins = TimeVal.substring(3, 5);
String AlarmMonth = DateVal.substring(3, 5);
String AlarmDay = DateVal.substring(0, 2);
System.out.println("SEWISINGHVV- "+ Integer.parseInt(AlarmMonth));
AlarmScheduler.setReminder(getContext(), Integer.parseInt(AlarmHour), Integer.parseInt(AlarmMins), Integer.parseInt(AlarmDay), Integer.parseInt(AlarmMonth)); // Here mContext is Context of Activity. If you use this code in Activity then you can pass ActivityName.this and in Fragment you can do getActivity()
Intent AlarmName = new Intent(getContext(), AlarmReceiver.class);
AlarmName.putExtra("NameOfAlarm", RemindVal);
getContext().startService(AlarmName);
}
break;
default:
break;
}
//dismiss();
//Ends dialog when button is pressed
}
AlarmScheduler
public static final int DAILY_REMINDER_REQUEST_CODE = 100;
public static final String TAG = "AlarmScheduler";
public static void setReminder(Context context, int hour, int min, int day, int month) {
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.MONTH, month);
setcalendar.set(Calendar.DAY_OF_MONTH, day);
setcalendar.set(Calendar.HOUR_OF_DAY, hour);
setcalendar.set(Calendar.MINUTE, min);
setcalendar.set(Calendar.SECOND, 0);
setcalendar.set(Calendar.MILLISECOND, 0);
// cancel already scheduled reminders
cancelReminder(context, AlarmReceiver.class);
if (setcalendar.before(calendar))
setcalendar.add(Calendar.DATE, 1);
// Enable a receiver
ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
public static void cancelReminder(Context context, Class<?> cls) {
// Disable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
pendingIntent.cancel();
}
AlarmReceiver
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}

Triggering the set on click listener from options item selected

I want to trigger set on click listener from options item selected...
this is my on Options item selected code
//cancel event added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// ClipData.Item menu_cancel_event=(ClipData.Item) findViewById(R.id.menu_cancel_event);
// int Id = item.getItemId();
switch (item.getItemId()) {
case R.id.menu_cancel_event:
eventMO.setIsDelete(1);
del();
return true;
}
return super.onOptionsItemSelected(item);
}
private void del() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
final long Id = eventMO.getEventId();
db.delete("event", "Event_ID" + " = ?", new String[]{String.valueOf(Id)});
db.close();
}
this is my set on click listener
btn_create_button = (Button) findViewById(R.id.create_button);
btn_create_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(OccasionActivity.this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
UserMO userMO = dbHelper.getRingeeUserData(1);
eventMO.setText(custom_Text.getText().toString());
eventMO.setPlace(event_Place.getText().toString());
eventMO.setEndTime(end_Time);
eventMO.setStartTime(start_Time);
try {
//date and time format changed here
String eventDate = btn_Date.getText().toString();
DateFormat date = new SimpleDateFormat("dd-M-yyyy");
Date date1 = date.parse(eventDate);
DateFormat convertDate = new SimpleDateFormat(" yyyy-MM-dd hh:mm:ss");
eventDate = convertDate.format(date1);
eventMO.setEventDate(eventDate);
} catch (ParseException e) {
e.printStackTrace();
}
//eventMO.setEventDate(btn_Date.getText().toString());
eventMO.setRingeeUserId(userMO.getRingeeUserId());
//event update functionality added here
final Long hidden_Text2 = eventId2;
if ((eventMO.getText() != null) && (eventMO.getPlace() != null) && (eventMO.getEventDate() != null)) {
if (hidden_Text2 != null) {
eventMO.setEventId(hidden_Text2);
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.updateEvent(eventMO, context);
}
#Override
protected void onPostExecute(String arg0) {
prgDialog.dismiss();
Intent contactAct = new Intent(getApplicationContext(), UserDashBoardActivity.class);
// Clears History of Activity
contactAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contactAct);
}
}.execute(null, null, null);
Toast.makeText(getApplicationContext(), "Details updated successfully", Toast.LENGTH_LONG).show();
I want to trigger the set on click listener from on options item selected.....how to call this...please help me to find
My Code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_occasion, menu);
return true;
}
//cancel event added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// ClipData.Item menu_cancel_event=(ClipData.Item) findViewById(R.id.menu_cancel_event);
// int Id = item.getItemId();
switch (item.getItemId()) {
case R.id.menu_cancel_event:
eventMO.setIsDelete(1);
del();
//doOnCLickAndOnOptionSelected();
return true;
}
return super.onOptionsItemSelected(item);
}
private void del() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
final long Id = eventMO.getEventId();
db.delete("event", "Event_ID" + " = ?", new String[]{String.valueOf(Id)});
db.close();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_occasion);
context = getApplicationContext();
seekBar_startTime = (SeekBar) findViewById(R.id.seekBar1);
textView_startTime = (TextView) findViewById(R.id.textView1);
seekBar_endTime = (SeekBar) findViewById(R.id.seekBar2);
textView_endTime = (TextView) findViewById(R.id.textView2);
btn_Date = (Button) findViewById(R.id.event_date_button);
event_Place = (TextView) findViewById(R.id.Enter_Place);
custom_Text = (TextView) findViewById(R.id.Custom_Text);
btn_create_button = (Button) findViewById(R.id.create_button);
//menu_cancel_event=(button) findViewId(R.id.menu_cancel_event);
/*box1=(CheckBox) findViewById(R.id.check_box1);
box2=(CheckBox) findViewById(R.id.check_box2);
box3=(CheckBox) findViewById(R.id.check_box3);*/
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
dbHelper = new DatabaseHelper(context);
btn_Date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "Occasion Date");
}
});
seekBar_startTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
start_Time = String.valueOf(progresValue);
textView_startTime.setText("Event Start Time :" + progresValue);
}
});
seekBar_endTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
end_Time = String.valueOf(progresValue);
textView_endTime.setText("Event End Time :" + progresValue);
}
});
//eventid get from OccasionFragment here
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
Long eventId1 = bundle.getLong("EventID");
eventId2 = eventId1;
String eventName = bundle.getString("EventName");
custom_Text.setText(eventName);
String eventPlace = bundle.getString("EventPlace");
event_Place.setText(eventPlace);
String eventDate = bundle.getString("EventDate");
try {
//String eventDate = bundle.getString("EventDate");
//time string removed from date here
String result = eventDate.split(" ")[0];
DateFormat sourceDate = new SimpleDateFormat("yyyy-MM-dd");
// parse the date string into Date object
Date date = sourceDate.parse(result);
DateFormat convertDate = new SimpleDateFormat("dd-M-yyyy");
// format the date into another format
result = convertDate.format(date);
btn_Date.setText(result);
} catch (ParseException e) {
e.printStackTrace();
}
//Event Start Time and Event End Time string added before the time here
String eventStart = bundle.getString("EventStart");
textView_startTime.setText("Event Start Time :" + eventStart);
String eventEnd = bundle.getString("EventEnd");
textView_endTime.setText("Event End Time :" + eventEnd);
}
btn_create_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Instantiate Progress Dialog object
//doOnCLickAndOnOptionSelected();
// code
prgDialog = new ProgressDialog(OccasionActivity.this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
UserMO userMO = dbHelper.getRingeeUserData(1);
eventMO.setText(custom_Text.getText().toString());
eventMO.setPlace(event_Place.getText().toString());
eventMO.setEndTime(end_Time);
eventMO.setStartTime(start_Time);
try {
//date and time format changed here
String eventDate = btn_Date.getText().toString();
DateFormat date = new SimpleDateFormat("dd-M-yyyy");
Date date1 = date.parse(eventDate);
DateFormat convertDate = new SimpleDateFormat(" yyyy-MM-dd hh:mm:ss");
eventDate = convertDate.format(date1);
eventMO.setEventDate(eventDate);
} catch (ParseException e) {
e.printStackTrace();
}
//eventMO.setEventDate(btn_Date.getText().toString());
eventMO.setRingeeUserId(userMO.getRingeeUserId());
//event update functionality added here
final Long hidden_Text2 = eventId2;
if ((eventMO.getText() != null) && (eventMO.getPlace() != null) && (eventMO.getEventDate() != null)) {
if (hidden_Text2 != null) {
eventMO.setEventId(hidden_Text2);
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.updateEvent(eventMO, context);
}
#Override
protected void onPostExecute(String arg0) {
prgDialog.dismiss();
Intent contactAct = new Intent(getApplicationContext(), UserDashBoardActivity.class);
// Clears History of Activity
contactAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contactAct);
}
}.execute(null, null, null);
Toast.makeText(getApplicationContext(), "Details updated successfully", Toast.LENGTH_LONG).show();
} else {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.addEvent(eventMO, context);
}
#Override
protected void onPostExecute(String eventId) {
prgDialog.dismiss();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("eventId", eventId);
editor.commit();
Intent contactAct = new Intent(getApplicationContext(), ContactActivity.class);
// Clears History of Activity
contactAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contactAct);
}
}.execute(null, null, null);
Toast.makeText(getApplicationContext(), "Details added successfully", Toast.LENGTH_LONG).show();
}
} else {
prgDialog.dismiss();
Toast.makeText(context, "Please check Event custom text or Event place or Event date field", Toast.LENGTH_LONG).show();
}
}
});
}
#SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Date = new StringBuilder().append(year).append("-").append(month + 1).append("-").append(day).append(" ").toString();
btn_Date.setText(new StringBuilder().append(day).append("-").append(month + 1).append("-").append(year).append(" ").toString());
}
}
}
In general one does not call android listener callbacks programmatically. That will lead to all kinds of confusion later.
So if you have code you want to run in two listener callbacks you create a method within the same scope as both callbacks (the Activity or Fragment). And then in your call backs you call that method.
Example for Activity:
class MyActivity extends Activity {
private void doOnCLickAndOnOptionSelected() {
// code
}
#Override
protected void onCreate(...) {
...
btn_create_button = (Button) findViewById(R.id.create_button);
btn_create_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doOnCLickAndOnOptionSelected();
}
}
...
someMenu.setOnOpttionsItemSelectedListener(new OnOpttionsItemSelectedListener {
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// ClipData.Item menu_cancel_event=(ClipData.Item) findViewById(R.id.menu_cancel_event);
// int Id = item.getItemId();
switch (item.getItemId()) {
case R.id.menu_cancel_event:
eventMO.setIsDelete(1);
del();
doOnCLickAndOnOptionSelected();
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
}

How can I use NotificationListenerService to collect and display/delete notifications?

I've been trying to learn how to use notifications in Android by creating an application that creates, displays, and deletes notifications with button clicks (to clarify it will display the notifications in app). Now I can easily get my program to create notifications but when I try to delete the notification or display it I keep getting nulls and when I change the code up nothing. I found a few tutorials that helped me understand what I should be doing but the code they wrote did not work and I've hit a wall at this point. Here is my main activity:
public class MainActivity extends Activity {
private TextView txtView;
private NotificationReceiver nReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.textView);
nReceiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.testing.notify.NOTIFICATION");
registerReceiver(nReceiver,filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(nReceiver);
}
public void buttonClicked(View v){
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this);
ncomp.setSmallIcon(R.mipmap.ic_launcher);
ncomp.setContentTitle("Notify");
ncomp.setContentText("Notification Listener Service Example");
ncomp.setTicker("Notification Listener Service Example");
ncomp.setAutoCancel(true);
nManager.notify((int)System.currentTimeMillis(),ncomp.build());
}
else if(v.getId() == R.id.btnClearNotify){
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("command","clearall");
sendBroadcast(i);
}
else if(v.getId() == R.id.btnListNotify){
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("command","list");
sendBroadcast(i);
}
}
class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String temp = intent.getStringExtra("notification_event") + "n" + txtView.getText();
txtView.setText(temp);
}
}
And here is the code to my notification service class
public class NotificationService extends NotificationListenerService {
private String TAG = this.getClass().getSimpleName();
private NLServiceReceiver nlservicereceiver;
#Override
public void onCreate() {
super.onCreate();
nlservicereceiver = new NLServiceReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.testing.notify.NOTIFICATION");
registerReceiver(nlservicereceiver,filter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(nlservicereceiver);
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG,"********** onNotificationPosted");
Log.i(TAG,"ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText + "t" + sbn.getPackageName());
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("notification_event","onNotificationPosted :" + sbn.getPackageName() + "n");
sendBroadcast(i);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG,"********** onNotificationRemoved");
Log.i(TAG,"ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText +"t" + sbn.getPackageName());
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("notification_event","onNotificationRemoved :" + sbn.getPackageName() + "n");
sendBroadcast(i);
}
class NLServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getStringExtra("command").equals("clearall")){
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
}
else if(intent.getStringExtra("command").equals("list")){
Intent i1 = new Intent("com.testing.notify.NOTIFICATION");
i1.putExtra("notification_event","=====================");
sendBroadcast(i1);
int i=1;
for (StatusBarNotification sbn : NotificationService.this.getActiveNotifications()) {
Intent i2 = new Intent("com.testing.notify.NOTIFICATION");
i2.putExtra("notification_event",i +" " + sbn.getPackageName() + "n");
sendBroadcast(i2);
i++;
}
Intent i3 = new Intent("com.testing.notify.NOTIFICATION");
i3.putExtra("notification_event","===== Notification List ====");
sendBroadcast(i3);
}
}
}
I've been trying to figure this out for a while now so any help would be appreciated.

Passing data from Activity to Service

I have a problem while passing String to a Service from Activity. What I am trying to do is to pass different Strings each time I call Service. I use Intent (putExtra() method each time). The problem is that each time it shows the first String that I passed. Is there a way to implement that?
Here is my Activity, Broadcast Receiver, Service
public class MainActivity extends Activity implements View.OnClickListener{
private PendingIntent pendingIntent;
private EditText event;
private Button submit, date, time;
private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int myYear = 2014;
private int myMonth = 8;
private int myDay = 16;
private int myHour = 6;
private int myMinute = 30;
private List<String> events;
private List<Calendar> dateTimes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
event = (EditText)findViewById(R.id.event);
submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(this);
date = (Button)findViewById(R.id.date);
date.setOnClickListener(this);
time = (Button)findViewById(R.id.time);
time.setOnClickListener(this);
events = new ArrayList<String>();
dateTimes = new ArrayList<Calendar>();
//List<Calendar> events = new ArrayList<Calendar>();
}
#Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_DATE) {
DatePickerDialog datePickerDialog = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
return datePickerDialog;
}else {
TimePickerDialog timePickerDialog = new TimePickerDialog(this, myCallBack1, myHour, myMinute, true);
return timePickerDialog;
}
}
DatePickerDialog.OnDateSetListener myCallBack = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
myYear = year;
myMonth = month;
myDay = day;
}
};
TimePickerDialog.OnTimeSetListener myCallBack1 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
myHour = hour;
myMinute = minute;
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.date:
showDialog(DIALOG_DATE);
break;
case R.id.time:
showDialog(DIALOG_TIME);
break;
case R.id.submit:
String eventS = event.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, myMonth);
calendar.set(Calendar.YEAR, myYear);
calendar.set(Calendar.DAY_OF_MONTH, myDay);
calendar.set(Calendar.HOUR_OF_DAY, myHour);
calendar.set(Calendar.MINUTE, myMinute);
calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, BR.class);
myIntent.putExtra("event", eventS);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
event.setText("");
break;
}
}
public class BR extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MyService.class);
intent.getExtras().getString("event");
myIntent.putExtra("event", intent.getStringExtra("event"));
context.startService(myIntent);
Log.i("myLogs", "BR started");
}
}
public class MyService extends Service {
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
String event = intent.getExtras().getString("event");
Notification notification = new Notification(R.drawable.ic_launcher, "This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), event, event, pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
A service can't be stopped until it's finish. You have to wait that your current service finish to send other data. You can collect all your strings and send them all together or wait until your background service finish

.Resources$NotFoundException: String resource ID #0x3

In my application when i pass an intent into another class,so that user can send sms messages and that data get stored in database,..and when user click on select contact button he get the contacts checked on which he send the messages,firstly it worked fine but when i added update code on button click it start giving back the error..and logcat is showing me the error
03-24 11:45:10.811: E/AndroidRuntime(18748): android.content.res.Resources$NotFoundException: String resource ID #0x3
03-24 11:45:10.811: E/AndroidRuntime(18748): at android.widget.Toast.makeText(Toast.java:311)
smsSend.java
public class SmsSend extends Activity implements OnClickListener {
BroadcastReceiver smsSentReciver, smsSentDelivery;
static EditText edName, edMessage;
static int ResultCode = 12;
static ArrayList<String> sendlist = new ArrayList<String>();
Button btnSaveForLater, btnStart, btnExternal, btnSelect;
static TextView txt;
static StringBuilder conct = new StringBuilder();
static String contacts = "";
String delim = ";";
public static String Name;
TextView ed;
int i = 0;
String rowid, rowid1, value;
int j;
String Name1, msg, msg1;
String[] cellArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_camp);
btnExternal.setOnClickListener(this);
txt = (TextView) findViewById(R.id.textnum2);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
rowid = getIntent().getStringExtra("rowid");
value = getIntent().getStringExtra("key");
rowid1 = getIntent().getStringExtra("rowid1");
entryData();
edName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edName.setError(null);
}
});
edMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edMessage.setError(null);
}
});
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
txt.setError(null);
}
});
// Toast.makeText(getApplication(), contacts.toString(),
// Toast.LENGTH_LONG).show();
Name1 = edName.getText().toString();
msg1 = edMessage.getText().toString();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
edName.setText(null);
edMessage.setText(null);
conct.delete(0, conct.length());
contacts = null;
txt.setText("0");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(smsSentReciver);
unregisterReceiver(smsSentDelivery);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
smsSentReciver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "sms has been sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic Fail",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No Service",
Toast.LENGTH_SHORT).show();
default:
break;
}
}
};
smsSentDelivery = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Sms Delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "Sms not Delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
};
registerReceiver(smsSentReciver, new IntentFilter("SMS_SENT"));
registerReceiver(smsSentDelivery, new IntentFilter("SMS_DELIVERED"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatabaseHelp entry = new DatabaseHelp(SmsSend.this);
entry.open();
switch (v.getId()) {
case R.id.btnSelect:
Intent a = new Intent(SmsSend.this, MainActivity.class);
startActivityForResult(a,ResultCode);
break;
case R.id.btnExternal:
Intent file = new Intent(SmsSend.this, File_Selecter.class);
startActivity(file);
break;
case R.id.btnStart:
Log.i("SMS", "Sendlist Size: " + sendlist.size());
if (edName.getText().toString().length() == 0
|| edName.getText().toString().length() == 0
|| txt.getText().equals("0")) {
edName.setError("First name is required!");
edMessage.setError("Message is required!");
txt.setError("Contacts required!");
} else {
/* if (rowid1 != null
&& edName.getText().toString().length() != 0
&& edName.getText().toString().length() != 0
&& txt.getText().equals("0")
&& edName.getText().toString() == value) {
Toast.makeText(getApplication(), "update", Toast.LENGTH_LONG).show();
SmsManager smsManager = SmsManager.getDefault();
PendingIntent piSend = PendingIntent.getBroadcast(this,
0, new Intent("SMS_SENT"), 0);
PendingIntent piDelivered = PendingIntent.getBroadcast(
this, 0, new Intent("SMS_DELIVERED"), 0);
Log.i("SMS", "contacts: " + contacts);
contacts = conct.toString();
cellArray = contacts.split(";");
for (int a1 = 0; a1 < cellArray.length; a1++) {
smsManager.sendTextMessage(cellArray[i].toString(),
null, msg1, piSend, piDelivered);
}
long ltt = Long.parseLong(rowid1);
entry.updateEntry(ltt, Name1, msg1, contacts);
Toast.makeText(getApplication(), "updated",
Toast.LENGTH_LONG).show();
} else {*/
boolean diditwork1 = true;
try {
Toast.makeText(getApplication(), "insert", Toast.LENGTH_LONG).show();
SmsManager smsManager = SmsManager.getDefault();
PendingIntent piSend = PendingIntent.getBroadcast(this,
0, new Intent("SMS_SENT"), 0);
PendingIntent piDelivered = PendingIntent.getBroadcast(
this, 0, new Intent("SMS_DELIVERED"), 0);
Log.i("SMS", "contacts: " + contacts);
contacts = conct.toString();
//Toast.makeText(getApplication(), contacts.toString(), Toast.LENGTH_LONG).show();
cellArray = contacts.split(";");
Toast.makeText(getApplication(), cellArray.length, Toast.LENGTH_LONG).show();
for (int a1 = 0; a1 < cellArray.length; a1++) {
smsManager.sendTextMessage(cellArray[i].toString(),
null, msg1, piSend, piDelivered);
}
DatabaseHelp entry1 = new DatabaseHelp(SmsSend.this);
entry1.open();
entry1.entryCreate(Name1, msg1, contacts);
entry1.close();
}
catch (Exception e) {
diditwork1 = false;
String erroe = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(erroe);
d.setContentView(tv);
d.show();
} finally {
if (diditwork1) {
Dialog d = new Dialog(this);
d.setTitle("Heck Yeah!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
}
edName.setText("");
edMessage.setText("");
txt.setText("0");
break;
}
}
//}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
sendlist = data.getStringArrayListExtra("name");
Toast.makeText(getApplication(), sendlist.size(), Toast.LENGTH_LONG).show();
if (sendlist != null) {
for (int i = 0; i < sendlist.size(); i++) {
conct.append(sendlist.get(i).toString());
conct.append(delim);
//Toast.makeText(getApplication(), conct.toString(),Toast.LENGTH_LONG).show();
}
}
}
i = sendlist.size();
txt.setText(Integer.toString(i));
if (resultCode == RESULT_CANCELED) {
}
}
}
}
MainaActiivty.java
public class MainActivity extends Activity implements OnItemClickListener {
ArrayList<String> name1 = new ArrayList<String>();
static ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
MyAdapter ma;
Button send;
String[] cellArray = null;
int[] str;
int v = 0;
String contacts;
static int check1;
ListView lv;
int index;
int top;
StringBuilder b = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.get);
// TextView txt = (TextView) findViewById(R.id.textView1);
getAllCallLogs(this.getContentResolver());
lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// b = SmsSend.contacts;
contacts = SmsSend.contacts;
if (SmsSend.contacts != null) {
cellArray = contacts.split(";");
// Toast.makeText(getApplication(),contacts.toString(),
// Toast.LENGTH_LONG).show();
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < phno1.size(); j++) {
if (cellArray[i].equals(phno1.get(j))) {
Toast.makeText(getApplication(),cellArray[i].toString(),
Toast.LENGTH_LONG).show();
ma.setChecked(j, true);
}
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.contact_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.addPage:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
phno0.add(phno1.get(i).toString());
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ name1.get(i).toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name", phno0);
setResult(RESULT_OK, returnIntent);
Toast.makeText(getApplication(), phno0.size(), Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
System.out.println(phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Save ListView state
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(name1.get(position));
tv1.setText(phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
try this one:
Toast.makeText(getApplication(), sendlist.size().tostring(), Toast.LENGTH_LONG).show();
or else:
Toast.makeText(getApplication(), sendlist.size().toString()+"", Toast.LENGTH_LONG).show();
bcoz it will allow second params in a string.. and also use getApplication instead of this one example :
Toast.makeText(getApplicationContext(),
"Error during request: " + e.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
Thank you,,
Toast.makeText(getApplication(), sendlist.size(), Toast.LENGTH_LONG).show();
sendlist.size() returns an int and passing an int to Toast.makeText() uses the overload that attempts to load a string resource with the given id.
Replace with e.g. Integer.toString(sendlist.size()) to toast the integer value.
You have the same issue in multiple places. Check all your Toast.makeText() calls.
The second param to Toast must be a String type.
Concatenate second param like this:
Toast.makeText(getApplication(), "" + sendlist.size(), Toast.LENGTH_LONG).show();
try this one
Toast.makeText(ExploreMatchDetail.this,sendlist.size()+"",Toast.LENGTH_SHORT).show();

Categories