how see an array in logcat for android - java

I would like to log raw data like arrays in my logcat, so I know what is the output.
Lets say I have an array... like that:
File[] mp3List = ...
Log.v("test", mp3List);
Why can't I just log the array to console? How can I do it?

You can't log the array because it is just an Object. LogCat has no idea how to deal with it or display it in a way you want.
If each File object has a toString() method that displays the information that you want you can use:
Log.v(Arrays.toString(mp3List));
Otherwise you'll have to concatenate your own String to log:
StringBuilder sb = new StringBuilder();
for(File f : mp3List) {
sb.append(f.getName());
}
Log.v(sb.toString());

The reason why this doesn't work is simply because the 2nd argument of Log.v is a String not a File[]. Java strictly enforces argument types.
Update:
You can easily transform the information contained a File object into a String object. All java objects implement a toString(), which if I remember correctly returns a combination of the ClassName and the address of the object is located. However this usually doesn't contain useful information. So you need to define the conversion yourself.
Now to convert from File[] to String is more complicated because you when call a method on an array it works on the array object rather than on members of an array (which contains the information I suspect you care about). So calling mp3List.toString() will return a single string that describes the array object and not the information contained in the array.
So you'll probably want to write a method like this:
String fileArrayToString(File[] f){
String output = "";
String delimiter = "\n" // Can be new line \n tab \t etc...
for (int i=0; i<f.length; i++)
{
output = output + f[i].getPath() + delimiter;
}
return output;
}
And then call make your log call as follows:
Log.v("MyTag", fileArraytoString(mp3List);
However this might be hard to read.
I personally would do it like this:
for (int i=0; i<mp3List.legnth; i++)
Log.v("MyTag", Integer.toString(i) + ":" + mp3List[i].getPath());
Its simpler, produces cleaner log messages and is easier to understand what is going on as a programmer.

If you have a String array, you can just add toString() to it and it will be displayed.
For custom objects, you should override the toString() method and print what you want to see for that object. If you then have an array, the array will be printed with the output from the toString method.

Maybe I misunderstood, but I think its simply:
string sLog = "";
for(mp3List..)
{
sLog += mp3List[i].getName();
}
Log.v(sLog);
isnT it? Because, I suppose, when you try to print an array like that you ll get a log entry saying that mp3List is an System.Blah.Blah.File[] ..
Hope it helps..

I like one liners better:
for(File file:list) Log.d(TAG, "list: " + file.getPath());

Related

Return or Print StringBuilder? Java

I am a bit confused about the StringBuilder. It seems that when I print a StringBuilder, there it no need to add .toString() because it will automatically give me a string representation. However, when I return a StringBuilder object, I have to add the .toString(). Is that true? and why?
Also, I am bit confused about the following code:
package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("India ");
System.out.println("string = " + str);
// append character to the StringBuilder
str.append('!');
// convert to string object and print it
System.out.println("After append = " + str.toString());
str = new StringBuilder("Hi ");
System.out.println("string = " + str);
// append integer to the StringBuilder
str.append(123);
// convert to string object and print it
System.out.println("After append = " + str.toString());
}
}
For the different println, sometimes this code use toString and some other times it didn't. Why? I tried deleting the toString and the results are the same. Is it still necessary to use toString in println?
Thanks so much for helping a newbie out!
When you print an object to a print stream, the String representation of that object will be printed, hence toString is invoked.
Some classes override Object#toString, amongst which StringBuilder does.
Hence explicitly invoking toString for StringBuilder is unnecessary.
On the other hand, other objects don't override toString. For instance, arrays.
When you print an array, unless using a utility such as Arrays.toString, you're getting the array's class type # its hash code, as opposed to a human-readable representation of its contents.
From the documentation:
Note that println() prints a string builder, as in:
System.out.println(sb);
because sb.toString() is called implicitly, as it is with any other object in a println() invocation.
If you try to append an object to a string like this : "string = " + str, the toString() method is implicitly called.
So no, it does not matter, if you specify it.
Also the toString() method itself (even when you are not append it to string) calls the toString() method.
Therefore System.out.println(str) and System.out.println(str.toString()) gives same result.
The first thing you should know about Java is that we work with objects and that all objects inherit methods from the class Object: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
This class has a toString() method and since every object inherits this method it can always be called on every object. When you do not override it, it usually returns the physical address of the object.
Like stated in other answers, whenever a string is expected in println for instance and you pass an object it automatically calls the method which requires an Object (note the capital, we are talking about the class Object here), it will then use the toString method on the object passed along as parameter. The reason you get the string you want is because StringBuilder overrides the toString() method for you.
When you in your own code want to pass the string in your StringBuilder you have two options. You can either pass StringBuilder.toString() or change the return type to Object or StringBuilder and call toString() when you actually need it.
Hope this clarifies why you can just pass the object instead of the string.

