Variable not parsed as string - android

Well in my onActivityResult() method, i have a switch case condition like this:
if (resultList.getText().toString().toLowerCase().contains("Hi")){
Random random = new Random();
int numberOfMethods = 4;
switch(random.nextInt(numberOfMethods)) {
case 0:
String txthow = "Hi "+ data.toString()";
tts.speak(txthow, TextToSpeech.QUEUE_FLUSH, null);
break;
case 1:
String txthowdue = "How are you "+data.toString()+"?";
tts.speak(txthowdue, TextToSpeech.QUEUE_FLUSH, null);
break;
}
When my TTS repeat the data value it repeats something like intent\00n or anyway something not correct because that value would be for example a name David. i also declared private String data; but nothing change.

From the docs:
public String toString()
Returns a string representation of the
object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method. The toString
method for class Object returns a string consisting of the name of the
class of which the object is an instance, the at-sign character `#',
and the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
This means that toString() will return a String representation of the Object. In this case it is an Intent object. What is probably returning is a String with the name of the Class and its location in memory.
What you want to do is to get the desired value from the Intent using one of its getX().

Related

I got this error: java.lang.NumberFormatException: For input string: " "

Basically I got this error when I try to convert String to int and when there isn't any string I got problem but still "" should be null, or "" and I can't Handle it.
As an example I want to create contacts that only has two fields name and age, but only name is important for me.
public class Contact {
public String name;
public int age;
public Contact(String name) {
this.name = name;
}
public Contact() {
}
public Contact(String name,int age) {
this.name = name;
this.age=age
}
}
in the part of code for some reason I need user add new Contact and its not important to insert age.
after user submit I expect get new Contact.
EditText editName=findviewByid(r.id.edit_name);
EditText editAge=findviewByid(r.id.edit_age);
.
.
.
when user click the submit button :
String name = editName.getText().toString().trim();
String age = editAge.getText().toString().trim();
Contact contact =new (name,Integer.parseInt(age));
if user didn't input age we got this error
java.lang.NumberFormatException: For input string: ""
That is correct as per how parseInt works. You have to check the value you received from the text view for null or empty. You could do something like this:
String name = editName.getText().toString().trim();
String age = editAge.getText().toString().trim();
// You have to think about what value you want to give to your `age` variable in
// the case of `null`. This depends on you, I have given it a value of -1 just for
// demonstration. You also need to make sure that you only allow numeric input in
// your text field, or otherwise you need to make sure you can cast the provided
// input to an integer before using `parseInt`
int ageInt = !TextUtils.isEmpty(age) ? Integer.parseInt(age) : -1
Contact contact =new (name, ageInt);
You are seeing this error because of how Integer.parseInt works.
From the documentation:
parseInt
Added in API level 1 public static int parseInt (String s)
Parses the
string argument as a signed decimal integer.
The characters in the
string must all be decimal digits, except that the first character may
be an ASCII minus sign '-' ('\u002D') to indicate a negative value or
an ASCII plus sign '+' ('\u002B') to indicate a positive value.
The
resulting integer value is returned, exactly as if the argument and
the radix 10 were given as arguments to the parseInt(java.lang.String,
int) method.
Parameters s String: a String containing the int representation to be
parsed
Returns int the integer value represented by the argument in
decimal.
Throws NumberFormatException if the string does not contain a
parsable integer.
You MUST pass a string with a number in it to parseInt.

Overriding toString to return more than one variable

I have a Story class with the following variables, which correspondent to database columns:
int id;
String title;
int author_id;
String collection;
String body;
I have overridden toString() to return title like so:
#Override
public String toString() {
return title;
}
With this setup, I can successfully pull all story titles from my database.
But what if I also want to pull all story collections? Is it possible to return more than one variable in the override, or should I look at another approach?
The toString generates a String representation of your object as a human readable text, you can concatenate the result of many vars AS a String
return title + " " + collection;
Java does not support multiple returns out of the box. I think your best options would be to either:
Encapsulate the data that you want to return into a simple Java class, so you can set the fields and return it as one object.
In a function that returns your object, when you are getting ready to return:
MyReturnObject obj = new MyReturnObject();
obj.setTitle(title);
obj.setCollection(collection);
return obj;
Alternatively you can return the collections with some sort of delimiter, so that you can extract the data you want later on: return title + "|" + collections;
This will leave you with a String like: myTitle|collection1|collection2|collection3, which you can parse by String[] tokens = myString.split("|");

In Android, how to choose what items of an ArrayAdapter a ListView can display? [duplicate]

I have a class defined as follows:
public class Person {
private String name;
// constructor and getter/setter omitted
}
I tried to print an instance of my class:
System.out.println(myPerson);
but I got the following output: com.foo.Person#2f92e0f4.
A similar thing happened when I tried to print an array of Person objects:
Person[] people = //...
System.out.println(people);
I got the output: [Lcom.foo.Person;#28a418fc
What does this output mean? How do I change this output so it contains the name of my person? And how do I print collections of my objects?
Note: this is intended as a canonical Q&A about this subject.
Background
All Java objects have a toString() method, which is invoked when you try to print the object.
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object class (the superclass of all Java objects). The Object.toString() method returns a fairly ugly looking string, composed of the name of the class, an # symbol and the hashcode of the object in hexadecimal. The code for this looks like:
// Code of Object.toString()
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
A result such as com.foo.MyType#2f92e0f4 can therefore be explained as:
com.foo.MyType - the name of the class, i.e. the class is MyType in the package com.foo.
# - joins the string together
2f92e0f4 the hashcode of the object.
The name of array classes look a little different, which is explained well in the Javadocs for Class.getName(). For instance, [Ljava.lang.String means:
[ - an single-dimensional array (as opposed to [[ or [[[ etc.)
L - the array contains a class or interface
java.lang.String - the type of objects in the array
Customizing the Output
To print something different when you call System.out.println(myObject), you must override the toString() method in your own class. Here's a simple example:
public class Person {
private String name;
// constructors and other methods omitted
#Override
public String toString() {
return name;
}
}
Now if we print a Person, we see their name rather than com.foo.Person#12345678.
Bear in mind that toString() is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString() for our Person class might be:
#Override
public String toString() {
return getClass().getSimpleName() + "[name=" + name + "]";
}
Which would print, e.g., Person[name=Henry]. That's a really useful piece of data for debugging/testing.
If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}.
Auto-generating the Output
Many IDEs offer support for auto-generating a toString() method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.
Several popular Java libraries offer this feature as well. Some examples include:
ToStringBuilder from Apache Commons Lang
MoreObjects.ToStringHelper from Google Guava
#ToString annotation from Project Lombok
Printing groups of objects
So you've created a nice toString() for your class. What happens if that class is placed into an array or a collection?
Arrays
If you have an array of objects, you can call Arrays.toString() to produce a simple representation of the contents of the array. For instance, consider this array of Person objects:
Person[] people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));
// Prints: [Fred, Mike]
Note: this is a call to a static method called toString() in the Arrays class, which is different to what we've been discussing above.
If you have a multi-dimensional array, you can use Arrays.deepToString() to achieve the same sort of output.
Collections
Most collections will produce a pretty output based on calling .toString() on every element.
List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));
System.out.println(people);
// Prints [Alice, Bob]
So you just need to ensure your list elements define a nice toString() as discussed above.
I think apache provides a better util class which provides a function to get the string
ReflectionToStringBuilder.toString(object)
Every class in Java has the toString() method in it by default, which is called if you pass some object of that class to System.out.println(). By default, this call returns the className#hashcode of that object.
{
SomeClass sc = new SomeClass();
// Class # followed by hashcode of object in Hexadecimal
System.out.println(sc);
}
You can override the toString method of a class to get different output. See this example
class A {
String s = "I am just a object";
#Override
public String toString()
{
return s;
}
}
class B {
public static void main(String args[])
{
A obj = new A();
System.out.println(obj);
}
}
In Eclipse,
Go to your class,
Right click->source->Generate toString();
It will override the toString() method and will print the object of that class.
I prefer to use a utility function which uses GSON to de-serialize the Java object into JSON string.
/**
* This class provides basic/common functionalities to be applied on Java Objects.
*/
public final class ObjectUtils {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private ObjectUtils() {
throw new UnsupportedOperationException("Instantiation of this class is not permitted in case you are using reflection.");
}
/**
* This method is responsible for de-serializing the Java Object into Json String.
*
* #param object Object to be de-serialized.
* #return String
*/
public static String deserializeObjectToString(final Object object) {
return GSON.toJson(object);
}
}
In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:
public class test {
int a;
char b;
String c;
Test2 test2;
#Override
public String toString() {
return "test{" +
"a=" + a +
", b=" + b +
", c='" + c + '\'' +
", test2=" + test2 +
'}';
}
}
As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).
By default, every Object in Java has the toString() method which outputs the ObjectType#HashCode.
If you want more meaningfull information then you need to override the toString() method in your class.
public class Person {
private String name;
// constructor and getter/setter omitted
// overridding toString() to print name
public String toString(){
return name;
}
}
Now when you print the person object using System.out.prtinln(personObj); it will print the name of the person instead of the classname and hashcode.
In your second case when you are trying to print the array, it prints [Lcom.foo.Person;#28a418fc the Array type and it's hashcode.
If you want to print the person names, there are many ways.
You could write your own function that iterates each person and prints
void printPersonArray(Person[] persons){
for(Person person: persons){
System.out.println(person);
}
}
You could print it using Arrays.toString(). This seems the simplest to me.
System.out.println(Arrays.toString(persons));
System.out.println(Arrays.deepToString(persons)); // for nested arrays
You could print it the java 8 way (using streams and method reference).
Arrays.stream(persons).forEach(System.out::println);
There might be other ways as well. Hope this helps. :)
If you Directly print any object of Person It will the ClassName#HashCode to the Code.
in your case com.foo.Person#2f92e0f4 is getting printed . Where Person is a class to which object belongs and 2f92e0f4 is hashCode of the Object.
public class Person {
private String name;
public Person(String name){
this.name = name;
}
// getter/setter omitted
#override
public String toString(){
return name;
}
}
Now if you try to Use the object of Person then it will print the name
Class Test
{
public static void main(String... args){
Person obj = new Person("YourName");
System.out.println(obj.toString());
}
}
If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.
Using Lombok #Data annotation on class will provide getter, setter, toString and hashcode. Using Lombok is better as it handles boilerplate code.
For a "deep" toString() there is an alternative to the JSON based answers (Jackson, GSON, etc.): ReflectionToStringBuilder from the Apache Commons Lang 3 library, with RecursiveToStringStyle or MultilineRecursiveToStringStyle. Code example:
System.out.println("My object: " +
ReflectionToStringBuilder.toString(theObject, new RecursiveToStringStyle()));
Output examples:
// RecursiveToStringStyle
Person#7f54[name=Stephen,age=29,smoker=false,job=Job#43cd2[title=Manager]]
// MultilineRecursiveToStringStyle
Person#7f54[
name=Stephen,
age=29,
smoker=false,
job=Job#43cd2[
title=Manager
]
]
I managed to get this done using Jackson in Spring 5. Depending on the object it might not work in all cases.
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(yourObject));
the output would look like
{
"id" : 1,
"fieldOne" : "string"
}
Here are more examples using Jackson
If you use GSON instead It might look like
Gson gson = new Gson();
System.out.println(gson.toJson(yourObject));
If you are using project Lombok you could use the #ToString annotation and generate a standard toString() method without adding boilerplate.
import lombok.ToString;
#ToString
public class LoginDto {
private String user;
private String pass;
}
...
System.out.println(loginDto.toString());
// LoginDto(user=x#xxx.x, pass=xxxxx)

Can't readout ArrayList in Android

I deliver a ArrayList to another method, where I just wanna readout a specific String of the list.
public void pruefeWerHat(ArrayList<Teilnehmer> test){
System.out.println(test);
I get this in LogCat
"1 PeterPan 0 0, 2 Hansi 0 0"
now I just want to use the name, but if I say (after sysout)
String name = test.get(1);
the problem he said to is, that he cannot convert from Teilnehmer to String. I also tested Teilnehmer.get(1) but it doesn't work neither.
When you do
System.out.println(test);
the toString() method is automatically used. This method is in the Object class, so all objects in java can call this method.
When you do
String name = test.get(1);
the toString() method is not called on it's own, you have to call it yourself. To do this, simply use
String name = test.get(1).toString();
Also, if you want to change what is printed, you can overwrite the toString() method in your class.
#Overwrite
public String toString() {
String stringToPrint = "This string will be printed";
return stringToPrint;
}
Now when you do
System.out.println(test);
instead of seeing "1 PeterPan 0 0, 2 Hansi 0 0" you will see "This string will be printed" (or whatever you choose to add in your toString() implementation.
When you print test toString function is called so use this in your code
String name = test.get(1).toString();
What are the members of Teilnehmer?
You need to use something like
string name = (Teilnehmer)test[1].Name
where Name is the field you are trying to extract
The get(int index) method available to ArrayList returns type E. In this instance, it returns type Teilnehmer, which is obviously not a String. You can try and cast Teilnehmer (although probably not desirable) to String or simply call the .toString() method (e.g; test.get(1).toString()) inherited from type Object. Or, if desired, calling a method that returns a String. test.get(1).getNameAsString();
The reason you are allowed to call the type in System.out.println(Teilnehmer) is that println makes a call to the object's string representation:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}

How to parse a JSON response when type is also coming in response

I am getting following json response from a web service call.
as you can see, what type of value we will get in response is also coming in type object.
{"settings":[
{
"name":"name1",
"value":4,
"type":"int"
},
{
"name":"name2",
"value":false,
"type":"boolean"
},
{
"name":"name3",
"type":"array",
"value":[
{
"name":"name3"
}]}]}
how to parse this json?
how to store parsed value in database where i have a table with column names name, value, etc?
Edit:
currently i am converting all values to string because we can't add boolean to database.
private enum Type{
INT("int"), BOOLEAN("boolean"), ARRAY("array"),UNKNOWN_TYPE("");
private String mType;
Type(String type){
mType = type;
}
public static Type toEnum(String type){
for (Type value: Type.values()){
if(value.mType.equals(type)){
return value;
}
}
return UNKNOWN_TYPE;
}
}
String value = null;
switch (Type.toEnum(type)){
case INT:
value = String.valueOf(setting.getInt("value"));
break;
case BOOLEAN:
value = String.valueOf(setting.getBoolean("value"));
break;
case ARRAY:
parseJsonArray();
break;
}
is this the correct approach?
The usual way to deal with data items which could be any of a small known number of types is to use a tagged union. In Java, you'd write one something like this:
// CREATE TABLE dataFromJson (type ENUM('INT', 'BOOLEAN', 'STRING'),
// intval INT, boolval INT, stringval LONGTEXT);
class DataItem {
public enum Type { INT, BOOLEAN, STRING };
public Type m_type;
public int m_int;
public bool m_boolean;
public String m_string;
public PreparedStatement toInsertQuery(Connection conn) {
PreparedStatement ps = conn.prepareStatement("INSERT INTO dataFromJson VALUES (?, ?, ?, ?)");
ps.setString(1, m_type.toString());
if (m_type==INT) ps.setInt(2, m_int); else ps.setObject(2, null);
if (m_type==BOOLEAN) ps.setBoolean(3, m_boolean); else ps.setObject(3, null);
if (m_type==STRING) ps.setString(4, m_string); else ps.setObject(4, null);
return ps;
}
}
Dealing with JSON arrays (and objects) is much trickier; first you'll have to figure out how you want the data to be represented. Do you want the whole array as a string? do you want the first N elements of the array "exploded" into individual columns? do you want to store a single integer array_id, the primary key of a separate and more complicated table ArrayValues? There's all sorts of things you could do here... none of them terribly satisfying on a philosophical level. It depends on what you're going to want to do with the data later.

Categories

Resources