Android: EditText returning same value as contents - java

The method below is responsible for inserting a new record to a database table and it is called when a button is pressed. However the String input that is assigned the value of the contents of the EditText never seems to be assigned to the new contents whenever a new value is typed in.
As a result inserting a new record only works once.
Any suggestions why this happens would be appreciated.
public void insertRecord(View additionBut) {
System.out.println("NOW INSIDE THE INSERT RECORD");
input = addTextInput.getText().toString();
addTextInput.getText().clear();
System.out.println(input);
if (purpose.equals("ViewNovel")) {
md.addPiece(input, "0");
} else if (purpose.equals("ViewPlay")) {
md.addPiece(input, "1");
} else {
// whatever else
}
displayList();
}

You can also clear your EditText in another way, Try following way,
public void insertRecord(View additionBut) {
System.out.println("NOW INSIDE THE INSERT RECORD");
input = addTextInput.getText().toString();
addTextInput.setText("") // Change here
System.out.println(input);
if (purpose.equals("ViewNovel")) {
md.addPiece(input, "0");
} else if (purpose.equals("ViewPlay")) {
md.addPiece(input, "1");
} else {
// whatever else
}
displayList();
}

Place
displayList();
addTextInput.getText().clear(); //after displayList();
May be the reference is same. Because of that when you try to clear the edit text the value in input getting reflected. If so, try creating new String object with the value in the edit text box.

Related

Showing an Integer tableview in javaFx as a string

I am trying to show a tableview where when the value in the table is a integer like 1 for example I want to display a String. So far I tried to get the cellValue like this:
public void changeView() {
if(intervall.getCellFactory().call(intervall).equals(1)) {
intervall.getCellFactory().call(intervall).setText("Täglich");
}
}
And I am calling the method in my initialize after setting the cellvalue.
public void initializeTable() {
try {
// Ablesen
Statement pStatement = connection.createStatement();
flightList = FXCollections.observableArrayList();
ResultSet myRs = pStatement
.executeQuery("select * from fluglinie where fluggesellschaft =\"" + fluggesellschaft + "\"");
while (myRs.next()) {
flightList.add(new flightRouteAddModel(myRs.getString("startFlughafen"),
myRs.getString("zielFlughafen"), myRs.getString("startDatum"), myRs.getString("flugzeug"),
myRs.getInt("intervall"), myRs.getInt("anzahlEconomy"), myRs.getInt("anzahlBusiness"),
myRs.getFloat("preisEconomy"), myRs.getFloat("preisBusines"), myRs.getFloat("distanz")));
}
} catch (Exception e) {
System.out.println(e);
}
startAirport.setCellValueFactory(new PropertyValueFactory<>("startAirport"));
targetAirport.setCellValueFactory(new PropertyValueFactory<>("targetAirport"));
flightDate.setCellValueFactory(new PropertyValueFactory<>("flightDate"));
airplane.setCellValueFactory(new PropertyValueFactory<>("airPlane"));
intervall.setCellValueFactory(new PropertyValueFactory<>("intervall"));
seatCountEco.setCellValueFactory(new PropertyValueFactory<>("countEconomy"));
seatCountBus.setCellValueFactory(new PropertyValueFactory<>("countBusiness"));
priceEco.setCellValueFactory(new PropertyValueFactory<>("priceEconomy"));
priceBus.setCellValueFactory(new PropertyValueFactory<>("priceBusiness"));
distance.setCellValueFactory(new PropertyValueFactory<>("distance"));
table.setItems(flightList);
changeView();
}
But it is not working can someone maybe take a look at this? I know changing the db would be maybe a better solution but I kinda wanted to try this workaround
The cellFactory returns TableCells. Calling this yourself does not result in a cell that is part of the TableView (or becomes part of it). Any TableCell with a properly impelemented equals method never yields true, if 1 (or any other Integer) is passed.
Assuming you always want to display Täglich instead of 1, the way to go about this is using a custom cellFactory for this column:
intervall.setCellFactory(col -> new TableCell<flightRouteAddModel, Integer>() {
#Override
protected void updateItem(Integer item, boolean empty) {
String text = "";
if (item != null) {
switch(item) {
case 1:
text = "Täglich";
break;
case 7:
text = "Wöchentlich";
break;
default:
text = String.format("Alle %d Tage", item);
break;
}
}
setText(text);
}
});
BTW: Please learn about the java naming conventions. This makes the code easier to read for other people and it should make this more readable even for yourself, since all java APIs (that I know of) use these conventions: Type names start with an uppercase letter.

How to check if JRadioButtons are selected?

I tried
if(jRadioButton1.isSelected() ||(jRadioButton2.isSelected()) {
jGenderGroup.getSelection().getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.")
}
But controller doesn't stop after highlighted line it does go ahead to final line and throw NullPointerException
customers.setGender(jGenderGroup.getSelection().getActionCommand());
Where customers is POJO class.
How I can get rid of this?
try this :)
jRadioButton1.setActionCommand("Male");
jRadioButton2.setActionCommand("Female");
if(!jGenderGroup.isChecked()){
jLable1.setText("Please Select Gender");
}
if(jRadioButton1.isSelected())
{
//Male
}
else if(jRadioButton2.isSelected())
{
//Female
}
else
{
// no radio button has been selected
}
or alter your code like
if(jGenderGroup.getSelection() != null)
{
customer.setGender(jGenderGroup.getSelection().getActionCommand())
} else {
jGndrErrorLabel.setText("Select gender.")
}
I simply removed ButtonGroup jGenderGroup
and perform conditions for jRadioButton1 and jRadioButton2 at last instead of middle and as I had commented I can not set String gender = new String(); as
gender = jRadioButton1.getActionCommand();
Within conditional block because of POJO
So I just tricked that put it at the end like this :
String gender = new String();
if (jRadioButton1.isSelected()) {
gender = jRadioButton1.getActionCommand();
} else if (jRadioButton2.isSelected()) {
gender = jRadioButton2.getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.");
jGndrErrorLabel.setForeground(Color.red);
}
That's what I expected
Thanks for all of your time and efforts.

