Error Cannot be cast string to integer - java

I can't change the EditTextPreference value from string to int. I've done in this way:
WifiOnOffValue = (EditTextPreference) findPreference("WifiOnOffValue");
String value = WifiOnOffValue.getText().toString();
if(value != null && !value.isEmpty()) {
try {
vedit = Integer.parseInt(value);
}
catch (NumberFormatException ex) {
ex.printStackTrace();
vedit = 0;
}
}
And I get the error java.lang.Integer cannot be cast to java lang.String... I need convert the value of my EditTextPreference in integer. Thanks
Log:
Code:
//-- Edittext Wifi
WifiOnOffValue = (EditTextPreference) findPreference("WifiOnOffValue");
String value = WifiOnOffValue.getText().toString().trim();
if(value!=null && !value.isEmpty()){
try{
vedit = Integer.parseInt(value);
} catch (NumberFormatException ex) {
ex.printStackTrace();
vedit=0;
}
}
Solved.. this was the solution: ClassCastException in PreferenceActivity seems that it stored wrong values.. Now i can start the app and seems goes well.. The solution to me was simply uninstall and reinstall the application.. so strange. Thanks to everybody anyway

Could you check the type of variable vedit? Is wrongly declared as String?

try to use String value = WifiOnOffValue.getText().toString().trim() and log out to see what the value of value is

Should'nt it be
WifiOnOffValue = (EditTextPreference) getPreferenceManager().findPreference("WifiOnOffValue");

Related

Using Jackcess to retrieve numeric values stored in a text field gives ClassCastException

I am working with Jackcess to read and categorize an access database. It's simply meant to open the database, loop through each line, and print out individual row data to the console which meet certain conditions. It works fine, except for when I try to read numeric values. My code is below. (This code is built into a Swing GUI and gets executed when a jbutton is pressed.)
if (inv == null) { // Check to see if inventory file has been set. If not, then set it to the default reference path.
inv = rPath;
}
if (inventoryFile.exists()) { // Check to see if the reference path exists.
List<String> testTypes = jList1.getSelectedValuesList();
List<String> evalTypes = jList3.getSelectedValuesList();
List<String> grainTypes = jList2.getSelectedValuesList();
StringBuilder sb = new StringBuilder();
for (int i=0; i<=evalTypes.size()-1; i++) {
if (i<evalTypes.size()-1) {
sb.append(evalTypes.get(i)).append(" ");
}
else {
sb.append(evalTypes.get(i));
}
}
String evalType = sb.toString();
try (Database db = DatabaseBuilder.open(new File(inv));) {
Table sampleList = db.getTable("NTEP SAMPLES LIST");
Cursor cursor = CursorBuilder.createCursor(sampleList);
for (int i=0; i<=testTypes.size()-1; i++) {
if ("Sample Volume".equals(testTypes.get(i))) {
if (grainTypes.size() == 1 && "HRW".equals(grainTypes.get(0))) {
switch (evalType) {
case "GMM":
for (Row row : sampleList){
if (null != row.getString("CURRENTGAC")) {}
if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}
}
break;
case "NIRT":
// some conditional code
break;
case "TW":
// some more code
break;
}
}
else {
JOptionPane.showMessageDialog(null, "Only HRW samples can be used for the selected test(s).", "Error", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
}
catch (IOException ex) {
Logger.getLogger(SampleFilterGUI.class.getName()).log(Level.SEVERE, null, ex);
}
When the code is run I get the following error:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
The following condition looks to be what is throwing the error.
row.getDouble("CURRENTGAC")>=12.00
It appears that when the data is read from the database, the program is reading everything as a string, even though some fields are numeric. I was attempting to cast this field as a double, but java doesn't seem to like that. I have tried using the Double.parseDouble() and Double.valueOf() commands to try converting the value (as mentioned here) but without success.
My question is, how can I convert these fields to numeric values? Is trying to type cast the way to go, or is there a different method I'm not aware of? You will also notice in the code that I created a cursor, but am not using it. The original plan was to use it for navigating through the database, but I found some example code from the jackcess webpage and decided to use that instead. Not sure if that was the right move or not, but it seemed like a simpler solution. Any help is much appreciated. Thanks.
EDIT:
To ensure the program was reading a string value from my database, I input the following code
row.get("CURRENTGAC").getClass().getName()
The output was java.lang.String, so this confirms that it is a string. As was suggested, I changed the following code
case "GMM":
for (Row row : sampleList){
if (null != row.get("CURRENTGAC"))
//System.out.println(row.get("CURRENTGAC").getClass().getName());
System.out.println(String.format("|%s|", row.getString("CURRENTGAC")));
/*if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00 && row.getDouble("CURRENTGAC")<=14.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}*/
}
break;
The ouput to the console from these changes is below
|9.85|
|11.76|
|9.57|
|12.98|
|10.43|
|13.08|
|10.53|
|11.46|
...
This output, although looks numeric, is still of the string type. So when I tried to run it with my conditional statement (which is commented out in the updated sample code) I still get the same java.lang.ClassCastException error that I was getting before.
Jackcess does not return all values as strings. It will retrieve the fields (columns) of a table as the appropriate Java type for that Access field type. For example, with a test table named "Table1" ...
ID DoubleField TextField
-- ----------- ---------
1 1.23 4.56
... the following Java code ...
Table t = db.getTable("Table1");
for (Row r : t) {
Object o;
Double d;
String fieldName;
fieldName = "DoubleField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %f",
o));
System.out.println();
fieldName = "TextField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %s",
o));
try {
d = r.getDouble(fieldName);
} catch (Exception x) {
System.out.println(String.format(
"r.getDouble(\"%s\") failed - %s: %s",
fieldName,
x.getClass().getName(),
x.getMessage()));
}
try {
d = Double.parseDouble(r.getString(fieldName));
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) succeeded. Value: %f",
fieldName,
d));
} catch (Exception x) {
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) failed: %s",
fieldName,
x.getClass().getName()));
}
System.out.println();
}
... produces:
DoubleField comes back as: java.lang.Double
Value: 1.230000
TextField comes back as: java.lang.String
Value: 4.56
r.getDouble("TextField") failed - java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
Double.parseDouble(r.getString("TextField")) succeeded. Value: 4.560000
If you are unable to get Double.parseDouble() to parse the string values from your database then either
they contain "funny characters" that are not apparent from the samples you posted, or
you're doing it wrong.
Additional information re: your sample file
Jackcess is returning CURRENTGAC as String because it is a Text field in the table:
The following Java code ...
Table t = db.getTable("NTEP SAMPLES LIST");
int countNotNull = 0;
int countAtLeast12 = 0;
for (Row r : t) {
String s = r.getString("CURRENTGAC");
if (s != null) {
countNotNull++;
Double d = Double.parseDouble(s);
if (d >= 12.00) {
countAtLeast12++;
}
}
}
System.out.println(String.format(
"Scan complete. Found %d non-null CURRENTGAC values, %d of which were >= 12.00.",
countNotNull,
countAtLeast12));
... produces ...
Scan complete. Found 100 non-null CURRENTGAC values, 62 of which were >= 12.00.

