Remove item from a RecyclerView list based on status of a checkbox - checkbox

I have a list application what is uses RecyclerView.
Each line has got a button, a checkbox and 2 textview.
All object is defined the RecyclerView clas, but I would like to check the checkbox status in the Main class and evaluate the status and remove the item from the list and from the SharedPreferences where the checkbox is checked
Main class is here:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
}
#Override
public void onItemClick(View view, int position) {
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
At now the item is removed when the whole line is touched. I would like to exchange to if only the Checkbox is "true".
At now the remove method is in the public void onItemClick(View view, int position) function.
I would like to put the content of the OnItemClick method to "if" part of CheckBox status.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
holder.myTextView.setText(meta_data);
holder.subtext.setText(meta_subdata +" "+ meta_subdata2);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = holder.myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView myTextView, subtext;
public Button add;
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done = itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
if(adapter.done.isChecked())should work I think, but I got null opbject reference exception.
Maybe the problem is that the checkbox is in the RecyclerView layout and not in Main class layout, but I am not sure.
Is it possible to handle the Checkbox methods from other class, and if yes, then where should I improve the code?

Related

Not able to read data from Firebase Database in Android Studio

I have an application that is getting price,title etc. data from website. I get data with using jsoup with html parsing. I use a different class for html parsing. I also added membership system from Firebase Authentication to my application. Each user have different product lists. Products are located with user id in database. I want app to get values from database table but it gets titles of tables. My problem is getting titles from database table.
You can see the problem at this photo.
You can see another class at this photo
How can i get values ?
package com.example.lkuygulama;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class UrunEklemeActivity extends AppCompatActivity {
FirebaseDatabase firebaseDatabase;
DatabaseReference reference;
private String userId;
private FirebaseAuth.AuthStateListener mAuthlistener;
public ArrayList<String> goster = new ArrayList<String>();
ListView view;
ArrayAdapter<String> arrayAdapter;
public Button aramam,bildirim,liste;
private FirebaseAuth mAuth;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urun_ekleme);
Urun urun = new Urun();
bildirim=(Button) findViewById(R.id.bildirimButon);
liste = (Button) findViewById(R.id.urunListeButon);
view=(ListView)findViewById(R.id.listele);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,goster);
view.setAdapter(arrayAdapter);
mAuthlistener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
}
};
tanimla();
listele();
bildirim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gonderBildirim();
}
});
}
private void tanimla() {
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference();
}
private void listele() {
reference.child("urunler").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String valeu =dataSnapshot.getKey();
goster.add(valeu);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void gonderBildirim() {
Intent intent = new Intent(this, BildirimActivity.class);
startActivity(intent);
}
private void gonderAra() {
Intent intent = new Intent(this,AramaActivity.class);
startActivity(intent);
}
private void gonderListe() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
You should use getValue(String.class).
Like this :
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String valeu =dataSnapshot.getValue(String.class);
goster.add(valeu);
arrayAdapter.notifyDataSetChanged();
}
I recommend addListenerForSingleValueEvent instead of addChildEventListener.

How to save entire object for a checkbox in javafx

