Attempt to invoke virtual method when displaying TOAST? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
when you click a button in my activity it starts/displays a DatePickerDialog. When the user selects a date and clicks "ok" i want to run an AsyncTask in the original class (the activity where the button was clicked). Everything works but i want to display to the user a TOAST when the AsyncTask is finished but it keep on getting an error when doing so.
Heres my code:
Button method in the BuyerHomePage.java
public void MeetingCreator(){
CalenderImageButton = (ImageButton)findViewById(R.id.CalenderImageButton);
CalenderImageButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
}
);
}
DatePickerFragment.java code
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static String formattedDate;
#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);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = sdf.format(c.getTime());
BuyerHomePage Meeting = new BuyerHomePage();
Meeting.new MeetingSender().execute();
}
}
BuyerHomePage.java (post method in the AsyncTask)
#Override
protected void onPostExecute (String result){
if (result.equals("email sent")) {
//This is where i get the error
Toast.makeText(BuyerHomePage.this, "Email sent!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(BuyerHomePage.this, "Can't send email", Toast.LENGTH_LONG).show();
}
}
Error Logs:
04-23 02:25:31.631 22071-22071/com.wilsapp.wilsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wilsapp.wilsapp, PID: 22071
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.widget.Toast.<init>(Toast.java:102)
at android.widget.Toast.makeText(Toast.java:259)
at com.wilsapp.wilsapp.BuyerHomePage$MeetingSender.onPostExecute(BuyerHomePage.java:930)
at com.wilsapp.wilsapp.BuyerHomePage$MeetingSender.onPostExecute(BuyerHomePage.java:836)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
if there's any confusion or i need to explain anything please comment! Thank you!

Try this.
Toast.makeText(getApplicationContext(), "Email sent!", Toast.LENGTH_LONG).show();

Related

Invalid Hijrah Day of Month : 31

I tried to create a simple activity with a button and a textview that showing the date. The button should show the HijriDatePicker dialog when clicked. I tried to make it using ummalqura-calendar and by the dialog, i tried use the HijriDatePicker to create the dialog.
However, after many attempts, it doesn't work. Sometimes the activity will stop when I click the button, and sometimes it just crash. I tried already for many fail attempts.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 13658
com.github.msarhan.ummalqura.calendar.DateTimeException: Invalid Hijrah day of month: 31
at com.github.msarhan.ummalqura.calendar.HijrahChronology.getEpochDay(HijrahChronology.java:255)
at com.github.msarhan.ummalqura.calendar.HijrahChronology.toGregorian(HijrahChronology.java:697)
at com.github.msarhan.ummalqura.calendar.UmmalquraCalendar.set(UmmalquraCalendar.java:259)
at net.alhazmy13.hijridatepicker.date.hijri.HijriDatePickerDialog.getEndDate(HijriDatePickerDialog.java:1028)
at net.alhazmy13.hijridatepicker.date.hijri.MonthAdapter.getCount(MonthAdapter.java:146)
at android.widget.ListView.setAdapter(ListView.java:493)
at net.alhazmy13.hijridatepicker.date.hijri.DayPickerView.refreshAdapter(DayPickerView.java:142)
at net.alhazmy13.hijridatepicker.date.hijri.DayPickerView.setController(DayPickerView.java:114)
at net.alhazmy13.hijridatepicker.date.hijri.DayPickerView.<init>(DayPickerView.java:105)
at net.alhazmy13.hijridatepicker.date.hijri.SimpleDayPickerView.<init>(SimpleDayPickerView.java:32)
at net.alhazmy13.hijridatepicker.date.hijri.HijriDatePickerDialog.onCreateView(HijriDatePickerDialog.java:340)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
and my main activity java
public class MainActivity extends AppCompatActivity implements HijriDatePickerDialog.OnDateSetListener{
TextView tvDate;
TextView etDate;
HijriDatePickerDialog.OnDateSetListener setListener;
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDate = findViewById(R.id.tv_date);
etDate = findViewById(R.id.et_date);
tvDate.setOnClickListener(v -> {
UmmalquraCalendar now = new UmmalquraCalendar();
HijriDatePickerDialog dpd = HijriDatePickerDialog.newInstance(
MainActivity.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setMinDate(new UmmalquraCalendar(1440,0,1));
dpd.show(getSupportFragmentManager(), "Datepickerdialog");
});
}
#Override
public void onResume() {
super.onResume();
assert getFragmentManager() != null;
HijriDatePickerDialog dpd = (HijriDatePickerDialog) getSupportFragmentManager().findFragmentByTag("Datepickerdialog");
if (dpd != null) dpd.setOnDateSetListener(this);
}
#Override
public void onDateSet(HijriDatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = "You picked the following date: " + dayOfMonth + "/" + (++monthOfYear) + "/" + year;
System.out.println(date);
etDate.setText(date);
}
}
This problem seems to be a known bug in the msarhan-library. There was also a meanwhile closed issue on its related website. It indicates that a fix has been applied in the newest version.
So I suggest you to update your marhan library to version v2.0.2 which might solve your problem.
Update:
When looking at the date-picker-library you use we can see that it still uses the version v2.0.1. Either you wait until the author of the date-picker-library fixes the dependency or you build your own version of the date-picker-library.
If you use koltin this method will fix your issue
fun selectDateOfBirthHijri(context: Context, editText: EditText, childFragmentManager: FragmentManager) {
val now = Calendar.getInstance()
val dateOfBirthClickListener =
HijriDatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
now.set(Calendar.YEAR, year)
now.set(Calendar.MONTH, month)
now.set(Calendar.DAY_OF_MONTH, dayOfMonth)
editText.setText(
Formatter.format(
now.time.toString(),
Formatter.EEE_MMM_DD_HH_MM_SS_ZZZ_YYYY,
Formatter.DD_MM_YYYY
)
)
}
val ummAlquraCalendar = UmmalquraCalendar()
val b = HijriDatePickerDialog.newInstance(
dateOfBirthClickListener,
ummAlquraCalendar.get(UmmalquraCalendar.YEAR),
ummAlquraCalendar.get(UmmalquraCalendar.MONTH),
ummAlquraCalendar.get(UmmalquraCalendar.DAY_OF_MONTH)
)
b.maxDate = UmmalquraCalendar(ummAlquraCalendar.get(Calendar.YEAR),
ummAlquraCalendar.get(Calendar.MONTH),
ummAlquraCalendar.get(Calendar.DAY_OF_MONTH))
b.setTitle(context.getString(R.string.hint_date_of_birth))
b.show(childFragmentManager, "HijriDatePickerDialog")
}