Convert String to Int with Integer.parseInt don't works

I'm working with JavaEE i need to convert this: request.getParameter("id") to int. The value of request.getParameter("id") is "9" (String).
When I'm trying to convert to int I have
java.lang.NumberFormatException
I've tried java.lang.Integer.parseInt(request.getParameter("id")) and request.getParameter("id",10) but it donsen't works...
Any solutions? Thank you.
A complete full proof code would be
String idString = request.getParameter("id");
if(idString != null) {
try {
System.out.println(idString.trim()); // print to verify
int idInt = Integer.parseInt(idString.trim());
}
catch(NumberFormatException nbe) {
nbe.printStackTrace();
}
}
First you need to check whether String returned by getParameter() is null or not then check whether it is empty ("") String or not then use Integer.parseInt().
String id = request.getParameter("id");
if(null != id && !("".equals(id))) {
try {
int number = Integer.parseInt(id.trim());
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}

Converting String to java.net.URI

First apologies, I'm mainly a Perl person doing some Java. I've read some literature but can't get this to give me the signature that I need:
logger.debug("Entered addRelationships");
boolean rval = true;
for(int i=0;i<relationships.length;i++)
{
URI converted_uri ;
try {
converted_uri = new URI("relationships[i].datatype") ;
} catch (URISyntaxException e) {
logger.error("Error converting datatype", e);
return rval = false ;
}
boolean r = addRelationship(context, relationships[i].subject,
relationships[i].predicate, relationships[i].object,
relationships[i].isLiteral, converted_uri);
if(r==false)
{
rval = false;
}
}
return rval;
}
The resulting error is:
addRelationship(org.fcrepo.server.Context,java.lang.String,java.lang.String,java.lang.String,boolean,java.lang.String) in org.fcrepo.server.management.DefaultManagement cannot be applied to (org.fcrepo.server.Context,java.lang.String,java.lang.String,java.lang.String,boolean,java.net.URI)
It seems to me that converted_uri is a URI at the end of this? datatype was a String in the previous release, so no gymnastics were required!
Just remove the qoutes:
converted_uri = new URI(relationships[i].datatype) ;
When you are using quotes, exactly as in perl you are dealing with string literal. If you want to refer to variable you have to mention it in code directly.
While #AlexR pointed out another problem in your code, it's not the cause of the problem you identified in your question.
You had a compile error, and an error in the syntax of the URI will only show up at runtime like the one that #AlexR identified.
The problem you have is that you are trying to pass a URI as the last argument, but the method addRelationship expects a String as the last argument. That's what the error says.
(The first part of the error says what the signature of the method is in reality, as you see it ends in java.lang.String, while the second part of the error says what type of data you are trying to give to the method, and as you see that one ends in java.net.URI)
So it seems that the URI was not changed as you expected; it still needs a String.
Solution is to change your code to:
boolean rval = true;
for(int i = 0; i < relationships.length; i++)
{
boolean r = addRelationship(context, relationships[i].subject,
relationships[i].predicate, relationships[i].object,
relationships[i].isLiteral, relationships[i].datatype);
if (!r)
{
rval = false;
}
}
return rval;