How do I keep asking the user for input if the input wasn't a number?

I'm making a cash register with an "other" option, which allows the user to add an amount through user input. I have done this with a JOptionPane, the "other" button code is the following:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt) {
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try {
double overigePrijs = Double.parseDouble(prijs);
if (overigePrijs > 0){
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
}
catch (Exception letter){
while (true){
prijs = JOptionPane.showInputDialog(this, "Vul a.u.b. alleen cijfers in.");
}
}
This while-loop will not close the JOptionPane, even when inputting numbers, how do I loop this correctly?
Edit after almost finishing my SE studies:
I was missing an if-statement in my while-loop. What I was trying to do was checking if the input of prijs were only numbers and if not, keep showing the dialog. I never got around to fixing this because it's an old project but I should have stated the motivation behind the code more clearly!
The question is not clear itself. What I assume that if the try part does not run as you wish, the JOptionPane should reopen and user should be prompted to do it again. If it is so, you can do the following:
Create a method:
private void doTheTask(){
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try{
//your task here.
}
catch (Exception letter){
//Call the method again.
doTheTask();
}
}
And call the method inside your action:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt){
doTheTask();
}
I suggest you a different approach in your code:
String prijs = "";
double overigePrijs = -1;
while (true) {
prijs = JOptionPane.showInputDialog(null, "Vul een bedrag in");
if (prijs != null) { // if user cancel the return will be null
try {
overigePrijs = Double.parseDouble(prijs);
break; // Exits the loop because you have a valid number
} catch (NumberFormatException ex) {
// Do nothing
}
} else {
// You can cancel here
}
// You can send a message to the user here about the invalid input
}
if (overigePrijs > 0) {
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
This code will loop until the user enters a valid number and then you can use after the while loop. Some improvement may be necessary like a cancel logic or change the message on the second time but the main idea is this.

How can I stop my arraylist being put multiple times into my shared preferences file?

The arraylist should be of the form, [{"12345"}, {"67890"}, etc...]
But when I close my app - I mean press the back button the amount of times it takes to get back to the Android home screen - and then restart it, I see MatchingContactsAsArrayListis[{"12345"}, {"67890"}, etc...,{"12345"}, {"67890"}, etc...]
If I close it twice, the arraylist comes up 3 times and so on, it keeps getting longer. It should just display each value once.
I thought editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit();
would take care of this.
Here's my code:
#Override
public void onResponse(String response) {
//convert the JSONArray, the response, to a string
String MatchingContactsAsString = response.toString();
//make an arraylist which will hold the phone_number part of the MatchingContacts string
MatchingContactsAsArrayList = new ArrayList<String>();
try {
JSONArray Object = new JSONArray(MatchingContactsAsString);
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
MatchingContactsAsArrayList.add(obj.getString("phone_number"));
}
SharedPreferences sharedPreferencesMatchingContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMatchingContactsAsArrayList = sharedPreferencesMatchingContactsAsArrayList.edit();
Gson gsonMatchingContactsAsArrayList = new Gson();
String jsonMatchingContactsAsArrayList = gsonMatchingContactsAsArrayList.toJson(MatchingContactsAsArrayList);
editorMatchingContactsAsArrayList.putString("MatchingContactsAsArrayList", jsonMatchingContactsAsArrayList);
editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit();
editorMatchingContactsAsArrayList.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
SharedPreferences.remove() method takes in the key that you used to save.
Which in this case is "MatchingContactsAsArrayList".
And actually, you don't need to use remove(), because putString() with an existing key, will override that value. Please make sure that the data from response is correct.

When I set a variable to JTextArea it has not value

I don't understand why a variable work in one part of code but in other part no. is the same variable, is referencied with the same value. this is my code
// Variables
String patologicos="";
String ginecologicos="";
String valuePanel="";
JTextArea ja;
here is built the constructor
public BaseHistorialPanelNoEditable(int typePanel){
// constructor
ja = new JTextArea();
ja.setPreferredSize(new Dimension(900, 280));
setBackground(Layout.pac_background);
ja.setEditable(false);
this.add(ja);
showInformation(typePanel);
}
Method to show some information
public void showInformation(int value){
// getting data from DB
getPatientData();
switch (value) {
case 1:
valuePanel = patologicos;
break;
case 2:
valuePanel = ginecologicos;
break;
default:
break;
}
// show message
Main.buildDialog(value + " " +valuePanel, "Mensaje informativo", JOptionPane.INFORMATION_MESSAGE);
// set a value to text area
ja.setText(valuePanel);
}
Method to get information from database
public void getPatientData(){
Main.readdb.select(
"select * from clinic where no_paciente=" +
Paciente.getPac_no());
if (Main.readdb.getNext()) {
patologicos = Main.readdb.getString("historia_clinic");
ginecologicos = Main.readdb.getString("gineco");
}
this fragment of code show a message
Main.buildDialog(value + " " +valuePanel, "Mensaje informativo", JOptionPane.INFORMATION_MESSAGE);
using the same variable it works.
why when I use the same variable one line after, it doesn't have any value?
ja.setText(valuePanel);
Thanks for your time.
Not sure but just an idea..
When you use setEditable(false).. It might be internal implementation that won't allow to set value..
try this:
ja.setEditable(true);
ja.setText(valuePanel);
ja.setEditable(false);
Hope this make sense..

Categories