JavaFx - is there any way to refresh whole treeview? - javafx

I'm newbie on java fx.
And I'm making an application with treeview and treeview has made by nested set model. So each treeitem has to have left, right data.(I made a treeitem like Treeitem>. Object has data(id, label name, left, right, etc) and String is label name to be shown at treeview.)
The problem is that whole treeitems have to be updated when I add a new treeitem(or delete treeitem). I already implemented whole data(the other treeitem's) to be updated on DB, but treeview still has data isn't updated.
I looked for the way to refresh treeview, but I just found user shouldn't use updateitem forcefully.
Is there any way or method to refresh whole treeview?
FYI. code below
Pair<LabelTreeItem,String> f = new Pair<>(new LabelTreeItem(1, "Root", 0, 0, "",0), "Root");
try {
f = new Pair<>(service.getRoot(), "Root");
} catch (SQLException e) {
System.out.println("Can't find Root Node");
e.printStackTrace();
}
TreeItem<Pair<LabelTreeItem,String>> root = createNode(f);
root.setExpanded(true);
treeView.setRoot(root);
treeView.setEditable(true);
treeView.setCellFactory(new Callback<TreeView<Pair<LabelTreeItem,String>>,TreeCell<Pair<LabelTreeItem,String>>>(){
#Override
public TreeCell<Pair<LabelTreeItem,String>> call(TreeView<Pair<LabelTreeItem,String>> p) {
return new TextFieldTreeCellImpl();
}
});
.....................................
private TreeItem<Pair<LabelTreeItem,String>> createNode(final Pair<LabelTreeItem,String> f) {
return new TreeItem<Pair<LabelTreeItem,String>>(f) {
private boolean isLeaf;
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;
#Override public ObservableList<TreeItem<Pair<LabelTreeItem,String>>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
super.getChildren().setAll(buildChildren(this));
}
return super.getChildren();
}
#Override public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
Pair<LabelTreeItem,String> f = getValue();
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
if(nodeRight-nodeLeft == 1) {
isLeaf = true;
System.out.println("this is leaf");
}
}
return isLeaf;
}
private ObservableList<TreeItem<Pair<LabelTreeItem,String>>> buildChildren(TreeItem<Pair<LabelTreeItem,String>> TreeItem) {
Pair<LabelTreeItem,String> f = TreeItem.getValue();
System.out.println("ID: "+f.getKey().getId());
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
try {
if (f != null && nodeRight-nodeLeft != 1) {
ArrayList<LabelTreeItem> item = new ArrayList<>();
item = service.getChildren(f.getKey().getLeft(), f.getKey().getRight(), f.getKey().getDepth());
ArrayList<Pair<LabelTreeItem,String>> itemList = new ArrayList<>();
for(int i=0; i<item.size(); i++) {
System.out.println("test : " + item.get(i).getLabel());
Pair<LabelTreeItem,String> pair = createPair(item.get(i), item.get(i).getLabel());
itemList.add(pair);
}
if(itemList.size() != 0) {
ObservableList<TreeItem<Pair<LabelTreeItem,String>>> children = FXCollections.observableArrayList();
for (Pair<LabelTreeItem,String> childNode : itemList) {
children.add(createNode(childNode));
}
return children;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FXCollections.emptyObservableList();
}
};
}
private Pair<LabelTreeItem, String> createPair(LabelTreeItem item, String name) {
return new Pair<>(item, name);
}
LabelTreeItem.java
public class LabelTreeItem {
private int id;
private String label;
private int left;
private int right;
private String comment;
private int depth;
public LabelTreeItem(int id, String label, int left, int right, String comment, int depth) {
this.id = id;
this.label = label;
this.left = left;
this.right = right;
this.comment = comment;
this.depth = depth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getLeft() {
return left;
}
public void setLeft(int left) {
this.left = left;
}
public int getRight() {
return right;
}
public void setRight(int right) {
this.right = right;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
}
TextFieldTreeCellImpl.java
public TextFieldTreeCellImpl() {
service = SqliteService.getInstance();
MenuItem addLabel = new MenuItem("Label add");
addMenu.getItems().add(addLabel);
addLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
getTreeItem().setExpanded(true);
LabelTreeItem newItem = null;
try {
id = getTreeItem().getValue().getKey().getId();
label = getTreeItem().getValue().getKey().getLabel();
depth = getTreeItem().getValue().getKey().getDepth()+1;
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
newItem = service.getData("New Label", id,depth);
TreeItem<Pair<LabelTreeItem,String>> newLabel = new TreeItem(createPair(newItem, newItem.getLabel()));
getTreeItem().getChildren().add(newLabel);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
MenuItem editLabel = new MenuItem("Label modify");
addMenu.getItems().add(editLabel);
editLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
startEdit();
}
});
MenuItem removeLabel = new MenuItem("Label delete");
addMenu.getItems().add(removeLabel);
removeLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
service.deleteData(left, right, (right-left)+1);
} catch (SQLException e) {
e.printStackTrace();
}
getTreeItem().getParent().getChildren().remove(getTreeItem());
System.out.println("Remove");
}
});
}
#Override
protected void updateItem(final Pair<LabelTreeItem, String> pair, boolean empty) {
super.updateItem(pair, empty);
if (!empty && pair != null) {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(pair.getKey().getLabel());
setGraphic(getTreeItem().getGraphic());
setContextMenu(addMenu);
}
} else {
setText(null);
setGraphic(null);
}
setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip(pair.getKey().getLabel());
tTip.uninstall(getTreeView(), tTip);
}
}
});
setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip();
tTip.setText(pair.getKey().getLabel()
+"\nComment : "+pair.getKey().getComment()
+"\nLeft : "+pair.getKey().getLeft()
+"\nRight : "+pair.getKey().getRight());
tTip.setFont(new Font("Arial", 16));
tTip.setStyle("-fx-background-color: grey;");
tTip.centerOnScreen();
tTip.install(getTreeView(), tTip);
}
}
});
}
DB Table
id|label|left|right|comment|depth