Null Pointer Exception from JCalander Combobox

My Java Application produces Null Pointer Exception from JCalander Combobox. I tried to catch the error. But that didnt work. Can someone assist me to fix this. Please.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1106)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:955)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:948)
at java.text.DateFormat.format(DateFormat.java:336)
at org.freixas.jcalendar.JCalendarCombo.paramString(JCalendarCombo.java:780)
at java.awt.Component.toString(Component.java:8095)
tbmodel = (DefaultTableModel)tblItmQty.getModel();
System.out.println(calRecvDate.getDate());
try{
if(calRecvDate.getDate()==null){ // Error
JOptionPane.showMessageDialog(null, "Please Select Shippment Received Date");
calRecvDate.requestFocus();
}else if(txtShipSs.getText().isEmpty()){
////////////////////////////////////////////////////////////////
if (inputValidate() == true) {
try {
String shipId = txtShipId.getText();
String invID = txtInvoice.getText();
String shipSs = txtShipSs.getText();
String address = txtNtfAddress.getText();
String sipper = txtAShipper.getText();
String vessal = txtVessal.getText();
Date rcvDate = calRecvDate.getDate(); // Jcalander
String consignee = txtConsigne.getText();
ArrayList<ShippmentItems> shipItems = new ArrayList<ShippmentItems>();
tbmodel = (DefaultTableModel) tblItmQty.getModel();
for (int i = 0; i < tbmodel.getRowCount(); i++) {
String itmcode = (String) tbmodel.getValueAt(i, 0);
String itmName = (String) tbmodel.getValueAt(i, 1);
int qty = (int) tbmodel.getValueAt(i, 2);
ShippmentItems shpItems = new ShippmentItems(shipId, itmcode, itmName, qty);
shipItems.add(shpItems);
}
Since this throws the NPE:
calRecvDate.getDate()==null
The calRecvDate variable is null, and you will either need to check if it's null before using it, or make sure that it isn't null by tracing back in your code to where you think you've initialized it and fix the problem (since it isn't initialized).
To check if it's null, you could do:
if (calRecvDate != null) {
// use the calRecvDate variable here
} else {
// initialize the calRecvDate variable here
// or perhaps better, display a JOptionPane error message to the user
// that the date hasn't been selected, and exit this method by calling return:
return;
}
Again, don't use try/catch blocks to handle NullPointerExceptions.

Better handling of number format exception in android

I've got the following code snippet that I'm thinking of refactoring to a more abstract application exception handler but I want to make sure I've got it as tidy as possible first
Any suggestions on how to improve this code or make it more resuable
int id = -1;
final StringBuilder errorMessage = new StringBuilder("Bad Input Value: ");
try {
id = Integer.parseInt(edtId.getText().toString());
} catch (final NumberFormatException e) {
errorMessage.append("Failed to parse id " + e.getMessage());
}
if (id < 0) {
errorToast(errorMessage.toString());
} else {
//go ahead an retreive values from database knowing the id has been parsed
//correctly to a positive int.
}
Why pre-assign id to a magic number?
try {
int id=Integer.parseInt(edtId.getText().toString());
//go on as normal
} catch (NumberFormatException e) {
//handle error
}

Categories