I want to use a statement if value is X than Show popup "Time UP Please Order Tomorrow"

I want to add a function in my main activity that the application will fetch device time. If time is More than 2:00 PM in Device time or Less than 08:00 AM in Device time. A Popup will show after splash screen "Sorry Time UP, Please Order Tomorrow from 08:00 AM to 02:00 PM". And an Ok button to exit the application.
After Answer I Updated my Splash Activity. And nothing happened.
`public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// **************** ORDER SLOT ******************* //
Calendar finalTime = Calendar.getInstance();
Calendar mCalendarOpeningTime = Calendar.getInstance();
mCalendarOpeningTime.set(Calendar.HOUR, 10);
mCalendarOpeningTime.set(Calendar.MINUTE, 59);
mCalendarOpeningTime.set(Calendar.AM_PM, Calendar.AM);
Calendar mCalendarClosingTime = Calendar.getInstance();
mCalendarClosingTime = Calendar.getInstance();
mCalendarClosingTime.set(Calendar.HOUR, 11);
mCalendarClosingTime.set(Calendar.MINUTE, 00);
mCalendarClosingTime.set(Calendar.AM_PM, Calendar.AM);
if (finalTime.after(mCalendarOpeningTime)&&finalTime.before(mCalendarClosingTime)){
// show the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(SplashScreen.this);
builder.setTitle(R.string.app_name);
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("Order Full, Please Order Tomorrow before 02:00PM")
.setCancelable(false)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
}
Well, there are too many ways to do this. If you want to get time from the internet you can use TrueTime. As per your request, You can use Date instances :
private void setOpeningAndClosingTimes() {
//current time
Calendar finalTime = Calendar.getInstance();
Calendar mCalendarOpeningTime = Calendar.getInstance();
mCalendarOpeningTime.set(Calendar.HOUR, 8);
mCalendarOpeningTime.set(Calendar.MINUTE, 0);
mCalendarOpeningTime.set(Calendar.AM_PM, Calendar.AM);
Calendar mCalendarClosingTime = Calendar.getInstance();
mCalendarClosingTime = Calendar.getInstance();
mCalendarClosingTime.set(Calendar.HOUR, 2);
mCalendarClosingTime.set(Calendar.MINUTE, 00);
mCalendarClosingTime.set(Calendar.AM_PM, Calendar.PM);
if (finalTime.after(mCalendarOpeningTime)&&finalTime.before(mCalendarClosingTime)){
// show the dialog
Toast.makeText(this,"Time is 8Am to 2PM",Toast.LENGTH_LONG).show();
}else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.app_name);
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("Order Full, Please Order Tomorrow before 02:00PM")
.setCancelable(false)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.show();
}
Now call this method in onCreate() or onStart() so that the values are assigned to the respective "times" before you start using them:

Setting Alarm for Multiple times in Android

In my app I want alarms for several times which will be set by the user.
But if I set the alarm for a different date and time it only responds on the last set-up time.
Such as if I set alarm for date 20-01-2017 time 10.10 am,
20-01-2017 time 10.20 am, 20-01-2017 time 10.30 am,
and so on it only gives the alarm for last selected date & Time.
But doesn't give alarm at 20-01-2017 time 10.10 am, 20-01-2017 time 10.20 am, or other selected times.
How can I get alarm at all selected times?
Here is my code:
public void setDate(View view) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void setTime(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void setAlarm(View view) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, alarmHour);
calSet.set(Calendar.MINUTE, alarmMin);
calSet.set(Calendar.DAY_OF_MONTH, alarmDay);
calSet.set(Calendar.YEAR, alarmYear);
calSet.set(Calendar.MONTH, alarmMonth);
setAlarmN(calSet);
}
private void setAlarmN(Calendar targetCal) {
makeText(this, "Alarm is set at" + targetCal.getTime(),
LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
pendingIntent);
}
//date picker fragment
public static 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) {
// Do something with the date chosen by the user
alarmDay = day;
alarmYear = year;
alarmMonth = month;
}
}
//Time picker fragment
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
alarmHour = hourOfDay;
alarmMin = minute;
}
}
Problem is in your void setAlarmN() method. You can't generate alarm notification with the same id. That should mean that notification before gets cancel and override. Try to set unique id for RQS_1 each time PendingIntent.getBroadcast() gets called. Probably you have to declare private variable and increment it.

DatePicker and TimePicker crash when I press the Set button

I am making a messenger that has date and time pickers pop up when I click the button. When I press the Set button to display them, the app crashes. My code is:
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
yearSet = year;
monthSet = monthOfYear + 1;
daySet = dayOfMonth;
btnDate.setText(yearSet + monthSet + daySet);
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
hourSet = hour;
minuteSet = minute;
btnTime.setText(hourSet + minuteSet);
}
};
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x7f4
at android.content.res.Resources.getText(Resources.java:1068)
at android.widget.TextView.setText(TextView.java:4546)
at devncode.kemo.testApp.SendMessageActivity$3.onDateSet(SendMessageActivity.java:95)
at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:199)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java:154)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:185)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Your problem is that you are setting text of different items as integers.. For example btn.setText(int); where it should be a string btn.setText(String);
So to fix it, wherever you have something like
btnTime.setText(hourSet + minuteSet);
change it to
btnTime.setText(hourSet + minuteSet + "");
Adding the + "" will cast it as a String and not give an error.

Displaying the current-time

I'm currently trying to display the current time to my custom ListView but I keep getting a NullPointerException and was wondering what I was doing wrong since I was already adding to the array and grabbing its value.
The custom Adapter and setter/getters are here: 1 2
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
boss_title = getResources().getStringArray(R.array.boss_array);
bossTime = (TextView) findViewById(R.id.boss_time);
adapter = new BossAdapter(getApplicationContext(), R.layout.boss_layout);
listView.setAdapter(adapter);
int i = 0;
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("HH-mm-ss");
String formattedTime = df.format(c.getTime());
String [] boss_time_array = new String[6];
for(int i =0; i < 6; i++){
boss_time_array[i] = formattedTime;
}
boss_time = boss_time_array;
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
for (String boss : boss_title) {
Boss bossObject = new Boss(boss_icon[i], boss, boss_time[i]);
adapter.add(bossObject);
i++;
}
}
Logcat
8541-8541/baegmon.com.bosstimer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: baegmon.com.bosstimer, PID: 8541
java.lang.RuntimeException: Unable to start activity ComponentInfo{baegmon.com.bosstimer/baegmon.com.bosstimer.MainActivity}: java.lang.NullPointerException: Attempt to read from null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to read from null array
at baegmon.com.bosstimer.MainActivity.onCreate(MainActivity.java:67)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
How do I modify it so that it doesn't return a null-pointer error and returns the correct time to my list view?
Handler handler=new Handler();
handler.post(new Runnable(){
#Override
public void run() {
// upadte textView here
handler.postDelayed(this,500); // set time here to refresh textView
}
});
Just pass your textview in the hanlder method. That works fine.
try to implement this code from the below site.
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
Hope any queries or concerns, do let me know.
You get the NullPointerException because the Thread isn't finished when you create the Adapter.
After the Thread was started you are immediately reading the results from boss_title.
This not possible because you have to wait for it to be finished.
You should use an AsyncTask for this and create your Adapter inside the onPostExecute (http://developer.android.com/reference/android/os/AsyncTask.html).
Also the SimpleDateFormat class is not thread-safe:
public static Date dateToString(Date date, final String format, final Locale locale)
ThreadLocal<SimpleDateFormat> formater = new ThreadLocal<SimpleDateFormat>() {
#Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(format, locale);
}
};
return formater.get().format(string);
}

Categories

Resources