This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am following this tutorial for implementing date and time on edit text click.
public class LoadActivity extends AppCompatActivity {
#SuppressLint("StaticFieldLeak")
static EditText DateEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
EditText startTimeEditText = (EditText) findViewById(R.id.start_time);
startTimeEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTruitonTimePickerDialog(v);
showTruitonDatePickerDialog(v);
}
});
} // end onCreate
public void showTruitonDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#NonNull
#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(requireActivity(), this, year, month, day);
}
}
#SuppressLint("SetTextI18n")
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit.setText(day + ":" + (month + 1) + ":" + year);
}
}// end main class
I am able to see the date fragment in my app but when I press ok button the app crashes and I am getting error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.thumbsol.accuratemobileassetsmanagament.LoadActivity$DatePickerFragment.onDateSet(LoadActivity.java:300)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java:134)
The line number 300 is DateEdit.setText(day + ":" + (month + 1) + ":" + year);
How can I get rid of this error? Any help would be highly appreciated.
You only define static EditText DateEdit, and also need to get it via findViewById.
for example:
DateEdit = (EditText) findViewById(R.id.date_edit);
That's because you're not setting the value of DateEdit anywhere in your code.
Tip: try to not use a view as static. It may cause leaks.
Related
I'm kind of new to Android, and I'm currently struggling with the TimePicker. So, I've got the TimePicker here:
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public String time;
#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
time = hourOfDay + ":" + minute;
//update global variable
MockDB.setCheckout(time);
}
}
This is working, but after the user selects a time I want to call a function in the activity the picker is in to change the button colors and text. This is in a function called ReserveProduct that extends AppCompatActivity.
public void animateButtons() {
//picker disappears until next button is clicked
Button picker = (Button) findViewById(R.id.button6);
picker.setVisibility(View.GONE);
Button picker1 = (Button) findViewById(R.id.button7);
picker1.setVisibility(View.GONE);
if (settingReturn == false) {
//first button turns gray
Button bttn1 = (Button) findViewById(R.id.buttonCheckIn);
bttn1.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getCheckout();
bttn1.setText("Check Out: 12:27 PM");
//new button appears
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setVisibility(View.VISIBLE);
settingReturn = true;
} else {
//make 2nd button inactive
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getReturn();
bttn2.setText("Return: 1:27 PM");
//show new buttons
Button set = (Button) findViewById(R.id.buttonSet);
set.setVisibility(View.VISIBLE);
Button home = (Button) findViewById(R.id.buttonHome);
home.setVisibility(View.VISIBLE);
}
}
My issue is that this function is not static, so I'm not able to simply call it from the TimePicker class. I can't move the button changing functionality to the TimePicker class because I need to be able to extend AppCompatActivity, but AppCompatActivity and DialogFragment have a conflicting class. I also can't make the animateButtons() class static because then the findViewById() functionality throws an error.
Please help!!
Instantiate the class first, i.e.
(new SomeClass()).someMethod();
I need to open a DatePicker with a default date based on the YEAR-MONTH-DAY_OF_MONTH properties of a GregorianCalendar.
Here is the code where I open the DatePicker:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
For exemple, if my values are like this:
MyCalendar.YEAR = 2017
MyCalendar.MONTH = 2
MyCalendar.DAY_OF_MONTH = 22
The default value set when I open the DatePicker would be:
What do I have to add to do that?
Basically straight from Android | Pickers
Plus, just like any other Fragment, you can use set and get-Arguments to pass data into the fragment.
Details: Best practice for instantiating a new Android Fragment
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static DatePickerFragment newInstance(int year,int month,int day) {
Bundle b = new Bundle();
b.putInt("year", year);
// put others...
Fragment f = new DatePickerFragment();
f.setArguments(b);
return f;
}
#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);
// Update using the arguments
Bundle args = getArguments();
if (args != null) {
year = args.getInt("year");
// get others...
}
// 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
}
}
And use that newInstance method.
DialogFragment newFragment = DatePickerFragment.newInstance(2017,02,07);
newFragment.show(getFragmentManager(), "datePicker");
I'm working on an android app. That uses a 'datepicker' as part of a data entry form. I've written a getter method "onDateSet" to return data from the object but i'm unable to call the method from the instance of the class.
line: datePicker.getSelectedDate(); I'm getting a 'method cannot be resolved' error
I get the same message when I try and access the variable directly. datePicker.selecteddate
I would be grateful if someone could point me in the right direction.
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);
}
int selectedDate;
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
selectedDate = day+month+year;
}
public int getSelectedDate() {
return selectedDate;
}
}
public void showDatePickerDialog(View view) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "datePicker");
int output = datePicker.getSelectedDate();
}
You have:
DialogFragment datePicker = new DatePickerFragment();
You mean:
DatePickerFragment datePicker = new DatePickerFragment();
This is because your methods are members of your subclassed DatePickerFragment, not of the base class DialogFragment.
Essentially, when you refer to an object through its base type, the compiler only knows about the methods the base type declares. It has no way of knowing that an arbitrary DialogFragment is actually a DatePickerFragment (or any other derived type).
An alternative, if you know it is a DatePickerFragment, is to explicitly cast datePicker to a DatePickerFragment:
DialogFragment datePicker = new DatePickerFragment();
...
int output = ((DatePickerFragment)datePicker).getSelectedDate();
This, of course, will fail with a ClassCastException if datePicker isn't actually a DatePickerFragment.
I've got a couple of Buttons that initially display the current date and the current time, respectively. When clicking in the Button that displays the date, it shows a DatePickerFragment that allows the user to choose a date, and then changes the Button's text to the date selected by the user. The other Button does exactly the same but with a TimePickerFragment.
To initialize the Buttons I use the following code:
protected void onCreate(Bundle savedInstanceState){
...
df = DateFormat.getDateInstance();
tf = DateFormat.getTimeInstance();
initDate = new GregorianCalendar();
...
updateDateButtons();
updateTimeButtons();
}
private void updateTimeButtons() {
tf.setCalendar(initDate);
String text = tf.format(initDate.getTime());
btnIniTime.setText(text.substring(0, text.lastIndexOf(":")));
}
private void updateDateButtons() {
df.setCalendar(initDate);
btnIniDate.setText(df.format(initDate.getTime()));
}
Initially, both buttons behave in an expected manner: btnIniTime shows the current time, and btnIniDate shows the current date.
As I said, when the user clicks the btnIniTime button, it shows a TimePickerFragment that prompts the user to choose a time, and the selected time is correctly displayed in btnIniTime.
The problem starts with btnIniDate, that should do the same, but using a DatePickerFragment instead of a TimePickerFragment. When the user selects a date, the button then displays an incorrect date. For example, if I choose 2013 Aug 30, the displayed date turns to be 2013 Aug. 26. If I choose 2013 Sep 1, it then shows 2013 Sep 29!
The classes and methods that I use to change the date ara arranged in the following way:
public abstract static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
protected TaskActivity activity;
protected Calendar c;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (TaskActivity) activity;
}
#Override
public abstract Dialog onCreateDialog(Bundle savedInstanceState);
public void onDateSet(DatePicker view, int year, int month, int day) {
if(activity instanceof TaskActivity){
setDateResult(year, month, day);
}
}
protected abstract void setDateResult(int year, int month, int day);
}
public static class InitDatePickerFragment extends DatePickerFragment {
#Override
protected void setDateResult(int year, int month, int day) {
activity.setInitDate(year, month, day);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = activity.getInitDate();
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 Calendar getInitDate() {
return initDate;
}
public void setInitDate(int year, int month, int day){
Log.d("TaskActivity", "Year: " + year + "; Month: " + month + "; Day: " + day);
initDate.set(Calendar.YEAR, year);
initDate.set(Calendar.MONTH, month);
initDate.set(Calendar.DAY_OF_WEEK, day);
updateDateButtons();
}
When you push the button:
#Override
public void onClick(View v) {
if(v.equals(btnIniDate)){
DialogFragment newFragment = new InitDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "initDatePicker");
}
...
}
By the way, when setting the date, LogCat produces the following output (I've chosen 2013 Aug 30):
Year: 2013; Month: 7; Day:30
The Problem might be
initDate.set(Calendar.DAY_OF_WEEK, day);
in your setInitDate(). This updates only the day of the week. So your date jumps +-6
use
initDate.set(Calendar.DAY_OF_MONTH, day);
In my Android application i have a tracker activity in which i retrieve the exercises information(name , period , burned calories) from the sqlite data base based on the selected date and display these information in a linear layout , and my problem that as the user select new date the retrieved data are displayed in another "new " layout appear above the old one but what actually i want to do is to display the new retrieved data on the same layout " change the layout content with the new retrieved data ", i have tried the remove all views method but it didn't work since the data appear for few minutes then dis appear
How i can do this: when the user select a new date the new retrieved data displayed on the same layout " refresh the old data by the new one " not to display them in anew layout . how i can do that ? please help me..
java code
public class Tracker extends BaseActivity
{
private Button date_btn;
private ImageButton left_btn;
private ImageButton right_btn;
private ImageView nodata;
private TextView ex_name;
private TextView ex_BCals;
private LinearLayout excercises_LL;
private LinearLayout content_LL ;
private LinearLayout notes;
private LinearLayout details;
private int year,month,day;
private double tot_excals_burned;
private Calendar localCalendar;
private static final int DATE_DIALOG_ID=0;
private boolean has_ex_details;
private boolean has_meal_details=false;
private Cursor exercises_cursor;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tracker);
date_btn=(Button)findViewById(R.id.btn_date);
date_btn.setText(FormatDate());
date_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar = Calendar.getInstance();
year = localCalendar.get(1);
month= localCalendar.get(2);
day = localCalendar.get(5);
showDialog(DATE_DIALOG_ID);
}
});
left_btn=(ImageButton)findViewById(R.id.btn_left);
left_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, -1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
right_btn=(ImageButton)findViewById(R.id.btn_right) ;
right_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, 1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
details=(LinearLayout)findViewById(R.id.ll_details);
notes=(LinearLayout)findViewById(R.id.ll_notes);
excercises_LL=(LinearLayout)findViewById(R.id.ll_exercises);
nodata=(ImageView)findViewById(R.id.nodata_imgV);
RefreshExercisesData();
RefreshNoDataImage();
}
private String FormatDate()
{
localCalendar = Calendar.getInstance();
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(int year, int month, int day)
{
localCalendar = Calendar.getInstance();
localCalendar.set(year, month, day);
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(Calendar calendar , String format)
{
return new SimpleDateFormat(format).format(calendar.getTime());
}
private void RefreshExercisesData()
{
tot_excals_burned=0;
DBAdapter db = new DBAdapter(this);
db.open();
String selected_date= date_btn.getText().toString();
Log.e("date", selected_date);
exercises_cursor = db.getExerciseInfo(selected_date);
if(exercises_cursor.getCount() !=0 )
{
has_ex_details=true;
details.setVisibility(0);
nodata.setVisibility(8);
notes.setVisibility(0);
//excercises_LL.removeAllViews();
excercises_LL.setWeightSum(1.0F);
excercises_LL.setVisibility(0);
excercises_LL.setOrientation(LinearLayout.VERTICAL);
LayoutInflater exc_LayoutInflater = (LayoutInflater)getApplicationContext().getSystemService("layout_inflater");
LinearLayout layout = (LinearLayout)exc_LayoutInflater.inflate(R.layout.tracker_header_item,null);
TextView tot_ex_cals_value=((TextView)(layout).findViewById(R.id.tv_tot_cals_value));
TextView exs_title=((TextView)(layout).findViewById(R.id.tv_item_title)) ;
exs_title.setText("Exercises ");
(layout).setPadding(0, 36, 0, 0);
excercises_LL.addView((View)layout, 0);
int i = 1;
if (exercises_cursor.moveToFirst())
{
do
{
content_LL=new LinearLayout(this);
ex_name=new TextView(this);
ex_name.setText( exercises_cursor.getFloat(1)+"," +exercises_cursor.getString(0) + "min ");
ex_name.setTextColor(R.color.black);
content_LL.addView(ex_name,0);
ex_BCals=new TextView(this);
ex_BCals.setText(Round(exercises_cursor.getFloat(2)) +" ");
ex_BCals.setTextColor(R.color.color_black);
content_LL.addView(ex_BCals,1);
tot_excals_burned = tot_excals_burned+exercises_cursor.getFloat(2);
excercises_LL.addView(content_LL, i);
i++;
}
while (exercises_cursor.moveToNext());
}
tot_ex_cals_value.setText(Round(tot_excals_burned) );
}
else if(exercises_cursor.getCount()==0 ||tot_excals_burned==0)
{
has_ex_details=false;
RefreshNoDataImage();
}
exercises_cursor.close();
exercises_cursor.deactivate();
db.close();
}
private void RefreshNoDataImage()
{
if(has_ex_details==false && has_meal_details==false)
{
notes.setVisibility(8);
excercises_LL.setVisibility(8);
nodata.setImageResource(R.drawable.bg_nodata);
nodata.setVisibility(View.VISIBLE);
}
else
nodata.setVisibility(8);
}
protected Dialog onCreateDialog(int id)
{
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, this.year, this.month, this.day);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker paramDatePicker, int year, int monthofYear, int dayofMonth)
{
Tracker.this.year=year;
month=monthofYear;
day=dayofMonth;
date_btn.setText(FormatDate(year,month,day));
RefreshExercisesData();
RefreshNoDataImage();
}
};
private String Round(double num) {
return String.format("%.1f%n", num);
}}
Looks like you need to edit your question, if you want us to see any code samples.
If this is only a few texts for an exercise, it should be sufficient to give those views ids in the layout xml, so they can be referenced in your activity.
Then you can just get your views with findViewById in OnCreate, and when you receive data for the new exercise, you update those views with e.g. TextView.setText().
If you have a layout, for example one like this:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/calories_burned_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Then in your Activity where you have access to your data from your sqlite db, you can modify the existing textviews within this layout by finding the view and using the setText method.
// load new data occurs above, now want to set
TextView name = (TextView)findViewById(R.id.name_textview);
name.setText(newName);
TextView calsBurned = (TextView)findViewById(R.id.calories_burned_textview);
calsBurned.setText(newCalsBurned);
It's possible, from what it sounds like in your description, that you are adding these textviews to the Activity via code each time some load button is clicked. You can do this, just hold on to the reference to these textviews you added and use setText() later on when you load a new entry (but don't create the textviews a second time).