I have number of objects. Let's say i have 10 Books object and i want user to select any number of the book. When user press the submit button i want to retrieve all the books "object" that user selected.
As of now, while showing screen to user i use
CheckBox cb= new CheckBox(book.getName());
this shows bookname to user and user selects the book. But on runtime i will be needing bookid and other properties of book object as well.
Is there anyway through which i can save the book object in the checkbox?
Basic Examle. if you want more sepecifc you need to post your code, we can set object to node using setUserDate, then we can use that object when we need. here i am using object id for example, in yor case save that object i hope this will solve your problem ,?s post a comment
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class UserData extends Application {
public void start(Stage primaryStage) {
VBox root = new VBox();
Book book = new Book(22, "firstBok");
Book book1 = new Book(2, "secondBok");
CheckBox checkB = new CheckBox(book.getName());
checkB.setUserData(book);
CheckBox checkB1 = new CheckBox(book1.getName());
checkB1.setUserData(book1);
Button btn = new Button("Submit");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (checkB.isSelected()) {
int firstCheckBxId = ((Book) checkB.getUserData()).getId();
System.out.println("id:" + firstCheckBxId);
}
if (checkB1.isSelected()) {
int secondCheckBxId = ((Book) checkB1.getUserData()).getId();
System.out.println("id:" + secondCheckBxId);
}
}
});
root.getChildren().addAll(checkB, checkB1, btn);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
class Book {
int id;
private String name;
Book(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
launch(args);
}
}
Consider using a control with built-in selection functionality, such as a ListView. Then you can just check the selection model.
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BookSelection extends Application {
#Override
public void start(Stage primaryStage) {
ListView<Book> bookList = new ListView<>();
bookList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
bookList.setCellFactory(lv -> new ListCell<Book>() {
#Override
public void updateItem(Book book, boolean empty) {
super.updateItem(book, empty);
if (empty) {
setText(null);
} else {
setText(book.getTitle());
}
}
});
IntStream.rangeClosed(1, 10).mapToObj(i -> new Book("Book "+i)).forEach(bookList.getItems()::add);
Button submit = new Button("Submit selection");
submit.setOnAction(e ->
bookList.getSelectionModel().getSelectedItems().forEach(book -> System.out.println(book.getTitle())));
BorderPane root = new BorderPane(bookList, null, null, submit, null);
BorderPane.setAlignment(submit, Pos.CENTER);
BorderPane.setMargin(submit, new Insets(10));
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Book {
private final StringProperty title = new SimpleStringProperty() ;
public Book(String title) {
setTitle(title);
}
public final StringProperty titleProperty() {
return this.title;
}
public final java.lang.String getTitle() {
return this.titleProperty().get();
}
public final void setTitle(final java.lang.String title) {
this.titleProperty().set(title);
}
}
public static void main(String[] args) {
launch(args);
}
}
If for some reason you really want to implement this with check boxes, you can keep a Set<Book> representing the selected books, and update it when each check box is selected/unselected. Note this is similar to #user99370's answer, but is more robust as it avoids downcasting the (essentially unknown-type) userData to your data type.
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class BookSelection extends Application {
#Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10 ));
List<Book> books = IntStream.rangeClosed(1, 10).mapToObj(i -> new Book("Book "+i)).collect(Collectors.toList());
Set<Book> selectedBooks = new HashSet<>();
int row = 0 ;
for (Book book : books) {
CheckBox checkBox = new CheckBox();
checkBox.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
selectedBooks.add(book);
} else {
selectedBooks.remove(book);
}
});
grid.addRow(row, checkBox, new Label(book.getTitle()));
row++ ;
}
Button submit = new Button("Submit selection");
submit.setOnAction(e ->
selectedBooks.forEach(book -> System.out.println(book.getTitle())));
GridPane.setHalignment(submit, HPos.CENTER);
grid.add(submit, 0, row, 2, 1);
Scene scene = new Scene(grid, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Book {
private final StringProperty title = new SimpleStringProperty() ;
public Book(String title) {
setTitle(title);
}
public final StringProperty titleProperty() {
return this.title;
}
public final java.lang.String getTitle() {
return this.titleProperty().get();
}
public final void setTitle(final java.lang.String title) {
this.titleProperty().set(title);
}
}
public static void main(String[] args) {
launch(args);
}
}
This is just a simplified version of the accepted answer.
We can use setUserData(Object) to set data and getUserData() to retrieve the previously set data of any JavaFX node (including CheckBox).
Reference:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#setUserData-java.lang.Object-

My app crashes when i try to launch it