Related

I'm taking a picture, but it doesn't display in recyclerview

I have a screen that when someone click in a button appear a AlertDialog, and user can choose take a picture or choose from gallery. The code of gallery is working good, but the another isn't.
The idea is take a picture and display in a recyclerview.
Bellow I'll post the code:
public class NovoConteudoActivity extends AppCompatActivity{
private RecyclerView recyclerViewAddImage;
private ImageButton buttonAddNewImage;
private List<Imagem> listImagens = new ArrayList<>();
private AdapterImagem adapter;
private Imagem imagemConfigurada;
private ImageView imageDimension;
String currentImagePath = null;
private String[] permissoesNecessarias = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
private static final int SELECAO_CAMERA = 100;
private static final int SELECAO_GALERIA = 200;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_novo_conteudo);
//Inicializar Componentes:
inicalizarComponentes();
//Validar Permissões:
Permissao.validarPermissoes(permissoesNecessarias, this, 1);
//Set Adapter:
adapter = new AdapterImagem(listImagens, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
layoutManager.setStackFromEnd(true);
recyclerViewAddImage.setLayoutManager(layoutManager);
recyclerViewAddImage.setHasFixedSize(true);
recyclerViewAddImage.setAdapter(adapter);
//Evento de clique no Botão para adicionar imagem:
buttonAddNewImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
criarAlertDialog();
}
});
}
#Override
protected void onStart() {
super.onStart();
recyclerViewAddImage.smoothScrollToPosition(listImagens.size());
if (listImagens.size() >= 6){
buttonAddNewImage.setVisibility(View.GONE);
}else {
buttonAddNewImage.setVisibility(View.VISIBLE);
}
}
private void inicalizarComponentes() {
recyclerViewAddImage = findViewById(R.id.recyclerViewAddImage);
buttonAddNewImage = findViewById(R.id.buttonAddNewImage);
imageDimension = findViewById(R.id.imageDimension);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public void criarAlertDialog(){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Escolha uma opção");
alertDialog.setCancelable(true);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout linearLayoutVertical = new LinearLayout(this);
linearLayoutVertical.setOrientation(LinearLayout.VERTICAL);
linearLayoutVertical.setLayoutParams(params);
TextView textCamera = new TextView(this);
textCamera.setText("Tirar foto");
textCamera.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_photo_camera_black_24dp, 0,0,0);
textCamera.setCompoundDrawablePadding(5);
textCamera.setGravity(Gravity.CENTER_VERTICAL);
textCamera.setLayoutParams(params);
textCamera.setPadding(16,16,10,16);
linearLayoutVertical.addView(textCamera);
TextView textGaleria = new TextView(this);
textGaleria.setText("Escolher Existente...");
textGaleria.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_photo_black_24dp, 0,0,0);
textGaleria.setCompoundDrawablePadding(5);
textGaleria.setGravity(Gravity.CENTER_VERTICAL);
textGaleria.setLayoutParams(params);
textGaleria.setPadding(16,10,10,16);
linearLayoutVertical.addView(textGaleria);
TextView textCancelar = new TextView(this);
textCancelar.setText("Cancelar");
textCancelar.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_close_cinza_24dp, 0,0,0);
textCancelar.setCompoundDrawablePadding(5);
textCancelar.setGravity(Gravity.CENTER_VERTICAL);
textCancelar.setLayoutParams(params);
textCancelar.setPadding(16,10,10,16);
linearLayoutVertical.addView(textCancelar);
alertDialog.setView(linearLayoutVertical);
final AlertDialog dialog = alertDialog.create();
dialog.show();
textCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()) != null){
File imageFile = null;
try {
imageFile = getImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null){
Uri imageUri = FileProvider.getUriForFile(NovoConteudoActivity.this,
"com.gustavo.android.fileprovider",
imageFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, SELECAO_CAMERA);
}
}
dialog.dismiss();
}
});
textGaleria.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (i.resolveActivity(getPackageManager()) != null){
startActivityForResult(i, SELECAO_GALERIA);
}
dialog.dismiss();
}
});
textCancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
Bitmap imagem = null;
try {
switch (requestCode){
case SELECAO_CAMERA:
rotateImage(setReducedImageSize());
break;
case SELECAO_GALERIA:
Uri localImagemSelecionada = data.getData();
InputStream imageStream = getContentResolver().openInputStream(localImagemSelecionada);
imagem = BitmapFactory.decodeStream(imageStream);
if (imagem!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imagem);
listImagens.add(imagemConfigurada);
Log.d("Imagem", "onActivityResult: " + listImagens);
adapter.notifyDataSetChanged();
}
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
private File getImageFile()throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
currentImagePath = image.getAbsolutePath();
return image;
}
private Bitmap setReducedImageSize(){
int targetImageViewWidth = imageDimension.getWidth();
int targetImageViewHeight = imageDimension.getHeight();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(currentImagePath, bmOptions);
int cameraImageWidth = bmOptions.outWidth;
int cameraImageHeight = bmOptions.outHeight;
int scaleFactor = Math.min(cameraImageWidth/targetImageViewWidth, cameraImageHeight/targetImageViewHeight);
bmOptions.inSampleSize = scaleFactor;
bmOptions.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(currentImagePath, bmOptions);
}
private void rotateImage(Bitmap bitmap){
ExifInterface exifInterface = null;
try {
exifInterface = new ExifInterface(currentImagePath);
}catch (IOException e){
e.printStackTrace();
}
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
switch (orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(270);
break;
default:
}
Bitmap imageRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
if (imageRotate!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imageRotate);
listImagens.add(imagemConfigurada);
Log.d("Lista", "rotateImage: " + listImagens);
adapter.notifyDataSetChanged();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int permissaoResultado: grantResults){
if (permissaoResultado == PackageManager.PERMISSION_DENIED){
alertaValidacaoPermissao();
}
}
}
private void alertaValidacaoPermissao(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Permissões Negadas");
builder.setMessage("Para utilizar o app é necessário aceitar as permissões");
builder.setCancelable(false);
builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
Bellow the code of adapter:
public class AdapterImagem extends RecyclerView.Adapter<AdapterImagem.MyViewHolder> {
List <Imagem> list;
Context context;
public AdapterImagem(List<Imagem> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_add_photo, parent, false);
return new AdapterImagem.MyViewHolder(item);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Imagem imagem = list.get(position);
Glide
.with(context)
.load(imagem.getImagem())
.centerCrop()
.into(holder.newImagem);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView newImagem;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
newImagem = itemView.findViewById(R.id.newImage);
}
}
}
And the Class Imagem:
public class Imagem {
private Bitmap imagem;
public Imagem() {
}
public Imagem(Bitmap imagem) {
this.imagem = imagem;
}
public Bitmap getImagem() {
return imagem;
}
public void setImagem(Bitmap imagem) {
this.imagem = imagem;
}
}
Because you are setting an adapter with an empty list.
instead of initializing the adapter here:
//don't initialize here
adapter = new AdapterImagem(listImagens, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
.........
instead initialize here:
case SELECAO_GALERIA:
Uri localImagemSelecionada = data.getData();
InputStream imageStream = getContentResolver().openInputStream(localImagemSelecionada);
imagem = BitmapFactory.decodeStream(imageStream);
if (imagem!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imagem);
listImagens.add(imagemConfigurada);
//here
adapter = new AdapterImagem(listImagens,this);
//also set the adapter here
recyclerViewAddImage.setAdapter(adapter);
Log.d("Imagem", "onActivityResult: " + listImagens);
adapter.notifyDataSetChanged();
}
break;

