I am trying to create a calendar fragment and I have created a DatePickerFragment to do so. I have gotten my source code from https://gist.github.com/codinginflow/53a4885e0829981e7f64e78eec8a32b7
and have adjusted it so I can click a button inside a fragment and pick my date on the calendar. But when I try to use my DatePickerFragment, it gives me this error:
java.lang.ClassCastException: android.app.FragmentManagerImpl cannot be cast to android.app.DatePickerDialog$OnDateSetListener
This is my code for the DatePickerFragment:
package com.example.budgetapp;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.app.DialogFragment;
import androidx.annotation.NonNull;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) this, year, month,day);
}
}
How can I return the DatePickerDialog correctly? Thank you!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I will be very grateful for your help, I am trying to create JavaFX applications, I want to start creating something on the canvas panel, the code is compiling but no effects, it seems to me that the canvas panel view is not refreshed, maybe some spec will advise what I forgot, I throw in the whole class, below the code the window structure from the scene builder and the project structure.
[![package com.example.rpgfxmaven;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.AnchorPane;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.IOException;
public class GameControler{
final int oryginalnyRozmiarLudzika = 16; // 16x16 tile
final int skala = 3;
final int rozmiarLudzika = skala * oryginalnyRozmiarLudzika;
final int dlugoscPlanszy = 20;
final int szerokoscPlanszy = 15;
final int dlugoscEkranu = rozmiarLudzika*dlugoscPlanszy;
final int szerokoscEkranu = rozmiarLudzika*szerokoscPlanszy;
#FXML
private Canvas canvaspane = new Canvas(dlugoscEkranu, szerokoscEkranu);
GraphicsContext content;
public static MediaPlayer mediaPlayer;
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("maingame-window.fxml"));
AnchorPane anchorPane= loader.load();
anchorPane.setPrefSize(dlugoscEkranu+100, szerokoscEkranu+75);
Scene scene = new Scene(anchorPane);
primaryStage.setScene(scene);
primaryStage.show();
content = canvaspane.getGraphicsContext2D();
startGame();
}
public void startGame()
{
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(10), e ->run(content)));
timeline.setCycleCount(Timeline.INDEFINITE);
}
public void run(GraphicsContext content) {
content.setFill(Color.BLUE);
content.fillRect(100, 100, rozmiarLudzika,rozmiarLudzika);
}
}
This is wrong:
#FXML
private Canvas canvaspane = new Canvas(dlugoscEkranu, szerokoscEkranu);
You should never set an #FXML injected field to a new value.
The fxml loader will already have created an instance of the #FXML field and linked that into the object tree returned by the loader.
If you assign the field to a new value, the new value will not be in the loaded object tree added to the scene graph, so it will never be seen. Only the empty canvas created by the loader will be seen.
You almost definitely have other issues with your application outside of this, but I can't really outline them in detail here.
I'm working in Kotlin and using retrofit. I have a recycler view, which consists of cards. Each card has a typeName and an image associated to it which for now I have added statically using dataclass. Now, I need to pass the typeName only from the CategoryFragment to the LocationFragment once the user clicks on a particular card. And at the LocationFragment I want to check the latitude, longitude and typeName from the database if it already exists.
Here's my code for the dataclass of Category:
data class Category_dataclass ( val category_image : Int , val typeName: String)
Here's my code for the CategoryFragment:
package com.example.atry.MakeComplaint
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.Complaints
import com.example.atry.History.MyComplainRecyclerViewAdapter
import com.example.atry.R
import kotlinx.android.synthetic.main.existing_complaint_popup.*
class CategoryFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_category, container, false)
val recyclerView = v.findViewById(R.id.category_list) as RecyclerView
recyclerView.apply {
layoutManager = GridLayoutManager(context!!, 2)
}
//creating an arraylist to store category using the data class user
val category = ArrayList<Category_dataclass>()
//adding some dummy data to the list of categories
category.add(Category_dataclass((R.drawable.trash) , "Water"))
category.add(Category_dataclass((R.drawable.fire) , "Sewerage"))
category.add(Category_dataclass((R.drawable.dustbin) , "load"))
//creating our adapter
val adapter = CategoryRecyclerViewAdapter(category)
//now adding the adapter to recyclerview
recyclerView.adapter = adapter
// Inflate the layout for this fragment
return v
}
}
Here's the CategoryRecyclerViewAdapter:
package com.example.atry.MakeComplaint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.ComplaintDetailsFragment
import com.example.atry.History.Complaints
import com.example.atry.MakeComplaint.Category_dataclass
import com.example.atry.MakeComplaint.CategoryRecyclerViewAdapter
import com.example.atry.R
import java.util.*
import kotlin.collections.ArrayList
class CategoryRecyclerViewAdapter(val categoryList: ArrayList<Category_dataclass>) : RecyclerView.Adapter<CategoryRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryRecyclerViewAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.fragment_category_single, parent, false)
return ViewHolder(v)
}
//this method is binding the data on the list
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItems(categoryList[position])
holder.mView.setOnClickListener{view->
val lFragment = LocationFragment()
val oldFragment = CategoryFragment()
val manager = (holder.mView.context as AppCompatActivity).supportFragmentManager
val transaction = manager.beginTransaction()
transaction.replace(
R.id.first_screen_of_makecomplaint,
lFragment
) // give your fragment container id in first parameter
transaction.show(lFragment)
transaction.hide(oldFragment)
transaction.isAddToBackStackAllowed
transaction.addToBackStack(oldFragment.fragmentManager.toString()) // if written, this transaction will be added to backstack
transaction.commit()
}
}
//this method is giving the size of the list
override fun getItemCount(): Int {
return categoryList.size
}
inner class ViewHolder(val mView : View) : RecyclerView.ViewHolder(mView) {
fun bindItems(cat:Category_dataclass) {
val imageViewName = mView.findViewById(R.id.category_image) as ImageView
val textViewtext = mView.findViewById(R.id.category_text) as TextView
imageViewName.setImageResource(cat.category_image)
textViewtext.text = cat.typeName
}
}
}
And this is my retrofit:
//to check existing complaint
#GET("api/existingComplain")
#FormUrlEncoded
fun checkExistingComplain(#Query("typeName") typeName:String,
#Query("longitude") longitude:String,
#Query("latitude") latitude:String):Observable<Observables.checkExistingResult>
I've created and object where i stored the dataclass which will return the following:
data class checkExistingResult(val description:String , val Complain:String)
if the typeName and location already exists in the database I want the description and Complain to be displayed on a material styled dialog.
You can try this:
1st Step:-
val dashboard = "Dashboard"
take variable like this you can take it's name as your fragment name so page name you can check like this MainActivity().dashboard
Now, 2nd Step:-
create one class and write function like this in that class
fun openPage(
activity: Activity,
pagename: String?, model: PaymentDetails
) {
when (pagename) {
MainActivity().dashboard -> {
val mfragment = DashboardFragment()
(activity as MainActivity).fragmentManager.beginTransaction()
.replace(R.id.nav_host, mfragment).commit()
val a = Bundle()
a.putSerializable("model", model)
mfragment.arguments = a
}
}
}
take key value pair as I take my whole model and key is model in my code you can write any thing.
3rd Step:-
Make your model Serializable
4th Step:- When you are adding your values into model add details and add your model for method in which you want to use these values like following
val payment = PaymentDetails(
type,
price,
name,
id,
)
paymentData!!.add(payment)
CustomMethods().openPagePaymentDetails(
activity!!,
MainActivity().sessionPaymentFragment, payment
)
5th Step:-
Declare and initialise your object with type of your model like following:
//Declare
private var model: PaymentDetails? = null
//initialise
model = arguments!!.getSerializable("model") as PaymentDetails?
And now finally you can access value of previous fragment into your next fragment like this,
var type: String
type = model!!.type
Note:- please do no forgot to make your model class Serializable
Hope so it will help you.
I am using a text file to load information to a javafx gui. Is there a way I can use a text value there to select a radio button in a toggle group.
I think '''toggleGroup.selectedValue(toggle value)''' is the function I need, but it does not take a string. Is there a way to convert the string to a toggle value, indirectly?
The following does not work because '''selectToggle()''' takes a toggle not a text value and neither an implicit nor explicit '''(toggle)''' cast seem to work.
tgrpSex.selectToggle(read.nextLine());
This should be reproducible:
package programmingassignment1;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.*;
//import javafx.scene.layout.StackPane;
//import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*; //input/output
import java.util.Scanner;
//import java.util.*; //scanner, user input
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
//import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class Address extends Application {
RadioButton rbMale = new RadioButton("Male");
RadioButton rbFemale = new RadioButton("Female");
ToggleGroup tgrpSex = new ToggleGroup();
GridPane rootPane = new GridPane();
#Override
public void start(Stage primaryStage){
//Setting an action for the Open Contact button
Button btOpenContact = new Button("Open Contact");
File file = new File("AddressBook.txt");
btOpenContact.setOnAction(event -> {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
});
//Setting an action for the Save button
Button btSave = new Button("Save");
btSave.setOnAction(
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{saveContact(file);}
catch(Exception f){f.getMessage();}
}});
//associate radio buttons with a toggle group
rbMale.setToggleGroup(tgrpSex);
rbFemale.setToggleGroup(tgrpSex);
rbMale.setOnAction(e -> {
if(rbMale.isSelected()){int maleContact = 1;}
});
rbFemale.setOnAction(e -> {
if(rbFemale.isSelected()){int maleContact = 0;}
});
rootPane.add(new Label("Sex"), 3, 1);
rootPane.add(rbFemale, 3, 2);
rootPane.add(rbMale, 3, 3);
rootPane.add(btOpenContact, 1, 13);
Scene scene = new Scene(rootPane, 1000, 500);
primaryStage.setTitle("Address Book");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public void saveContact(File file) throws FileNotFoundException, Exception{ //declaration
//this code might cause a FileNotFoundException
//if it does it creates an exception object of the above type
try{
//PrintWriter output = new PrintWriter (file);
PrintStream output = new PrintStream(file);
output.println(tfContactFirst.getText());
output.println(tfContactLast.getText());
output.println(tfSpouseFirst.getText());
output.println(tfSpouseLast.getText());
output.println(cboWorkHome.getValue());
output.println(tfStreet.getText());
output.println(tfCity.getText());
output.println(tfState.getText());
output.println(tfZip.getText());
output.close();
}
//what do do with exception
//here the catch clause with create another exception
//that is passed the result of the getMessage() method from the original exception
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
//read same text file you save too
public void openContact(File file) throws FileNotFoundException, Exception{
try{
Scanner read = new Scanner(file);
while(read.hasNextLine()){
//how do I save the imageFileName
tfContactFirst.setText(read.nextLine());
tfContactLast.setText(read.nextLine());
tgrpSex.selectToggle(read.nextLine());
tfSpouseFirst.setText(read.nextLine());
tfSpouseLast.setText(read.nextLine());
//tfSpouseGender.setText(read.nextLine());
cboWorkHome.setValue(read.nextLine());
tfStreet.setText(read.nextLine());
tfCity.setText(read.nextLine());
tfState.setText(read.nextLine());
tfZip.setText(read.nextLine());
//taNotes.setText(read.nextLine());
}
}
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
}
No results <- syntax error
Sorry. I got the answer. I didn't know what a toggle type object was. I looked up an examples of selectToggle() and learned you can pass a radio button object to it. So I put that in an if then statement. if(read.nextLine().equals("Male")){tgrpSex.selectToggle(rbMale);}
else{tgrpSex.selectToggle(rbFemale);}
I have a simpleIntegerProperty representing a quantity in seconds which I want to represent in hh:mm:ss format.
I'd like to render this in a Label via binding the Label textProperty to the simpleIntegerProperty. I understand I can do something similar to this with format strings, e.g.
activeTimeText.textProperty().bind(model.activeTimeSeconds.asString("Seconds: %04d"));
renders:
Seconds: 0000
So the question, how to implement a more complex asString conversion? For example my current desired output output (where the digits are functions of the seconds simpleIntegerProperty.):
00:00:00
I've searched for an a similar question already as I feel this should be quite common. However have not found the answer. Apologies if this is a duplicate.
You can extend SimpleIntegerProperty to override asString:
class MySimpleIntegerProperty extends SimpleIntegerProperty{
#Override
public StringBinding asString(){
return Bindings.createStringBinding(() -> " hello " + get() , this);
}
}
To test use:
MySimpleIntegerProperty activeTimeSeconds = new MySimpleIntegerProperty();
activeTimeSeconds.set(7);
SimpleStringProperty activeTimeText = new SimpleStringProperty();
activeTimeText.bind(activeTimeSeconds.asString());
System.out.println(activeTimeText.get());
You can of course delegate the value processing to a method:
#Override
public StringBinding asString(){
return Bindings.createStringBinding(() -> processValue(get()), this);
}
private String processValue(int value){
return " hello " + get() ;
}
The NumberExpression.asString(String) formats the number according to the rules of Formatter, same as if using String.format or Print[Stream|Writer].printf. Unfortunately, unless I'm missing something, the Formatter class expects date/time objects to represent a moment in time, not a duration of time. To format your property as a duration with a HH:MM:SS format you'll need to create your own binding.
To get the String you want you can still use String.format, but by formatting as integral numbers rather than time. This requires you to calculate the hours, minutes, and seconds.
String str = String.format("%02d:%02d:%02d", hours, minutes, seconds);
If you're using Java 9+, calculating the hours, minutes, and seconds is made extremely easy with java.time.Duration; the class had the toHoursPart, toMinutesPart, toSecondsPart, and other similar methods added in Java 9. If using Java 8 you'll need to do the calculations manually or pull in a library, see this question for some help in that regard.
Here's an example assuming Java 9+ and using Bindings.createStringBinding to create the binding:
import java.time.Duration;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
private final IntegerProperty seconds = new SimpleIntegerProperty(this, "seconds");
#Override
public void start(Stage primaryStage) {
Label label = new Label();
label.textProperty().bind(Bindings.createStringBinding(() -> {
// java.time.Duration
Duration duration = Duration.ofSeconds(seconds.get());
return String.format("%02d:%02d:%02d", duration.toHoursPart(),
duration.toMinutesPart(), duration.toSecondsPart());
}, seconds));
primaryStage.setScene(new Scene(new StackPane(label), 500, 300));
primaryStage.show();
Timeline timeline = new Timeline(
new KeyFrame(javafx.util.Duration.seconds(1.0), e -> seconds.set(seconds.get() + 1))
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
}
I want to display an alert when a file already exists when trying to create the file with same name . I have not completed the code fully. I want to retrieve the button value Yes/No from the UI .
Code:
This is how the controller is coded.
package application;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class WarningController implements Initializable {
#FXML
public Button yes;
#FXML
public Button no;
public static String type;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public String confirmSelection(ActionEvent event)throws IOException{
Button button = (Button) event.getSource();
type = button.getText();
if(type.equals("Yes")){
Stage stage = (Stage) yes.getScene().getWindow();
stage.close();
//System.out.println("Yes");
return type;
}
else{
//System.out.println("No");
Stage stage1 = (Stage) no.getScene().getWindow();
stage1.close();
return type;
}
}
/********************************************************************************/
public void writesheet(String[][] result,String ComboValue,String[] heading) throws IOException{
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");
//Create row object
XSSFRow row;
String[][] towrite=result;
int rows=towrite.length;
//int cols=towrite[0].length;
// System.out.println(rows +" "+ cols);
Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
empinfo.put("0", heading);
for(int i=1;i<=rows;i++){
empinfo.put( Integer.toString(i),towrite[i-1]);
}
//Iterate over data and write to sheet
Set < String > keyid = empinfo.keySet();
int rowid = 0;
for (String key : keyid)
{
row = spreadsheet.createRow(rowid++);
Object [] objectArr = empinfo.get(key);
int cellid = 0;
for (Object obj : objectArr)
{
Cell cell = row.createCell(cellid++);
//cell.setCellValue((String)obj);
cell.setCellValue(obj.toString());
}
}
//Write the workbook in file system
File f=new File(("C:\\"+ComboValue+".xlsx"));
if(f.exists()){
Stage primaryStage=new Stage();
Parent root=FXMLLoader.load(getClass().getResource("/application/Warning.fxml"));
Scene scene = new Scene(root,350,150);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(type);
}
FileOutputStream out = new FileOutputStream(f);
workbook.write(out);
out.close();
System.out.println(ComboValue+" "+"Excel document written successfully" );
workbook.close();
}
}
I want to use button value(stored in String type) in writesheet function. Now it is returning NULL.
Please suggest if there is any other way to show warning.I am using two fxml files and this is the second excel file.
[1]: http://i.stack.imgur.com/ZK6UC.jpg
Simply use the Alert class. It provides functionality for most yes/no dialogs that you ever need.
Alert alert = new Alert(AlertType.WARNING,
"File already exists. Do you want to override?",
ButtonType.YES, ButtonType.NO);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
Also here is a good tutorial.
I usually make a method, and call it if certain conditions are not met.
Ex:
if(condition)
alert();
public void alert(){ //alert box
Alert alert = new Alert(AlertType.WARNING,"", ButtonType.YES, ButtonType.NO); //new alert object
alert.setTitle("Warning!"); //warning box title
alert.setHeaderText("WARNING!!!");// Header
alert.setContentText("File already exists. Overwrite?"); //Discription of warning
alert.getDialogPane().setPrefSize(200, 100); //sets size of alert box
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
}
I grabbed some code from Jhonny007, credit to him.