My app crashes when i tried to launch it.
I'm trying to learn how to make the app cycle through an array of strings and then repeats once everything has been picked. This is done with a press of a button. But it crashes when i try to launch it on my phone. Any suggestions or help would be greatly appreciated.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
TextView textOne = (TextView) findViewById(R.id.TextView1);
Button pushMe = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textOne.setText(pick());
}
List<String> myStrings = new ArrayList<String>() {{
add("b");
add("a");
add("z");
add("y");
add("x");
}};
List<String> dupeList = new ArrayList<String>() {{
addAll(myStrings);
}};
Random r = new Random();
public String pick() {
String retval = "";
int pos;
switch (dupeList.size()) {
case 1:
retval = dupeList.get(0);
dupeList.clear();
dupeList.addAll(myStrings);
return retval;
default:
pos = r.nextInt(dupeList.size());
retval = dupeList.get(pos);
dupeList.remove(pos);
return retval;
}
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//this opens another activity
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.RulesButton:
startActivity(new Intent(this, RulesActivity.class));
break;
}
return true;
}
}
found the problem. i just needed to change "TextView textOne...." to "final TextView textOne..." and place it below the onCreate method.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.TextView1);
Button pushMe = (Button) findViewById(R.id.button);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textOne.setText(pick());
}
List<String> myStrings = new ArrayList<String>() {{
add("b");
add("a");
add("z");
add("y");
add("x");
}};
List<String> dupeList = new ArrayList<String>() {{
addAll(myStrings);
}};
Random r = new Random();
public String pick() {
String retval = "";
int pos;
switch (dupeList.size()) {
case 1:
retval = dupeList.get(0);
dupeList.clear();
dupeList.addAll(myStrings);
return retval;
default:
pos = r.nextInt(dupeList.size());
retval = dupeList.get(pos);
dupeList.remove(pos);
return retval;
}
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//this opens another activity
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.RulesButton:
startActivity(new Intent(this, RulesActivity.class));
break;
}
return true;
}
}
Just for information as you are new in Android logs will help you more.
Log will be in eclipse tool (developing tool you are using) not on your device.
Change perspective to DDMS -> Go to LogCat.
There will be error logs in it.

Combobox refresh value and listview when object content change

I would like to update my combobox when the content of the object used to display text in combo changes.
Here is a sample:
package com.javafx.example.combobox;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class ComboboxSample extends Application {
class Sequence {
public StringProperty name = new SimpleStringProperty();
public Sequence(String name) {
super();
this.name.set(name);
}
#Override
public String toString() {
return "null";
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("ComboBoxSample");
ComboBox<Sequence> combo = new ComboBox<>();
combo.setItems(FXCollections.observableArrayList(
new Sequence("Toto"),
new Sequence("Titi")));
combo.getSelectionModel().selectFirst();
combo.setConverter(new StringConverter<ComboboxSample.Sequence>() {
#Override
public String toString(Sequence sequence) {
return sequence.name.get();
}
#Override
public Sequence fromString(String string) {
System.out.println("call fromString");
return null;
}
});
TextField text = new TextField();
Button renameButton = new Button("Rename");
renameButton.setOnAction(evt -> combo.getValue().name.set(text.getText()));
HBox root = new HBox(combo, text, renameButton);
HBox.setHgrow(text, Priority.ALWAYS);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String... args) {
launch(args);
}
}
The combobox contains objects with a property name. If i rename this property, the display do not change or sometimes it changes but not all the time. It is the standard behavior as the combobox update when the object changes, and not when its content changes.
How can i do to force the combobox to refresh its value and the listview on change?
Thanks
EDIT1:
Using a callback in an observaleList seems to be a solution.
package com.javafx.example.combobox;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class ComboboxSample extends Application {
ObservableList<Sequence> sequences;
class Sequence {
public StringProperty name = new SimpleStringProperty();
public Sequence(String name) {
super();
this.name.set(name);
}
#Override
public String toString() {
return "null";
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("ComboBoxSample");
Callback<Sequence, Observable[]> extractor = new Callback<Sequence, Observable[]>() {
#Override
public Observable[] call(Sequence s) {
return new Observable[] {s.name};
}
};
sequences = FXCollections.observableArrayList(extractor);
sequences.addAll(
new Sequence("Toto"),
new Sequence("Titi"));
ComboBox<Sequence> combo = new ComboBox<>();
combo.setItems(sequences);
combo.getSelectionModel().selectFirst();
combo.setConverter(new StringConverter<ComboboxSample.Sequence>() {
#Override
public String toString(Sequence sequence) {
return sequence.name.get();
}
#Override
public Sequence fromString(String string) {
System.out.println("call fromString");
return null;
}
});
combo.valueProperty().addListener((obs, oldValue, newValue) -> System.out.println("Change from " + oldValue.name.get() + " to " + newValue.name.get()));
TextField text = new TextField();
Button renameButton = new Button("Rename");
renameButton.setOnAction(evt -> {
combo.getValue().name.set(text.getText());
});
HBox root = new HBox(combo, text, renameButton);
HBox.setHgrow(text, Priority.ALWAYS);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String... args) {
launch(args);
}
}
Everytime a new value is added to the object list, set the combobox value again. Works for me. I did a small example to show this. Hope it is helpful
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ComboTest extends Application {
int i =0;
ObservableList<String> list = FXCollections.observableArrayList("A","B");
ComboBox<String> combo = new ComboBox();
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
combo.setPromptText("Testing combobox");
combo.setPrefWidth(300);
btn.setText("Add items to list");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
list.add(String.valueOf(i));
System.out.println("size of list " + list.size() );
i++;
combo.setItems(list);
}
});
combo.setItems(list);
VBox root = new VBox();
root.getChildren().addAll(btn,combo);
root.setSpacing(20);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