use ints for prop.setProperty()

i'm trying to do a configurations file from an array of objects, where the properties are taken from a range of getters.
eg
prop.setProperty("Name", bugs[0].getName());
prop.setProperty("Species", bugs[0].getSpecies());
When i try, for example
prop.setProperty("Energy", bugs[0].getEnergy());
it says
The method setProperty(String, String) in the type Properties is not
applicable for the arguments (String, int)
How would I do method of setProperty(String, Int)?
EDIT*
Also, How do i write for an array of the objects, looping bugs[i] doesn't seem to work either.
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name", bugs[i].getName());
prop.setProperty("Species", bugs[i].getSpecies());
prop.setProperty("X", String.valueOf(bugs[i].getX()));
prop.setProperty("Y", String.valueOf(bugs[i].getY()));
prop.setProperty("Energy", String.valueOf(bugs[i].getEnergy()));
prop.setProperty("Symbol", String.valueOf(bugs[i].getId()));
}
// save properties to project root folder
prop.store(output, null);
How would i make it show the values for all the bugs, its only showing the last one?
bugs[0].getEnergy() is giving integer value to you and you are setting integer value insted of string that why exception came in your code.
Try
prop.setProperty("Energy", String.valueOf(bugs[0].getEnergy()));
For second part of Question :
How do i write for an array of the objects, looping bugs[i] doesn't
seem to work either.
Your loop showing last value because your key of property is same, you are not changing the key assigning all values to same key so it is giving you last value.
Try something , It will create new keys
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name"+i, bugs[i].getName());
prop.setProperty("Species"+i, bugs[i].getSpecies());
}
Mainly you can do this in two ways:
First way:
Overloading the setProperty(); metod. As it seems you decleared this method some where like this:
public void setProperty(String s1, String s2) {
// Doing some operations
}
Now, you can overload another method with the same name, but different signature to handle another kind of arguments (String - int), like this:
public void setProperty(String s1, int value) {
// Doing some operations suitable for this kind of method
}
Second way:
You can also easily convert the value of given integer to the string, by String.valueOf(); method, like this:
prop.setProperty("Energy", String.valueOf(bugs[0].getEnergy()));
EDITED:
In the loop you entered here, you're overwriting the values of prop object properties every time you loop through for.
First time the name of prop will be the bugs[0].getName(). In the next time, the last value will be deleted and bugs[1].getName() replaces it.
So if you want to store all of bugs array properties, you need an array of prop like objects (I don't know whats the type of prop but I assume it's Prop). So you need to write something like this:
Prop[] props = new Prop[bugs.length];
And then set properties of it's elements.
Also if you want to store all of properties in one object, you have to change the given key to setProperty(String, Int) method (as the String). So you can do something like this:
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name " + i, bugs[i].getName());
prop.setProperty("Species " + i, bugs[i].getSpecies());
// An so
}
prop.store(output, null);

array output not correct

