Since i started programing with java on android projects, i didn't have problems where it says: Non static field cannot be referenced from a static context.
This is my code:
package com.esmad.pdm.friendlymanager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import java.util.Calendar;
import android.media.Image;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
public class NewMatch extends AppCompatActivity {
ImageView questionMark;
RadioGroup radioGroup;
EditText gameEventNameTxt;
TextInputLayout textInputLayout;
TextView dateHourTxt;
public static boolean changedData = false;
public static boolean changedHour = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_match);
questionMark = (ImageView) findViewById(R.id.questionMark);
questionMark.setClickable(true);
gameEventNameTxt = (EditText)findViewById(R.id.gameEvent);
textInputLayout = (TextInputLayout)findViewById(R.id.textInputLayout);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
dateHourTxt = (TextView)findViewById(R.id.dateHour);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
if (checkedId == R.id.event) {
textInputLayout.setHint("Event name");
}
else{
textInputLayout.setHint("Match name");
}
}
});
}
public void imageClick(View view) {
Log.d("builderH","im in the builder");
AlertDialog.Builder builder = new AlertDialog.Builder(NewMatch.this);
builder.setTitle("What is a event?");
builder.setMessage("You can create a Event and a game, a Event is a list of games that can be repeated without the need to create every week a new game!");
builder.setCancelable(false);
builder.setPositiveButton("I got it!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#RequiresApi(api = Build.VERSION_CODES.N)
#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) {
changedHour = true;
if(changedHour && changedData){
dateHourTxt
}
}
}
public void hourPicker(View view){
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
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) {
changedData = true;
}
}
public void datePicker(View view){
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
as you guys can see above i changed some data to static at initialization, but in other activities i didn't need to do that, and the same error happens for my dateHourTxt inside my onTimeSet method :S
You guys know why this is happening?
You are referencing dateHourTxt from a completely separate class, one that does not contain dateHourTxt.
Your onTimeSet() method is in TimePickerFragment. That is a static class. While its lines physically are inside of NewMatch, it has no access to regular fields on NewMatch. TimePickerFragment could just as easily be a separate Java class, in its own file. In fact, until you gain a bit more experience with Java, I recommend you do just that, to help you better visualize the separation between classes.
If you want TimePickerFragment to work with NewMatch, you need to do so using typical techniques, such as using getActivity() in the fragment to get at the NewMatch instance, so you can call methods on it.
When you make nested class static, it no longer has access to the outer class non static fields. It can access only static fields. In you example solution is to use Fragment.getActivity method to access NewMatch. It should look as follows,
if(changedHour && changedData){
if (getActivity() != null && getActivity() instanceof NewMatch) {
((NewMatch)getActivity()).dateHourTxt = ...
}
}
Related
I want to open a dialog from a subclass.
However, there are some problems with the Show function.
It does not take the subclass but the main class.
The Main Controller :
private void InitNavigation(){
MenuView = findViewById(R.id.bottomNavigationView);
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment);
NavController navCo = navHostFragment.getNavController();
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(R.id.home2,
R.id.verantstaltung, R.id.veranstalter,R.id.tanzpartnersuche).build();
NavigationUI.setupActionBarWithNavController(this, navCo, appBarConfiguration);
NavigationUI.setupWithNavController(MenuView, navCo);
navCo.navigate(R.id.home2);
}
I think at the Funktion openDatePickerDialog is the error. With getActivity().getsupportFragmentManager i get the Main Class but here i will get the subclass
The Sub Controller from which the dialog should be opened :
private void openDatePickerDialog(String type){
new DialogDatePicker(type).show(getActivity().getSupportFragmentManager(),"DialogDatePicker");
}
}
And Last the Dialog Controller :
package florian.tanzapp;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CalendarView;
import java.util.Calendar;
import java.util.Date;
import androidx.appcompat.app.AppCompatDialogFragment;
public class DialogDatePicker extends AppCompatDialogFragment {
private DialogDatePickerListener listener;
//DatePicker
CalendarView DatePicker;
//Var
String Type;
Date datum;
public DialogDatePicker(String type){
Type = type;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_datepicker,null);
builder.setView(view)
.setTitle("DatePicker")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
listener.applyDate(datum,Type);
}
});
DatePicker = view.findViewById(R.id.calendarView3);
DatePicker.setMinDate((new Date().getTime()));
DatePicker.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, month, dayOfMonth);
datum = newDate.getTime();
}
});
return builder.create();
}
#Override
public void onAttach(Context context){
super.onAttach(context);
try {
listener = (DialogDatePickerListener) context;
}
catch (ClassCastException e){
throw new ClassCastException(context.toString() + "must implement DialogDatePickerListener");
}
}
public interface DialogDatePickerListener{
void applyDate(Date datum, String type);
}
}
I don't have so much experience in Java because I am more specialized in C#. Does anyone see the problem what is wrong when I want to open the dialog from the subclasse ?
So, I want all of those variables to get the value after going through the OnClick method. When I put the log in the method they are ok, but outside... I know that they destroy because it's OnClick method and they are local but I don't know how to keep them. Please if you know how to help rewrite the code. Thanks!
package com.exemple.android.calendar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class NewEventActivity extends AppCompatActivity {
//step 1.A:create objects
public EditText DayEditText;
public EditText MonthEditText;
public EditText YearEditText;
public EditText StartingHourEditText;
public EditText StartingMinuteEditText;
public EditText EndingHourEditText;
public EditText EndingMinuteEditText;
public EditText Title;
public RadioGroup answer1;
public Button NewEventButton;
int day, month, year, s_hour, s_min, e_hour, e_min;
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_event_page);
//Step 1.B: assign objects
DayEditText = findViewById(R.id.DayEditText);
MonthEditText = findViewById(R.id.MonthEditText);
YearEditText = findViewById(R.id.YearEditText);
StartingHourEditText = findViewById(R.id.StartingHourEditText);
StartingMinuteEditText = findViewById(R.id.StartingMinuteEditText);
EndingHourEditText = findViewById(R.id.EndingHourEditText);
EndingMinuteEditText = findViewById(R.id.EndingMinuteEditText);
Title = findViewById(R.id.TitleEditText);
answer1 = findViewById(R.id.Answer1);
NewEventButton = findViewById(R.id.CreateEventButton);
//Step 2: get data into variables
//Step 2.B: get data and assign
//PROBLEM: If we just extract, the code won't be run because there's nothing to extract yet. We need a conditional.
//SOLUTION: Create a condition for pressing the button, and then extract the variables when the button is pressed.
NewEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
title = Title.getText().toString();
day = Integer.parseInt(DayEditText.getText().toString());
month = Integer.parseInt(MonthEditText.getText().toString());
year = Integer.parseInt(YearEditText.getText().toString());
s_hour = Integer.parseInt(StartingHourEditText.getText().toString());
s_min = Integer.parseInt(StartingMinuteEditText.getText().toString());
e_hour = Integer.parseInt(EndingHourEditText.getText().toString());
e_min = Integer.parseInt(EndingMinuteEditText.getText().toString());
}
});
Log.i("INFO:",title+" "+day+" "+month+" "+year+" "+s_hour+" "+s_min+" "+e_hour+" "+e_min);
}
}
Your code is correct, it is just a understanding issue.
In fact, it's normal the Log method prints nothing because your variables are not set. The code inside the OnClick is called only if a click happens. Then, when click happens, your variables are set correctly.
Understood ?
Here is an example of TextWatcher
DayEditText = findViewById(R.id.DayEditText);
DayEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
day = Integer.parseInt(s.toString());
}
});
Do the same for each EditTexts you have
I have created two activity one for registration details and another one for showing the value user has entered. But when I tried to get the value of radiobutton from the radiogroup selected. It doesn't show any error but when I debug and run in my phone.
And clicked the signup button
It show app stopped working start again message
My MainActivity.java :
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button signUpButton,signInButton;
TextView userTimeJoining, dateOfBirth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.signinbutton);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
signUpButton = findViewById(R.id.signupbutton);
signUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoRegAct = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(gotoRegAct);
}
});
}
}
My RegistrationActivity.java :
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class RegistrationActivity extends AppCompatActivity {
String courseList[] = {"Java","Python", "Android", "Kotlin"};
Button submitButton;
EditText nameOfUser, userGmail, userName, userPassword;
TextView userDateOfBirth, userTimeOfJoining;
Spinner mySpinnerForCourse;
RadioGroup genderSelected;
RadioButton selectedRadiobutton;
String setTime;
String setDate;
String setGender=" ";
int itemNoSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
submitButton = findViewById(R.id.submitButton);
nameOfUser = findViewById(R.id.nameofuser);
userGmail = findViewById(R.id.usergmail);
userName = findViewById(R.id.username);
userPassword = findViewById(R.id.userpassword);
userDateOfBirth = findViewById(R.id.userdateofbirth);
userTimeOfJoining = findViewById(R.id.usertimeofjoining);
mySpinnerForCourse = findViewById(R.id.usercourse);
genderSelected = findViewById(R.id.usergender);
//This is the code which is not working
int selectedRadioButtonId = genderSelected.getCheckedRadioButtonId();
selectedRadiobutton = (RadioButton) findViewById(selectedRadioButtonId);
setGender = selectedRadiobutton.getText().toString();
ArrayAdapter<String> arrayAdapterForCourse = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,courseList);
mySpinnerForCourse.setAdapter(arrayAdapterForCourse);
mySpinnerForCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
itemNoSelected = i;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
userTimeOfJoining.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int hh = calendar.get(Calendar.HOUR);
int mm = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(RegistrationActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
setTime = i+" : "+i1;
userTimeOfJoining.setText(setTime);
}
},
hh, mm, false);
timePickerDialog.show();
}
});
userDateOfBirth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int mm = calendar.get(Calendar.MONTH);
int yy = calendar.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(RegistrationActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
setDate = i2+" / "+i1+" / "+i;
userDateOfBirth.setText(setDate);
}
}, yy, mm, dd);
datePickerDialog.show();
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoShowInfo = new Intent(RegistrationActivity.this, ShowInfo.class);
Bundle bundleforenteredvalue = new Bundle();
bundleforenteredvalue.putString("enteredname",nameOfUser.getText().toString());
bundleforenteredvalue.putString("enteredgmail",userGmail.getText().toString());
bundleforenteredvalue.putString("enteredusername",userName.getText().toString());
bundleforenteredvalue.putString("enteredpassword",userPassword.getText().toString());
bundleforenteredvalue.putString("dateselected",setDate);
bundleforenteredvalue.putString("timeselected",setTime);
bundleforenteredvalue.putString("genderselected",setGender);
bundleforenteredvalue.putString("courseselected",courseList[itemNoSelected]);
gotoShowInfo.putExtras(bundleforenteredvalue);
startActivity(gotoShowInfo);
}
});
}
}
My ShowInfo.java :
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ShowInfo extends AppCompatActivity {
TextView nameOfUserEntered, usernameEntered, passwordEntered,gmailEntered, genderSelected, courseSelected, dateOFJoinSelected, timeOfJoinSelected;
Button signInButtonAgain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_info);
Bundle getValue = getIntent().getExtras();
String getnameentered = getValue.getString("enteredname");
String getenteredGmail = getValue.getString("enteredgmail");
String getenteredUsername = getValue.getString("enteredusername");
String getenteredPassword = getValue.getString("enteredpassword");
String getdateSelected = getValue.getString("dateselected");
String gettimeSelected = getValue.getString("timeselected");
String getgenderSelected = getValue.getString("genderselected");
String getcourseSelected = getValue.getString("courseselected");
nameOfUserEntered = findViewById(R.id.nameofuserentered);
usernameEntered = findViewById(R.id.usernameentered);
passwordEntered = findViewById(R.id.passwordentered);
gmailEntered = findViewById(R.id.gmailentered);
genderSelected = findViewById(R.id.genderselected);
courseSelected = findViewById(R.id.courseselected);
dateOFJoinSelected = findViewById(R.id.dateofjoinselected);
timeOfJoinSelected = findViewById(R.id.timeofjoinselected);
signInButtonAgain = findViewById(R.id.signinbuttonagain);
nameOfUserEntered.setText("Welcome "+ getnameentered);
usernameEntered.setText("Your username is "+getenteredUsername);
passwordEntered.setText("Your password is "+getenteredPassword);
gmailEntered.setText("Your gmail is "+getenteredGmail);
genderSelected.setText("Your gender is the "+getgenderSelected);
courseSelected.setText("You selected for the "+getcourseSelected+" Course");
dateOFJoinSelected.setText("your joinig date is "+getdateSelected);
timeOfJoinSelected.setText("Time of your duty is starts from "+gettimeSelected);
signInButtonAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoMainmenu = new Intent(ShowInfo.this, MainActivity.class);
startActivity(gotoMainmenu);
}
});
}
}
In registration activity I've added a comment by only that code my app show the error message. If I remove the radiobutton code and the getString String. It works properly and then it doesn't show app stopped working message.
So why I'm not able to pass the value of the radiobutton string from one activity to another.
Try this may be your radiobutton id returns -1 if no values are selected in radio group.
int chk_gender = rg_gender.getCheckedRadioButtonId();
if (chk_gender != -1) {
Gender = ((RadioButton)findViewById(chk_gender)).getText().toString();
}
else
{
Gender = "";
}
EDITED
rg_gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != -1) {
Gender = ((RadioButton)findViewById(checkedId)).getText().toString();
}
else
{
Gender = "";
}
}
});
In your xml layout ,did you checked TRUE any radio button ?
You should get the selected radio button value on click of submit button.It will update your setGender string with most recent value.
for your app crash , Please post your logcat error while app crash.
I have been using this tutorial here to create a time picker. I can select the time fine, but I can't get the time selected to show up in my TextView. Java is not my preferred language so that is probably where I am falling down.
Here is my java code:
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//code from: http://developer.android.com/guide/topics/ui/controls/pickers.html
public void showTimePicker(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
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 - how!?
}
}
}
In my XML I have the Choose Time button run the showTimePicker method on click like so:
android:onClick="showTimePicker"
I have tried just setting the text field inside the onTimeSet method but I get a nullpointerexception. Then I thought I should initialize it in onCreateDialog but there I don't know how to use findViewById to find the actual text view. I'm sure this is probably simple but I have searched up and down without much luck. Thanks for your help!
you can do it like that:
1) Solution 1 (better):
public class MainActivity extends Activity {
TextView resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = (TextView)findViewById(R.id./*YOUR TEXT VIEW ID*/);
}
//code from: http://developer.android.com/guide/topics/ui/controls/pickers.html
public void showTimePicker(View v) {
DialogFragment newFragment = new TimePickerFragment(resultText);
newFragment.show(getFragmentManager(), "timePicker");
}
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
TextView mResultText;
public TimePickerFragment(TextView textView) {
mResultText = textView;
}
#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) {
String time = /*CONVERT YOUR TIME FROM hourOfDay and minute*/;
mResultText.setText(time);
}
}
}
2) Solution 2:
public class MainActivity extends Activity {
public TextView mResultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResultText = (TextView)findViewById(R.id./*YOUR TEXT VIEW ID*/);
}
//code from: http://developer.android.com/guide/topics/ui/controls/pickers.html
public void showTimePicker(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public 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) {
String time = /*CONVERT YOUR TIME FROM hourOfDay and minute*/;
mResultText.setText(time);
}
}
}
You can actually use findViewById, as with getActivity() your fragment gets access to the activity it is running in and thus to the views inside the activity.
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView textView = (TextView) getActivity().findViewById(R.id.my_text_view);
textView.setText(String.format("%02d", hourOfDay), String.format("%02d", minute);
}
This simple solution should be preferred over passing a reference to the TextView to the fragment, as this reference will be lost on reinstantiation of the fragment (see comment).
I want to create a TimePickerDialog using FragmentDialog and exchange data between my fragment and the TimePickerDialog . I already created a DatePickerDialog but I don't know how to create a TimePickerDialog . I want that when the user click the button in my fragment TimePickerDialog appear .
This is how I create The DatePickerDialog :
import java.util.Calendar; import java.util.Date; import
java.util.GregorianCalendar;
import android.app.Activity; import android.app.AlertDialog; import
android.app.Dialog; import android.content.DialogInterface; import
android.content.Intent; import android.os.Bundle; import
android.support.v4.app.DialogFragment; import android.view.View;
import android.widget.DatePicker; import
android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "criminalintent.DATE";
Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment()
.onActivityResult(getTargetRequestCode(), resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date)getArguments().getSerializable(EXTRA_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater()
.inflate(R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker)v.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month, int day) {
mDate = new GregorianCalendar(year, month, day).getTime();
// update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
sendResult(Activity.RESULT_OK);
}
})
.create();
} }
CrimeFragment
import java.util.Date; import java.util.UUID;
import android.app.Activity; import android.content.Intent; import
android.os.Bundle; import android.support.v4.app.Fragment; import
android.support.v4.app.FragmentManager; import android.text.Editable;
import android.text.TextWatcher; import android.view.LayoutInflater;
import android.view.View; import android.view.ViewGroup; import
android.webkit.WebView.FindListener; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener; import
android.widget.EditText;
public class CrimeFragment extends Fragment {
public static final String EXTRA_CRIME_ID = "criminalintent.CRIME_ID";
private static final String DIALOG_DATE = "date";
private static final int REQUEST_DATE = 0;
Crime mCrime;
EditText mTitleField;
Button mDateButton;
CheckBox mSolvedCheckBox;
Button mTime;
String time;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
public void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
public void updateTime() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before, int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count, int after) {
// this space intentionally left blank
}
public void afterTextChanged(Editable c) {
// this one too
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTime = (Button) v.findViewById(R.id.crime_time);
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_DATE) {
Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
} }
Now I want to create a TimePickerDialog .
public class DialogFragmentTimePicker extends DialogFragment implements OnTimeSetListener {
public static final String ARG_HOUR = "hour";
public static final String ARG_MINUTE = "minute";
private OnTimeSetListener mListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
int hour, minute;
if (getArguments() != null) {
hour = getArguments().getInt(ARG_HOUR);
minute = getArguments().getInt(ARG_MINUTE);
} else {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
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 setOnTimeSetListener(OnTimeSetListener listener) {
mListener = listener;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (mListener != null) {
mListener.onTimeSet(view, hourOfDay, minute);
}
}
}