I want to convert csv file to xml

I want to convert csv file to xml and i want to send the converted xml file to a queue in activemq..Is there any sample code or any reference websites or blogs please help to find sample code for this program..
Use the Bindy and Xstream components. From http://workingwithqueues.blogspot.ch/2012/07/converting-csv-to-xml-with-camel-bindy.html (with a JMS endpoint instead of a file endpoint):
DataFormat bindy = new BindyCsvDataFormat("com.package.dto");
from("file://TEST?fileName=Employee.csv")
.unmarshal(bindy)
.marshal()
.xstream()
.to("jms:queue:FOO.BAR");
For connecting to JMS have a look at the JMS and ActiveMQ components.
package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Greeting {
#XmlElementWrapper(name = "Person")
#XmlElement(name = "persons")
private List<Person> persons;
public List<Person> getPerson() {
return persons;
}
public void setPerson(List<Person> persons) {
this.persons = persons;
}
}
========================================================================================
package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#CsvRecord(separator = ",")
public class Person {
#DataField(pos = 1)
#XmlElement
private int id;
#DataField(pos = 2)
#XmlElement
private String name;
#DataField(pos = 3)
#XmlElement
private int age;
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
======================================================================================
package org.mycompany.conversion;
import javax.xml.bind.JAXBContext;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.DataFormat;
public class CsvConversion {
public static void main(String[] args) throws Exception {
JaxbDataFormat xmlDataFormat = new JaxbDataFormat();
JAXBContext con = JAXBContext.newInstance(Greeting.class);
xmlDataFormat.setContext(con);
DataFormat bindy = new BindyCsvDataFormat(Person.class);
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:src/main/data/in/csv?noop=true").split().tokenize("\n").unmarshal(bindy)
// constanr(true):-aggregate all using same expression
.aggregate(constant(true), new AttachAggregation())
//mandatory after aggregate
.completionTimeout(100)//end after this gives problem
.marshal(xmlDataFormat).log("xml body is ${body}")
.to("file:src/main/data/in/xml?fileName=convertedXml.xml");// .aggregate(new
// AttachAggreagation());
}
});
context.start();
Thread.sleep(5000);
}
}
=========================================================================================
package org.mycompany.conversion;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
public class AttachAggregation implements AggregationStrategy {
List<Person> list = new ArrayList();
Greeting gre = new Greeting();
#Override
//person-address
// greeting-user
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
Person newBody1 = newExchange.getIn().getBody(Person.class);
list.add(newBody1);
return newExchange;
} else {
Person newBody2 = newExchange.getIn().getBody(Person.class);
list.add(newBody2);
gre.setPerson(list);
oldExchange.getIn().setBody(gre);
return oldExchange;
}
}
}

Resources