I am using 2 classes and a bunch of methods to store something in an array then writing it to a file. After I write something to a file, instead of being of the var double,
this is my code:
public void storeArray(Quest1 a, Quest2 b, String filename) throws FileNotFoundException{
PrintWriter k = new PrintWriter(filename);
for(int i = 0; i < a.getDays(); i++)
{
k.println(b.storeArr(a));
}
k.close();
System.out.println("Written.");
}
Quest 1 is a class, Quest 2 is a class and String filename is just getting passed through.
After doing all that and putting the Quest3 object in my main menu.
I run the program, input all my values etc which get put into an array in the class Quest 2 and then I write them to a file.
I open that file to check if it has worked and i get this:
[D#264532ba
How do I fix that to get my double variables in the file?
Print out Arrays.toString instead of just print out the array (which invokes its toString inherited from Object):
k.println(Arrays.toString(b.storeArr(a)));
Or if you want some custom format, you can use StringUtils.join from Apache Commons. Or, perhaps just write a loop if you cannot use any dependencies.
The thing you output is the toString of the array, which is its type ([D) + # + its hash code (264532ba).
Arrays use the default implementation of toString() and that's why the output of the array is:
[D#264532ba
You have two options to print an array's content:
Iterate over each element.
Use Arrays.toString(array).
Explanation of the weird output
Let me explain the following code:
double[] array = new double[10];
System.out.println(array);
array is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The array's toString() is similar to Object's toString():
getClass().getName() + "#" + Integer.toHexString(hashCode());
So the output would be something like:
[D#756a7c99
where [ represnts the depth of the array, and D refers to double. 756a7c99 is the value returned from hashCode() as a hex number.
Read also Class.getName() JavaDoc.
if storeArr returns an Array, you could use Arrays.toString(b.storeArr(a))
This here:
k.println(b.storeArr(a));
You are printing b.storeArr(a) which is an array object.
Just do this:
PrintWriter k = new PrintWriter(filename);
for(int i = 0; i < a.getDays(); i++)
{
b.storeArr(a);
k.println(Arrays.toString(b));
}

Increment last letter of a string

Here's where I wish Java's String class had a replaceLast method, bu it doesn't and I'm getting the wrong results with my code.
I'm writing a program that searches a data structure for any items that match a string prefix. However, since I'm using an Iterator, the last item returned by the iter.next() call doesn't match the pattern, so I want to change the search string so that the last character of the query is increased by one letter. My testing code is returning [C#b82368 with this code and An as titleSearch:
public String changeLastCharacter(String titleSearch) {
char[] temp= titleSearch.toCharArray();
char lastLetter= temp[temp.length-1];
lastLetter++;
temp[temp.length-1]= lastLetter;
String newTitleSearch= temp.toString();
return newTitleSearch;
}
First, what is the cause of the output from this code?
Second, is there a better way to execute my solution?
You want:
newTitleSearch = new String(temp);
The toString method is not overridden for arrays; it's the usual Object.toString, intended for debugging. The above actually creates a string of the characters. An alternative is:
int len = titleSearch.length();
String allButLast = titleSearch.substring(0, len - 1);
newTitleSearch = allButLast + new Character(titleSearch.charAt(len - 1) + 1);
Whenever you see unexpected output like ....#<hex-digits>, the chances are that you are accidentally using toString() on some object whose class inherits the default implementation from Object.
The default toString() method returns a String whose value consists of the type name for the object combined with the object's "identity hash code" as hex digits. In your case the [C part is the type name for a char[] object. The '[' means "array of" and the 'C' means the char primitive type.
The rules for forming the type names used in the default toString() method are fully documented in the javadocs for java.lang.Class.getName().
Your problem is temp.toString(). Try String newTitleSearch = new String(temp); instead.
I figured this out by System.out.println(temp[0]+","+temp[1]); after temp[1] add been assigned to the incremented value. You could do this even easier by using your IDE's debugger.
Since the array was being assigned properly, the problem had to be in the toString().

What is the reverse of (ArrayList).toString for a Java ArrayList?

I am using the toString method of ArrayList to store ArrayList data into a String. My question is, how do I go the other way? Is there an existing method that will parse the data in the String instance back into an ArrayList?
The short answer is "No". There is no simple way to re-import an Object from a String, since certain type information is lost in the toString() serialization.
However, for specific formats, and specific (known) types, you should be able to write code to parse a String manually:
// Takes Strings like "[a, b, c]"
public List parse(String s) {
List output = new ArrayList();
String listString = s.substring(1, s.length() - 1); // chop off brackets
for (String token : new StringTokenizer(listString, ",")) {
output.add(token.trim());
}
return output;
}
Reconstituting objects from their serialized form is generally called deserialization
Here's a similar question:
Reverse (parse the output) of Arrays.toString(int[])
It depends on what you're storing in the ArrayList, and whether or not those objects are easily reconstructed from their String representations.
I would recommend using some standard format with a library for it instead.
JSON is probably the closest syntactically.
Alternatively some XML or serialization based solution could work too. It all depends on your needs of course.
What does the ArrayList consist of? As others said, it may be impossible in certain cases, but quite possible and guaranteed to work if:
each string representation of element of the array can be identified unambiguously (as it can be for example if the ArrayList consists of Integers)
there is a way to create an object of original type from its String representation. I find it most elegant to do this using a static method fromString
Of course, this mimics the whole (de)serialization framework.
Apache Commons ftw.
Arrays.asList(StringUtils.split(StringUtils.substringBetween("[1, 2, 3]", "[", "]"), ", "))
private List<String> parseStringToList(String column) {
List<String> output = new ArrayList<>();
String listString = column.substring(1, column.length() - 1);
StringTokenizer stringTokenizer = new StringTokenizer(listString,",");
while (stringTokenizer.hasMoreTokens()){
output.add(stringTokenizer.nextToken());
}
return output;
}
In case the above gives a compilation error. (Can't use forEach on StringTokenizer)

Categories

Resources