Fragment in ViewPager shows nothing while returning from another fragment

I have a ViewPager in the fragment named FragmentHome, and the viewpager contains fragments. Am using FragmentStatePagerAdapter for this. When the fragmentHome loads first the fragments in Viewpager show perfectly. I have another fragment named FragmentCountryList to select a country, according to that country the fragments in the viewpager to be refreshed/updated. Now The problem is after selecting the country, the country fragment is popped and returns to the FragmentHome, but, there nothing is showing in the view pager, if we scrolls the second page(fragment) can be viewed then scrolls back the first page(fragment) can be viewed.
Am new with the FragmentStatePagerAdapter, so i couldn't rectify the reason for this problem. Please Help. The code i used gives below
public class FragmentHome extends WeGrabBaseFragment {
private static String TAG = "FragmentHome";
private HomeDealsDataClass homeDealsDataClass;//1, homeDealsDataClass2;
private ViewPager viewPagerHome;
private ImageView imgViewDealIndicator;
private OnCitySelectedListener onCitySelectedListener;
private FragPageAdapter fragAdapt;
private ArrayList<HomeDealsDataClass> arrayListHomeData;
private FragmentHomeDetails fragmentHomeDetails1,fragmentHomeDetails2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity = (WeGrabBaseActivity) this.getActivity();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater
.inflate(R.layout.fragment_home, container, false);
((WeGrabMainActivity) Activity).showBottomBar();
((WeGrabMainActivity) Activity).setShowActionBar();
((WeGrabMainActivity) Activity).setHeading(PrefUtil.getCityName(Activity));
((WeGrabMainActivity) Activity).defaultButtonState();
viewPagerHome = (ViewPager) v.findViewById(R.id.viewPagerHome);
viewPagerHome.setOffscreenPageLimit(2);
imgViewDealIndicator = (ImageView) v.findViewById(R.id.imgViewDealIndicator);
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
viewPagerHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
} else if (position == 1) {
Picasso.with(Activity).load(R.drawable.deals2).into(imgViewDealIndicator);
}
}
#Override
public void onPageSelected(int position) {
fragAdapt.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
onCitySelectedListener = new OnCitySelectedListener() {
#Override
public void onCitySelected() {
fetchFromWeb();
}
};
fetchFromWeb();
return v;
}
private void fetchFromWeb() {
if (Activity.isNetworkAvailable()) {
if (VolleyUtils.volleyEnabled) {
Activity.startSpinwheel(false, true);
JSONObject jsonObject = new JSONObject();
try {
if (!PrefUtil.isGPSLocation(Activity)) {
jsonObject.putOpt(AppConstants.COUNTRY_ID, PrefUtil.getCountryCode(Activity));
jsonObject.putOpt(AppConstants.CITY_ID, PrefUtil.getCityCode(Activity));
Log.e(TAG, "Not GPS Home : " + jsonObject.toString());
CommandFactory commandFactory = new CommandFactory();
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
} else {
/*jsonObject.putOpt(AppConstants.COUNTRY_NAME, PrefUtil.getCountryName(Activity));
jsonObject.putOpt(AppConstants.CITY_NAME, PrefUtil.getCityName(Activity));*/
jsonObject.putOpt(AppConstants.COUNTRY_ID, "112");
jsonObject.putOpt(AppConstants.CITY_ID, "6");
CommandFactory commandFactory = new CommandFactory();
Log.e(TAG, "In GPS Home : " + jsonObject.toString());
/*commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL_GPS, jsonObject);*/
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onHomeDetailsPageDataLoadedSuccessfully(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedSuccessfully(jsonObject);
Activity.stopSpinWheel();
try {
if (jsonObject != null) {
if (jsonObject != null) {
fragAdapt = new FragPageAdapter(getFragmentManager());
viewPagerHome.setAdapter(fragAdapt);
JSONArray jsonArray = jsonObject.getJSONArray(AppConstants.DEALS);
arrayListHomeData = new ArrayList<HomeDealsDataClass>();
if(jsonArray.length() > 0) {
viewPagerHome.setVisibility(View.VISIBLE);
for (int i = 0; i < jsonArray.length(); i++) {
arrayListHomeData.add(new HomeDealsDataClass(jsonArray.getJSONObject(i)));
}
fragAdapt.notifyDataSetChanged();
}else{
viewPagerHome.setVisibility(View.GONE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onHomeDetailsPageDataLoadedFailed(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedFailed(jsonObject);
Activity.stopSpinWheel();
}
private class FragPageAdapter extends FragmentStatePagerAdapter {
FragPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
Log.e(TAG,"Returns Fragment Home deals 1");
fragmentHomeDetails1 = FragmentHomeDetails.newInstance(arrayListHomeData.get(0));
return fragmentHomeDetails1;
case 1:
Log.e(TAG,"Returns Fragment Home deals 2");
fragmentHomeDetails2 = FragmentHomeDetails.newInstance(arrayListHomeData.get(1));
return fragmentHomeDetails2;
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if(arrayListHomeData != null)
return arrayListHomeData.size();
else
return 0;
}
}
}
I had this problem too before, after searching through SO answers, this helped me.
Basically try changing your PagerAdapter to extend FragmentStatePagerAdapter from FragmentPagerAdapter

Javafx Task - update progress from a method

In a JavaFX application I wish to update a status bar according to some work logic which I've implemented in an other class.
I can't figure out how to combine my desire to pass to work logic to the method (and not to write it inside the task) and to know about the work progress percentage.
This is an example of the controller with the Task:
public class FXMLDocumentController implements Initializable {
#FXML private Label label;
#FXML ProgressBar progressBar;
#FXML
private void handleButtonAction(ActionEvent event) {
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality.performWorkOnDb();
//updateProgress(1, 1);
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
progressBar.progressProperty().bind(myService.progressProperty());
myService.restart();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
This is the helper class:
public class DatabaseFunctionality {
public static void performWorkOnDb () throws InterruptedException {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
//Update progress
}
}
}
Thank you
You have a couple of options here. One is to do as Uluk suggests and expose an observable property in your DatabaseFunctionality class:
public class DatabaseFunctionality {
private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper();
public double getProgress() {
return progressProperty().get();
}
public ReadOnlyDoubleProperty progressProperty() {
return progress ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
progress.set(1.0*i / 100);
}
}
}
And now in your Task, you can observe that property and update the task's progress:
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.progressProperty().addListener((obs, oldProgress, newProgress) ->
updateProgress(newProgress.doubleValue(), 1));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
Another option (in case you don't want your data access object to depend on the JavaFX properties API) is to pass the data access object a callback to update the progress. A BiConsumer<Integer, Integer> would work for this:
public class DatabaseFunctionality {
private BiConsumer<Integer, Integer> progressUpdate ;
public void setProgressUpdate(BiConsumer<Integer, Integer> progressUpdate) {
this.progressUpdate = progressUpdate ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
if (progressUpdate != null) {
progressUpdate.accept(i, 100);
}
}
}
}
and then
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.setProgressUpdate((workDone, totalWork) ->
updateProgress(workDone, totalWork));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
public void initialize() {
Task<Void> task = new Task<>() {
#Override
protected Void call() {
try {
Double d = 0.0;
for (int i = 1; i <= 100; i++) {
Thread.sleep(100);
d = 1.0 * i / 100;
updateProgress(d, 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
task.progressProperty().addListener((obs, oldProgress, newProgress) -> {
System.out.println((newProgress.doubleValue() * 100) + "% completed");
});
new Thread(task).start();
}

Datas repeated in my ListFragment

I encounter a problem with my ListFragment provided by Volley Library and hosted by a ViewPager ! So when i swipe follow Fragment and back to my previous ListFragment, datas are repeated again ! Why ? Please help me !
This my code :
Code for bind ListFragment:
public class AllConferencesFragment extends ListFragment {
// Variables
final String URL_ALL_CONFERENCES = "http://192.168.43.246/android_christEvent/all_events_conference.php";
//final String URL_ALL_CONFERENCES = "http://7avecdieu.org/android_christEvent/all_events_conference.php";
//private static String TAG = ConferenceActivity.class.getSimpleName();
ListView listView;
View view;
List<Event> eventLists = new ArrayList<Event>();
CustomListEventsAdapter customListEventsAdapter;
CircularProgressView circularProgressView;
// Contructeur
public AllConferencesFragment() {
}
// Creation du fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Creation de la vue
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.conferences_frag, container, false);
circularProgressView = (CircularProgressView) view.findViewById(R.id.circular_progress);
return view;
}
// Activité gestionnaire du fragment créé
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
circularProgressView.setVisibility(View.VISIBLE);
circularProgressView.startAnimation();
getListView();
//listView = (ListView) view.findViewById(R.id.list);
customListEventsAdapter = new CustomListEventsAdapter(getActivity(), eventLists);
//listView.setAdapter(customListEventsAdapter);
setListAdapter(customListEventsAdapter);
// On check si la cache est vide
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_ALL_CONFERENCES);
if (entry != null) {
circularProgressView.setVisibility(View.VISIBLE);
// Parcours des données de la cache de cette url passée en parametre
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
else {
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
// Au Cliq sur un iem
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), DetailsEventsActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
/**
* Parsing json reponse and passing the data to event view list adapter
**/
private void parseJsonFeed(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray("events");
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
Event evt = new Event();
evt.setPriceEvent(eventObj.getString("event_price"));
// Image might be null sometimes
String image = eventObj.isNull("event_thumb") ? null : eventObj.getString("event_thumb");
evt.setThumbEvent(image);
evt.setNameEvent(eventObj.getString("event_name"));
evt.setPlaceEvent(eventObj.getString("event_place"));
evt.setHourEvent(eventObj.getString("event_hour"));
evt.setDateEvent(eventObj.getString("event_date"));
eventLists.add(evt);
}
circularProgressView.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
//progressBar.setVisibility(View.GONE);
}
}
Code for Volley Application :
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if(mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// Set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
My parseJsonEvent :
private void parseJsonEvent(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray(TAG_EVENTS);
// Loop Json node
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
// Create event object
Event evt = new Event();
evt.setIdEvent(eventObj.getInt(TAG_EVENT_ID));
evt.setDateEvent(eventObj.getString(TAG_EVENT_DATE));
evt.setPriceEvent(eventObj.getString(TAG_EVENT_PRICE));
evt.setNameEvent(eventObj.getString(TAG_EVENT_NAME));
evt.setCountryEvent(eventObj.getString(TAG_EVENT_COUNTRY));
evt.setPlaceEvent(eventObj.getString(TAG_EVENT_PLACE));
evt.setTypeEvent(eventObj.getString(TAG_EVENT_TYPE));
// event thumbnail
String eventUrl = eventObj.isNull(TAG_EVENT_THUMB) ? null : eventObj.getString(TAG_EVENT_THUMB);
evt.setThumbEvent(eventUrl);
// Adding in the list object
eventList.add(evt);
// notify list view to adding
}
adapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
My Main Activity :
public class ConferenceActivity extends AppCompatActivity {
private Toolbar toolbarConference;
private TabLayout tabLayoutConference;
private ViewPager viewPagerConference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbarConference = (Toolbar) findViewById(R.id.toolbar_conference);
setSupportActionBar(toolbarConference);
viewPagerConference = (ViewPager) findViewById(R.id.viewpager_conference);
setupViewPager(viewPagerConference);
tabLayoutConference = (TabLayout) findViewById(R.id.tabs_conference);
tabLayoutConference.setupWithViewPager(viewPagerConference);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new AllEventsConferenceFragments(), "TOUS");
adapter.addFragment(new ThisWeekFragment(), "AUJOURD'HUI");
adapter.addFragment(new TodayEventFragment(), "CETTE SEMAINE");
adapter.addFragment(new AllEventsConferenceFragments(), "SEMAINE PROCHAINE");
adapter.addFragment(new ThisWeekFragment(), "CE MOIS CI");
adapter.addFragment(new TodayEventFragment(), "MOIS PROCHAIN");
adapter.addFragment(new AllEventsConferenceFragments(), "ANNEE EN COURS");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class AllConferencesFragment extends ListFragment {
private boolean loaded = false;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(loaded){
return;
}
loaded = true;
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}

Same asked a different way this time the StringConverter is acting up

Books.java
`final class Books extends Group {
private TableView table = new TableView();
private ObservableList<Book> data;
//private ObservableList<Person> plist;
final HBox hb = new HBox();
final TextField Title = new TextField();
final TextField Author = new TextField();
final TextField Publisher = new TextField();
final TextField Copywrite = new TextField();
final TextField ISBN = new TextField();
final Boolean CheckedOut = false;
final Label Whom;
final Button addButton = new Button("Add");
Boolean FirstRead = true;
//StringConverter<Person> converter;
public final class Book {
private final SimpleStringProperty title;
private final SimpleStringProperty author;
private final SimpleStringProperty publisher;
private final SimpleStringProperty copywrite;
private final SimpleStringProperty isbn;
private final BooleanProperty checkedout;
private final SimpleStringProperty who;
Book(String Titl, String Auth, String Publ,
String Cpywrit, String IsBn, Boolean ChkdOut, String WHO) {
this.title = new SimpleStringProperty(Titl);
this.author = new SimpleStringProperty(Auth);
this.publisher = new SimpleStringProperty(Publ);
this.copywrite = new SimpleStringProperty(Cpywrit);
this.isbn = new SimpleStringProperty(IsBn);
this.checkedout = new SimpleBooleanProperty(ChkdOut);
this.who = new SimpleStringProperty(WHO);
}
public boolean isCheckedOut() {
return checkedout.get();
}
public void setCheckedOut(boolean international) {
this.checkedout.set(international);
}
public BooleanProperty isCheckedOutProperty() {
return checkedout;
}
public String getTitle() {
return title.get();
}
public void setTitle(String Title) {
title.set(Title);
}
public String getAuthor() {
return author.get();
}
public void setAutor(String Author) {
author.set(Author);
}
public String getPublisher() {
return publisher.get();
}
public void setPublisher(String Publisher) {
publisher.set(Publisher);
}
public String getCopywrite() {
return copywrite.get();
}
public void setCopywrite(String Copywrite) {
copywrite.set(Copywrite);
}
public String getIsbn() {
return isbn.get();
}
public void setIsbn(String ISBN) {
isbn.set(ISBN);
}
public Boolean getIo() {
return checkedout.get();
}
public void setIo(Boolean CheckedOut) {
checkedout.set(CheckedOut);
}
public String getWho() {
return who.get();
}
public void setWho(String Who) {
who.set(Who);
}
public String isWhoProperty() {
return getWho();
}
}
public Books(final File User) throws IOException {
this.Whom = new Label("inLibrary");
this.data = FXCollections.<Book>observableArrayList(
(Book bk) -> new Observable[]{bk.isCheckedOutProperty()
});
PhoneList list = new PhoneList(User);
final Label label = new Label("Book List");
label.setFont(new Font("Arial", 20));
table.setPrefSize(600, 400);
table.setEditable(true);
TableColumn nameCol = bookName();
TableColumn authorCol = bookAuthor();
TableColumn publisherCol = bookPublisher();
TableColumn copywriteCol = bookCopywrite();
TableColumn isbnCol = bookISBN();
TableColumn<Book, Boolean> ioCol = ioCol();
///// START work area
final TableColumn whoCol;
whoCol = new TableColumn<>("Who to");
whoCol.setMinWidth(100);
whoCol.setEditable(true);
whoCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("who"));
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist));
////////////////////////////////////////////////////////////////////////////////
//whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));
//whoCol.setCellFactory(ComboBoxTableCell.<String, Person>forTableColumn(converter, plist));
//whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist));
/*
whoCol.setOnEditCommit((TableColumn.CellEditEvent<Book, String> t) -> {
((Book) t.getTableView().getItems().get(
t.getTablePosition().getRow()))
.setWho(t.getNewValue());
try {
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
});
*/
//// END work area
AddBook(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol, User);
data.addListener((javafx.collections.ListChangeListener.Change<? extends Book> change) -> {
while (change.next()) {
if (change.wasUpdated() && FirstRead != true) {
try {
System.out.println("List changed");
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
getChildren().addAll(vbox);
try {
readFile(User);
} catch (Exception ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
private TableColumn<Book, Boolean> ioCol() {
final TableColumn<Book, Boolean> ioCol = new TableColumn<>("In/Out");
ioCol.setMinWidth(50);
ioCol.setEditable(true);
ioCol.setCellValueFactory(new PropertyValueFactory<>("isCheckedOut"));
final Callback<TableColumn<Book, Boolean>, TableCell<Book, Boolean>> iocellFactory = CheckBoxTableCell.forTableColumn(ioCol);
ioCol.setCellFactory((TableColumn<Book, Boolean> column) -> {
TableCell<Book, Boolean> iocell = iocellFactory.call(column);
iocell.setAlignment(Pos.CENTER);
return iocell;
});
ioCol.setCellFactory(iocellFactory);
return ioCol;
}
private TableColumn bookISBN() {
//Column ISBN Number
TableColumn isbnCol = new TableColumn("ISBN #");
isbnCol.setMinWidth(100);
isbnCol.setCellValueFactory(
new PropertyValueFactory<>("isbn"));
isbnCol.setCellFactory(TextFieldTableCell.forTableColumn());
return isbnCol;
}
private TableColumn bookCopywrite() {
//Column Copywrite
TableColumn copywriteCol = new TableColumn("Copywrite");
copywriteCol.setMinWidth(100);
copywriteCol.setCellValueFactory(
new PropertyValueFactory<>("copywrite"));
copywriteCol.setCellFactory(TextFieldTableCell.forTableColumn());
return copywriteCol;
}
private TableColumn bookPublisher() {
//Column Publisher
TableColumn publisherCol = new TableColumn("Publisher");
publisherCol.setMinWidth(100);
publisherCol.setCellValueFactory(
new PropertyValueFactory<>("publisher"));
publisherCol.setCellFactory(TextFieldTableCell.forTableColumn());
return publisherCol;
}
private TableColumn bookAuthor() {
//Column Author
TableColumn authorCol = new TableColumn("Author");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(
new PropertyValueFactory<>("author"));
authorCol.setCellFactory(TextFieldTableCell.forTableColumn());
return authorCol;
}
private TableColumn bookName() {
// Column Name
TableColumn nameCol = new TableColumn("Title");
nameCol.setMaxWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<>("title"));
nameCol.setCellFactory(TextFieldTableCell.forTableColumn());
return nameCol;
}
private void AddBook(TableColumn nameCol, TableColumn authorCol, TableColumn publisherCol,
TableColumn copywriteCol, TableColumn isbnCol, TableColumn ioCol, TableColumn whoCol, final File User) {
table.setItems(data);
table.getColumns().addAll(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol);
addButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
addBook();
try {
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void addBook() {
data.add(new Book(
Title.getText(),
Author.getText(),
Publisher.getText(),
Copywrite.getText(),
ISBN.getText(),
CheckedOut,
Whom.getText()
));
Title.clear();
Author.clear();
Publisher.clear();
Copywrite.clear();
ISBN.clear();
}
});
hb.getChildren().addAll(Title, Author, Publisher,
Copywrite, ISBN, addButton);
hb.setSpacing(10);
Title.setPromptText("Tile of Book");
Title.setMaxWidth(nameCol.getPrefWidth());
Author.setMaxWidth(authorCol.getPrefWidth());
Author.setPromptText("Author");
Publisher.setMaxWidth(publisherCol.getPrefWidth());
Publisher.setPromptText("Publisher");
Copywrite.setMaxWidth(copywriteCol.getPrefWidth());
Copywrite.setPromptText("Year Copywrite");
ISBN.setMaxWidth(isbnCol.getPrefWidth());
ISBN.setPromptText("ISBN #");
}
private void writeFile(File User) throws IOException {
File file = new File(User + "/Books.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
if (table.getItems() != null) {
data.stream().map((data1) -> {
if (data1.getTitle().equals("")) {
data1.setTitle("No_Title");
}
return data1;
}).map((data1) -> {
if (data1.getAuthor().equals("")) {
data1.setAutor("No_Author");
}
return data1;
}).map((data1) -> {
if (data1.getPublisher().equals("")) {
data1.setPublisher("No_Publisher");
}
return data1;
}).map((data1) -> {
if (data1.getCopywrite().equals("")) {
data1.setCopywrite("No_Copywrite");
}
return data1;
}).map((data1) -> {
if (data1.getIsbn().equals("")) {
data1.setIsbn("No_ISBN");
}
return data1;
}).map((data1) -> {
if (data1.getWho().equals("")) {
data1.setWho("InLibrary");
}
return data1;
}).map((data1) -> {
outFile.println(data1.getTitle());
return data1;
}).map((data1) -> {
outFile.println(data1.getAuthor());
return data1;
}).map((data1) -> {
outFile.println(data1.getPublisher());
return data1;
}).map((data1) -> {
outFile.println(data1.getCopywrite());
return data1;
}).map((data1) -> {
outFile.println(data1.getIsbn());
return data1;
}).map((data1) -> {
outFile.println(data1.getIo());
return data1;
}).forEach((data1) -> {
outFile.println(data1.getWho());
});
outFile.close();
}
}
private void readFile(File User) throws Exception {
try {
String name, author, publisher, copywrite, isbn, whom;
Boolean InOut;
try (Scanner inFile = new Scanner(new File(User + "/Books.txt"))) {
while (inFile.hasNextLine()) {
name = inFile.next();
author = inFile.next();
publisher = inFile.next();
copywrite = inFile.next();
isbn = inFile.next();
InOut = inFile.nextBoolean();
whom = inFile.next();
data.add(new Book(name, author, publisher, copywrite,
isbn, InOut, whom));
}
}
table.setItems(data);
} //insert catch statements
catch (FileNotFoundException exception) {
System.out.println("File not found");
} catch (ArrayIndexOutOfBoundsException AIOOBexception) {
System.out.println("Array Index is out of bounds");
} catch (IllegalArgumentException IAexception) {
System.out.println("Divide by zero error");
} catch (NoSuchElementException NAexception) {
}
FirstRead = false;
}
}`
PhoneList.java
`final class PhoneList extends Group {
private TableView table = new TableView();
final ObservableList<Person> phonelist = FXCollections.observableArrayList();
final HBox hb = new HBox();
public PhoneList(final File User) {
final Label label = new Label("Phone List");
label.setFont(new Font("Arial", 20));
table.setEditable(true);
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMaxWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<>("firstName"));
firstNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
firstNameCol.setOnEditCommit(
new EventHandler<CellEditEvent<Person, String>>() {
#Override
public void handle(CellEditEvent<Person, String> t) {
try {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setFirstName(t.getNewValue());
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(
new PropertyValueFactory<>("lastName"));
lastNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
lastNameCol.setOnEditCommit(
new EventHandler<CellEditEvent<Person, String>>() {
#Override
public void handle(CellEditEvent<Person, String> t) {
try {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setLastName(t.getNewValue());
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
TableColumn phoneNumCol = new TableColumn("Phone Number");
phoneNumCol.setMinWidth(100);
phoneNumCol.setCellValueFactory(
new PropertyValueFactory<>("phoneNum"));
phoneNumCol.setCellFactory(TextFieldTableCell.forTableColumn());
phoneNumCol.setOnEditCommit(
new EventHandler<CellEditEvent<Person, String>>() {
#Override
public void handle(CellEditEvent<Person, String> t) {
try {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setPhoneNum(t.getNewValue());
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
TableColumn emailCol = new TableColumn("Email");
emailCol.setMinWidth(120);
emailCol.setCellValueFactory(
new PropertyValueFactory<>("email"));
emailCol.setCellFactory(TextFieldTableCell.forTableColumn());
emailCol.setOnEditCommit(
new EventHandler<CellEditEvent<Person, String>>() {
#Override
public void handle(CellEditEvent<Person, String> t) {
try {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setEmail(t.getNewValue());
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
table.setItems(phonelist);
table.getColumns().addAll(firstNameCol, lastNameCol, phoneNumCol, emailCol);
final TextField addFirstName = new TextField();
addFirstName.setPromptText("First Name");
addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
final TextField addLastName = new TextField();
addLastName.setMaxWidth(lastNameCol.getPrefWidth());
addLastName.setPromptText("Last Name");
final TextField addPhoneNum = new TextField();
addPhoneNum.setMaxWidth(lastNameCol.getPrefWidth());
addPhoneNum.setPromptText("Phone Number");
final TextField addEmail = new TextField();
//addEmail.setMaxWidth(emailCol.getPrefWidth());
addEmail.setPrefWidth(175);
addEmail.setPromptText("Email");
final Button addButton = new Button("Add");
addButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
try {
phonelist.add(new Person(
addFirstName.getText(),
addLastName.getText(),
addPhoneNum.getText(),
addEmail.getText()));
addFirstName.clear();
addLastName.clear();
addPhoneNum.clear();
addEmail.clear();
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
hb.getChildren().addAll(addFirstName, addLastName, addPhoneNum, addEmail, addButton);
hb.setSpacing(3);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
getChildren().addAll(vbox);
try {
readFile(User);
} catch (Exception ex) {
Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void readFile(File User) throws Exception {
try {
String fN, lN, pNum, eMail;
try (Scanner inFile = new Scanner(new File(User + "/PhoneList.txt"))) {
while (inFile.hasNextLine()) {
fN = inFile.next();
lN = inFile.next();
pNum = inFile.next();
eMail = inFile.next();
phonelist.add(new Person(fN, lN, pNum, eMail));
}
}
table.setItems(phonelist);
} //insert catch statements
catch (FileNotFoundException exception) {
System.out.println("File not found");
} catch (ArrayIndexOutOfBoundsException AIOOBexception) {
System.out.println("Array Index is out of bounds");
} catch (IllegalArgumentException IAexception) {
System.out.println("Divide by zero error");
} catch (NoSuchElementException NAexception) {
}
}
public void writeFile(File User) throws IOException {
File file = new File(User + "/PhoneList.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
if (table.getItems() != null) {
for (int i = 0; i < phonelist.size(); i++) {
outFile.println(phonelist.get(i).getFirstName());
outFile.println(phonelist.get(i).getLastName());
if (phonelist.get(i).getPhoneNum().equals("")) {
phonelist.get(i).setPhoneNum("No_Phone");
}
if (phonelist.get(i).getEmail().equals("")) {
phonelist.get(i).setEmail("No_Email");
}
outFile.println(phonelist.get(i).getPhoneNum());
outFile.println(phonelist.get(i).getEmail());
}
outFile.close();
}
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty phoneNum;
private final SimpleStringProperty eMail;
Person(String fName, String lName, String pNum, String email) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.phoneNum = new SimpleStringProperty(pNum);
this.eMail = new SimpleStringProperty(email);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lName) {
lastName.set(lName);
}
public String getPhoneNum() {
return phoneNum.get();
}
public void setPhoneNum(String pNum) {
phoneNum.set(pNum);
}
public String getEmail() {
return eMail.get();
}
public void setEmail(String email) {
eMail.set(email);
}
public String getName() {
String Name = getFirstName() + "_" + getLastName();
return Name;
}
public Observable isWhoProperty() {
return firstName;
}
#Override
public String toString() {
String Name = getFirstName() + "_" + getLastName();
return Name;
}
}
class EditingCell extends TableCell<Person, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(textField.getText());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem();
}
}
}`
With these two I do have the ComboBoxTableCell working properly... Thank you very much. Now its time to figure out how to save it to the .txt file. Hmm can't think of anything more to say - make sure that you also get MykeZ folder and its contents. but this version has all it needs to work so you can add new data if necessary.
`final TableColumn<Book, Person> whoCol;
whoCol = new TableColumn<>("Who to");
whoCol.setMinWidth(100);
whoCol.setEditable(true);
whoCol.setCellValueFactory(new PropertyValueFactory("who"));
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist));
whoCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Book, Person>>() {
public void handle(TableColumn.CellEditEvent<Book, Person> evt) {
try {
evt.getRowValue().setWho(evt.getNewValue().getName());
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
});`
And were finished Please give your self credit in this postings for the answer, am very happy thank you your the best
I don't really understand the question, but you should be doing something like this.
edit: from looking briefly at your code you might be trying to do something like this;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class ComboBoxTable extends Application {
#Override
public void start(Stage stage) {
ObservableList<Person> persons = FXCollections.observableArrayList();
persons.addAll(new Person("Jack"),new Person("Jill"),new Person("John"));
ObservableList<Book> books = FXCollections.observableArrayList();
for (int i=1;i<5;i++)books.add(new Book(i*100,new Person("wrong guy")));
StringConverter<Person> cvrt = new StringConverter<Person>(){
#Override
public String toString(Person person) {
return person.getName();
}
#Override
public Person fromString(String string) {
return null;
}
};
TableView<Book> tv = new TableView(books);
tv.setEditable(true);
tv.getSelectionModel().setCellSelectionEnabled(true);
TableColumn<Book, Integer> numCol = new TableColumn("Book Num");
numCol.setCellValueFactory(new PropertyValueFactory("num"));
TableColumn<Book, Person> nameCol = new TableColumn("Name");
nameCol.setCellValueFactory(new PropertyValueFactory("person"));
nameCol.setCellFactory(ComboBoxTableCell.<Book, Person>forTableColumn(cvrt,persons));
tv.getColumns().addAll(numCol, nameCol);
StackPane root = new StackPane(tv);
Scene scene = new Scene(root, 300, 250);
stage.setScene(scene);
stage.show();
}
public class Person{
SimpleStringProperty name;
public Person(String name) {
this.name = new SimpleStringProperty(name);
}
public SimpleStringProperty nameProperty() {
return name;
}
public String getName() {
return name.get();
}
//in simple cases you can just do this and not use a string converter
#Override
public String toString(){
return name.get();
}
}
public class Book{
SimpleIntegerProperty num;
SimpleObjectProperty<Person> person;
public Book(int num, Person person) {
this.num = new SimpleIntegerProperty(num);
this.person = new SimpleObjectProperty<>(person);
}
public SimpleIntegerProperty numProperty() {
return num;
}
public SimpleObjectProperty<Person> personProperty() {
return person;
}
}
}
Look at the TableView, TableColumn, and ComboBoxTableCell documentation and pay attention to the <S,T>
The reason you're getting a reference to Person is because the ComboBox doesn't know how to convert it to a string. I put a simple bit of code to override the toString() method for the Person class. If you don't specify a StringConverter it won't know how to convert and just uses toString() for objects.
Edit again: Look at your Book class, you have StringProperty who and you're trying to store a person in that field. Look at my code and I use an ObjectProperty<Person>.
You can do it your way but override the toString() in the Person class like in my example and don't use a StringConverter.
#Override
public String toString(){
return name.get();
}
Then make your TableColumn like this and use the type <Book, Person>
TableColumn<Book, Person> whoCol = new TableColumn<>("Who to");
whoCol.setMinWidth(100);
//editable is true for columns by default.
whoCol.setCellValueFactory(new PropertyValueFactory("who"));
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(p.phonelist));
whoCol.setOnEditCommit((evt) -> {
evt.getRowValue().setWho(evt.getNewValue().getName());
});
I made an onEditCommit so the Book class will know how to store the Person info.

Resources