I'm trying to create calendar in one of my fragments, yet I can't figure out how can I call the calendar class into the onCreate(); function in fragmentTwo.java.
I have tried this, but I keep getting error:
FATAL ERROR Attempt to invoke virtual method
'android.view.Window$Callback android.view.Window.getCallback()' on a
null object reference
.
fragmentTwo.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Calendar calendar = new Calendar();
calendar.setContentView(R.layout.calendar);
}
Calendar.java:
public class Calendar extends AppCompatActivity {
CalendarView calendarView;
TextView dateDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
calendarView = (CalendarView) findViewById(R.id.calendarView);
dateDisplay = (TextView) findViewById(R.id.date_display);
dateDisplay.setText("Date: ");
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {
dateDisplay.setText("Date: " + i2 + " / " + i1 + " / " + i);
Toast.makeText(getApplicationContext(), "Selected Date:\n" + "Day = " + i2 + "\n" + "Month = " + i1 + "\n" + "Year = " + i, Toast.LENGTH_LONG).show();
}
});
}
}
How can I apply the Calendar class in my fragmentTwo onCreate() function?
The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
So basically you can't do view stuff inside onCreate() .
So you need to add those two lines
Calendar calendar = new Calendar();
calendar.setContentView(R.layout.calendar);
in onCreateView()
Link to the docs
Related
How can I filter SMS INBOX by date?
I have a function to load SMS and save it to an SQL Database but it seems to be slow because it loads every SMS that the device has. I want to load only all SMS from a specific date with datepicker.
public class StartPage extends AppCompatActivity {
TextInputEditText selectDate;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_page);
selectDate = findViewById(R.id.dateText);
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: MM/dd/yyy: " + month + "-" + day + "-" + year);
String fm=""+month;
String fd=""+day;
if(month<10){
fm ="0"+month;
}
if (day<10){
fd="0"+day;
}
String date = fm + "-" + fd + "-" + year;
selectDate.setText(date);
loadMsg();
}
};
}
public void loadMsg(){
ContentResolver cr = getContentResolver();
Cursor c = cr.query(Uri.parse("content://sms/inbox"),
null, null, null, null); /*<--this is where I want to filter by date(EX: I want to load only SMS corresponding to what the user have selected on the date picker)*/
int messageIndex = c.getColumnIndex("body");
int dateStampIndex = c.getColumnIndex("date");
while(c.moveToNext()){
if(c.getString(dateStampIndex).equals(selectDate.getText().toString()))/*<-this is what I did. Obviously, this is wrong because it will load all the SMS because there's no filter in the cursor.*/{
Toast.makeText(this, "Message loaded: " + c.getString(messageIndex), LENGTH_SHORT).show();
}
}
}
}
I have a Simple Date Picker App in Android and it's working fine when I click on First TextView.
How Can I activate the same Calendar with a second TextView. One TextView shows the Long Date and other shows the Short Date
public class MainActivity extends AppCompatActivity {
private TextView mDisplayLongDate;
TextView mDisplayShortDate;
CheckBox checkBoxVisibility;
private DatePickerDialog.OnDateSetListener mDateSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDisplayLongDate = findViewById(R.id.tvLDate);
mDisplayShortDate = findViewById(R.id.tvSDate);
//View checkBox = findViewById(R.id.checkBox);
checkBoxVisibility = findViewById(R.id.checkBox_visibility);
//boolean isChecked = checkBoxVisibility.isClickable();
boolean isChecked = checkBoxVisibility.isChecked();
updateTextVisibility(isChecked);
checkBoxVisibility.setOnCheckedChangeListener((buttonView, isChecked1) -> {
//Step 05 - Updating UI according to the currently changed state
updateTextVisibility(isChecked1);
});
mDisplayLongDate.setOnClickListener(view -> {
Calendar cal = Calendar.getInstance();
With a CheckBox, the TextView Shows Long Date and Short Date.
I cannot click on the short date to edit the Calendar. How to activate the Calendar in both situation.
String dateLong = monthStr + "/" + day + "/" + year;
String dateShort = monthStr + "/" + day;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
};
}
private void updateTextVisibility(boolean isChecked) // When checking the trigger (checkbox)
{
if (isChecked)
{
mDisplayShortDate.setVisibility(View.VISIBLE);
mDisplayLongDate.setVisibility(View.GONE);
}
else
{
mDisplayShortDate.setVisibility(View.GONE);
mDisplayLongDate.setVisibility(View.VISIBLE);
}
You can use this type of method and call it where you need .
private void getCal() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int monthStr = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dPDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog,
new DatePickerDialog.OnDateSetListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
public void onDateSet(DatePicker datepicker, int selectedY, int selectedM, int selectedD) {
String[] months = new DateFormatSymbols(Locale.ENGLISH).getMonths();
String dateLong = months[selectedM] + "/" + selectedD + "/" + selectedY;
String dateShort = months[selectedM] + "/" + selectedD;
// String dateLong = (selectedM + 1) + "/" + selectedD + "/" + selectedY;
//String dateShort = (selectedM + 1) + "/" + selectedD;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
}
}, year, monthStr, day);
dPDialog.show();
}
Example class-
public class MainActivity extends AppCompatActivity {
private TextView mDisplayLongDate;
TextView mDisplayShortDate;
CheckBox checkBoxVisibility;
private DatePickerDialog.OnDateSetListener mDateSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDisplayLongDate = findViewById(R.id.tvLDate);
mDisplayShortDate = findViewById(R.id.tvSDate);
mDisplayLongDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCal();
}
});
mDisplayShortDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCal();
}
});
}
private void getCal() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int monthStr = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dPDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog,
new DatePickerDialog.OnDateSetListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
public void onDateSet(DatePicker datepicker, int selectedY, int selectedM, int selectedD) {
String[] months = new DateFormatSymbols(Locale.ENGLISH).getMonths();
String dateLong = months[selectedM] + "/" + selectedD + "/" + selectedY;
String dateShort = months[selectedM] + "/" + selectedD;
// String dateLong = (selectedM + 1) + "/" + selectedD + "/" + selectedY;
//String dateShort = (selectedM + 1) + "/" + selectedD;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
}
}, year, monthStr, day);
dPDialog.show();
}
}
I have a variable of its kind int.
I've allocated value in it through another value from within another object ,but there's a problem.
The problem is happening when i press the button 3
after i set the required time values for each object.
I'll show you the wrong message ,and the code used.
I want to change the code to work properly.
// Logcat:
java.lang.NullPointerException: Attempt to read from field 'int com.ahmedco.testcode2.TimePickerDialog.hourOfDay' on a null object reference
at com.ahmedco.testcode2.MainActivity$3.onClick(MainActivity.java:65)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
// class 1
public class MainActivity extends AppCompatActivity {
Button b1, b2, b3;
DialogFragment timePickerDialog1, timePickerDialog2;
int hourTimer1, hourTimer2, minuteTimer1, minuteTimer2;
String time1Format, time2Format, AM_PMTimer1, AM_PMTimer2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePickerDialog1 = new TimePickerDialog(1);
timePickerDialog1.show(getSupportFragmentManager(), "timePicker");
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePickerDialog2 = new TimePickerDialog(2);
timePickerDialog2.show(getSupportFragmentManager(), "timePicker");
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hourTimer1 = ((TimePickerDialog) timePickerDialog1).hourOfDay;
hourTimer2 = ((TimePickerDialog) timePickerDialog2).hourOfDay;
minuteTimer1 = ((TimePickerDialog) timePickerDialog1).minute;
minuteTimer2 = ((TimePickerDialog) timePickerDialog2).minute;
AM_PMTimer1 = ((TimePickerDialog) timePickerDialog1).AM_PM;
AM_PMTimer2 = ((TimePickerDialog) timePickerDialog2).AM_PM;
//Log.i("trace1","test "+((TimePickerDialog) timePickerDialog1).hourOfDay);
//Log.i("trace2","test "+((TimePickerDialog) timePickerDialog2).hourOfDay);
time1Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer1;
time2Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer2;
Log.i("time1Format", "" + time1Format);
Log.i("time2Format", "" + time2Format);
}
});
}
}
// class 2
public class TimePickerDialog extends DialogFragment implements android.app.TimePickerDialog.OnTimeSetListener {
public String AM_PM = "";
public int hourOfDay = 0;
public int minute = 0;
public TimePickerDialog(int id) {
// currentEditText = id;
}
#Override
public Dialog onCreateDialog(#Nullable 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);
return new android.app.TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay_, int minute_) {
// "11:06 PM"
if (hourOfDay_ > 12) {
AM_PM = "PM";
hourOfDay_ = hourOfDay_ - 12;
} else {
AM_PM = "AM";
}
///Log.i("hourOfDay",""+hourOfDay_+":"+hourOfDay_+" "+AM_PM);
hourOfDay = hourOfDay_;
minute = minute_;
}
}
You having problem inside b3.setOnClickListener because you are not initialized object so you have to initialize objects timePickerDialog1 and timePickerDialog2 globally.
DialogFragment timePickerDialog1=new TimePickerDialog(1), timePickerDialog2=new TimePickerDialog(2);
or
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(timePickerDialog1==null)
timePickerDialog1=new TimePickerDialog(1);
if(timePickerDialog2==null)
timePickerDialog1=new TimePickerDialog(2);
hourTimer1 = ((TimePickerDialog) timePickerDialog1).hourOfDay;
hourTimer2 = ((TimePickerDialog) timePickerDialog2).hourOfDay;
minuteTimer1 = ((TimePickerDialog) timePickerDialog1).minute;
minuteTimer2 = ((TimePickerDialog) timePickerDialog2).minute;
AM_PMTimer1 = ((TimePickerDialog) timePickerDialog1).AM_PM;
AM_PMTimer2 = ((TimePickerDialog) timePickerDialog2).AM_PM;
//Log.i("trace1","test "+((TimePickerDialog) timePickerDialog1).hourOfDay);
//Log.i("trace2","test "+((TimePickerDialog) timePickerDialog2).hourOfDay);
time1Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer1;
time2Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer2;
Log.i("time1Format", "" + time1Format);
Log.i("time2Format", "" + time2Format);
}
});
You declare your TimePickerDialog in the beginning (DialogFragment timePickerDialog1, timePickerDialog2;)
But only initialise it when Button 1 or 2 are pressed respectively
timePickerDialog2 = new TimePickerDialog(2);
Therefore timePickerDialog2is nulluntil Button 2 was pressed.
When trying to call .hourOfDay in Button 3 when timePickerDialog2has not been initialised yet, you get a NullPointerException. You can't call methods on an object that is null.
In one class I set the ID to my Warranty class. I added my full code so you can see where it goes wrong. I declare the class so I can call it. Set the ID on the setter and finally I retrieve it on the other class with the getter.
public class HomeActivity extends AppCompatActivity {`
DatabaseHelper db = new DatabaseHelper(this);
LinearLayout buttonViewWarrantys;
Warranty wr = new Warranty();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Display display = getWindowManager().getDefaultDisplay();
int width_display = display.getWidth();
width_display = (width_display/10) * 8;
Button addWarBtn = findViewById(R.id.add_warranty);
buttonViewWarrantys = findViewById(R.id.show_warratys);
addWarBtn.getLayoutParams().width = width_display;
addWarBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent inputScreen = new Intent(HomeActivity.this, InputScreen.class);
startActivity(inputScreen);
}
});
updateWarrantys();
}
#Override
public void onResume() {
super.onResume();
updateWarrantys();
}
void updateWarrantys(){
List<Warranty> warrantys = db.getAllContacts();
for (Warranty cn : warrantys) {
final String ID = Integer.toString(cn.getID());
String buttonName = ID + "_" + cn.getName();
String buttonText = "Name: " + cn.getName() + '\n' + " Bought on: " + cn.getStartDate() + '\n' + " Warranty stops on: " + cn.getEndDate();
Button buttons = new Button(this);
buttons.setTag(buttonName);
buttons.setText(buttonText);
buttons.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
final String warranty_name = cn.getName();
final String start_date = cn.getStartDate();
final String end_date = cn.getEndDate();
final String img_path = cn.getImgFilePath();
buttons.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println(ID);
wr.setID(Integer.parseInt(ID));
//new Warranty(Integer.parseInt(ID), warranty_name, start_date, end_date, img_path);
Intent showWarranty = new Intent(HomeActivity.this, ShowWarranty.class);
startActivity(showWarranty);
}
});
buttonViewWarrantys.addView(buttons);
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Startdate: " + cn.getStartDate() + " ,EndDate: " + cn.getEndDate() + " ,Path: " + cn.getImgFilePath();
System.out.println(log);
}
}
}
This is my Warranty class with my setter and getter.
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
After this I try to retrieve it but the result of the ID is 0 and when I set it it is 8.
public class ShowWarranty extends AppCompatActivity {`
Warranty wr = new Warranty();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_warranty);
int test = wr.getID();
System.out.println("The number is: " + test);
}
}
Why is this not possible?
You create a new instance in both the classes, meaning when you grab it in the second class you haven't set the value on the instance in that class. From what you're describing, the variable is not static, meaning the value depends on the instance. The default value for integer primitives is 0, which is the reason why it has that specific value.
Pseudocode example of what you're doing:
Warranty x = new Warranty();
x.setID(8);
Warranty y = new Warranty();
System.out.println(y.getID());//Since the ID of y isn't set, it'll print 0
As for a possible solution:
If your class is fairly basic, just make it implement Serializable and put it as an extra in the intent. And by "fairly basic" I mean a class that you actually can serialize. Classes like Context cannot be serialized, so you'd need to add a method for adding it back after it's been deserialized and mark unserializable fields as transient. Or just pass the primitives directly.
You can use parcelable instead of Serializable, but that's a matter of preference.
You add the data into the intent. See how to pass primitives. Or if you want to pass an object, you must first flatten it, and then pass the parcelable. Each intent has its own address space
I have an input form in an activity where I'd like to retrieve the start time and end time of an event. I am using a timepicker displayed in a dialog fragment to get the start time and return it to the main activity, but how do re use the same logic to retrieve the end time of the event? My code:
Main Activity:
public class AddEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener{
private int pickerHour = 0;
private int pickerMin = 0;
//code ommitted for length
public void showTimePickerDialog(View v) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String amOrPm = "am";
pickerHour = hourOfDay;
pickerMin = minute;
String minutesString = "";
if (hourOfDay > 12){ //translate to 12 hr clock. Little workaround to get both timepicker and am/pm label to show up correctly.
amOrPm = "pm";
pickerHour-=12;
}
if (pickerMin < 10) {
minutesString = "0"; //fix weird bug where only one zero is shown on times ending in :00
}
startTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
}
TimePickerFragment:
public class TimePickerFragment extends DialogFragment {
int hour,minute;
private Activity mActivity;
private TimePickerDialog.OnTimeSetListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
try {
mListener = (TimePickerDialog.OnTimeSetListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnTimeSetListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(mActivity, mListener, hour, minute,
DateFormat.is24HourFormat(mActivity));
}
}
I need to be able to differentiate between the start time and the end time, but I am not sure how to differentiate them without repeating myself. I am pretty new to Java and Android. Thank you so much for any help.
Possibly something as simple as a boolean?
public class AddEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener{
...
boolean isSettingStartTime = true;
//code ommitted for length
public void showTimePickerDialog(View v) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
...
if (isSettingStartTime) {
startTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
isSettingStartTime = false;
} else {
endTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
}
}
}
This would require you being able to retrieve the TimePicker from your TimePickerFragment
You either need to get the TimePicker instance when you create both TimePickerFragments and store them in two fields such as startTimePicker and finishTimePicker.
Then when the TimePicker is passed in through the onTimeSet you then check to see which TimePicker it is like so.
if ( timePicker == startTimePicker ) {
startTimeTextView.setText....
} else {
finishTimeTextView.setText...
}