Viewing variables within a java object in the logs - java

I have a really simple wrapper class thats displayed below:
public class EmbedFoods {
private Collection<Food> foods;
public Collection<Food> getFoods() {
return foods;
}
public void setFoods(Collection<Foods> foods) {
this.foods = foods;
}
}
public class Food {
private String nutrition;
private String calories;
private String peanuts;
etc...
}
I get a list of "Food" for this EmbedFoods class by calling my API which returns a JSON string and I use Robospice for Spring Android to populate EmbedFoods automatically.
Now, I would like to view the object EmbedFoods in a human-readable format, preferably JSON.
If I go Log.e("embedFoods", EmbedFoods.toString());, it returns:
E/embedFoods [LModel.Food;#25ef9bbb
I can only see the model that is inside the embedFood class, but I cannot see variables that it comprises of. I was hoping to see a JSON string that shows all the variable of the java object printed in the logs.
How can I view all the variables that were set within the embedFood class other than debugging the line in which the embedFood is set in the app?

Well a way to do this can be done by overriding the toString method to display the correct values you want to see.
Something like
#Override
public String toString() {
Foods[] foods = collection.toArray();
String words = "[";
for (int i = 0; i < foods.length; i++) {
words = words + "{" + foods.nutrition + foods.etc + "}"
}
words = words + "]"
return words;
}
In your Embed foods.

Related

Java Class to access data from Adapter in Kotlin

Upgrading to Kotlin I came to the point of a Java Interface I was using to get data out of a Custom Recycler Adapter. Now in Kotlin I do not fully understand how to access the interface now. This is my Java Code I'm trying to get working in my Kotlin App.
btOK is a Button in my XML which collects all the selected Items my user has picked inside a ExpListView (You can find the full code here) and due the interface "SelectedDrink" I'm able to access the data.
Here the Button with the ClickListener:
btOk.setOnClickListener(view -> {
Button button = (Button) view;
msg = "Upload!\n";
ArrayList<SelectedDrink> selectedDrinks = expandableListAdapterDrinks.getOrderList();
Gson gson = new Gson();
for (SelectedDrink selectedDrink : selectedDrinks) {
msg += "aid=" + selectedDrink.content + "+qty=" + selectedDrink.qty + "\n";
}
final String jsonOrder = gson.toJson(selectedDrinks);
sendToServer(jsonOrder,sessionId);
}
});
this is the Interface:
public class SelectedDrink {
String content;
Double qty;
}
Now in Kotlin it gives me an error on these two boys here:
selectedDrink.content
selectedDrink.qty
that
"Cannot access: 'content/qty': it is public/package in
SelectedDrink"
I just don't understand what's the error about, neither how to fix it.
You can't access member variables directly in Java except public, You need getter/setter to access it.
Just create Getter methods
public class SelectedDrink {
private String content;
private Double qty;
public String getContent() {
return content;
}
public Double getQty() {
return qty;
}
}
Fields must be public
public class SelectedDrink {
public String content;
public Double qty;
}

Writing a method to return the string inside an object in Java

I'm really new to Java and programming in general (~3 weeks of experience) so sorry if this question is obvious for you guys. I tried searching for answers here but couldn't find any that fit my specific problem. And yeah it's for school, I'm not trying to hide it.
Here I'm supposed to write an object method that returns the string contained in the object oj, in reverse. I do know how to print a string in reverse, but I don't know how I should call the object since the method isn't supposed to have any parameters.
import java.util.Random;
public class Oma{
public static void main(String[] args){
final Random r = new Random();
final String[] v = "sininen punainen keltainen musta harmaa valkoinen purppura oranssi ruskea".split(" ");
final String[] e = "etana koira kissa possu sika marsu mursu hamsteri koala kenguru papukaija".split(" ");
OmaMerkkijono oj = new OmaMerkkijono(v[r.nextInt(v.length)] + " " + e[r.nextInt(e.length)]);
String reve = oj.printreverse();
System.out.println(reve);
}
}
class OmaMerkkijono{
private String jono;
public OmaMerkkijono(String jono){
this.jono=jono;
}
public String printreverse(){
//so here is my problem, i tried calling the object in different ways
//but none of them worked
return reversedstringthatdoesnotexist;
}
}
You just need to add this to your "printreverse" method :
new StringBuilder(this.jono).reverse().toString()
With this, when you call the method with the object "oj":
String reve = oj.printreverse();
After the previous line, "reve" must contain the value of the String reversed.
Olet hyvä, moi moi!
To revers a String use StringBuilder and reverse()
public String printreverse(){
return new StringBuilder(jono).reverse().toString();
}
To access private attributes from outside the class you use what are called accessors and mutators, aka getters and setters.
You just need a basic getter that also reverses the string.
public class MyObject {
private String objectName;
MyObject(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName; // returns objectName in order
}
public String getReversedObjectName() {
return new StringBuilder(objectName).reverse().toString();
}
public static void main(String[] args) {
MyObject teslaRoadster = new MyObject("Telsa Roadster");
System.out.println(teslaRoadster.getObjectName());
System.out.println(teslaRoadster.getReversedObjectName());
}
}
Output:
Telsa Roadster
retsdaoR asleT

Calling class methods from another class

I have created a class for a book with various field. I have then created a an array class for the library to store the book details. However I am not sure how to link them. I am looking to ultimately be able to search my array for all books with the same author surname for example. Should I somehow be calling methods from the book code to the library code?
This is my object class
public class Bookrecord
{
private int idnumber;
private String author;
private String title;
private String fiction;
public Bookrecord( int newidnumber, String newauthorname, String newtitlename, String newfictionname)
{
idnumber = newidnumber;
author = newauthorname;
title = newtitlename;
fiction = newfictionname;
}
public int getidnumber()
{
return idnumber;
}
public String getauthorname()
{
return author;
}
public String getfictianname()
{
return fiction;
}
public String gettitlename()
{
return title;
}
public void setidnumber(int insertidnumber)
{
idnumber = insertidnumber;
}
public void setauthor(String insertauthorname)
{
author = insertauthorname;
}
public void setfictian(String insertfictionname)
{
fiction = insertfictionname;
}
public void settitle(String inserttitlename)
{
title = inserttitlename;
}
public void printBookrecord()
{
System.out.println("The idNumber is " + idnumber + " The authorname is " + author + " The fictionname is " + fiction + " The titlename is " + title);
}
}
This is my array class
import java.util.ArrayList;
public class Libraryclass
{
// instance variables - replace the example below with your own
private ArrayList<String> member;
private ArrayList<String> bookrecord;
private ArrayList<String> libraryloan;
/**
* Constructor for objects of class Loan
*/
public Libraryclass()
{
// initialise instance variables
member = new ArrayList<String>();
bookrecord = new ArrayList<String>();
libraryloan = new ArrayList<String>();
}
public void addMember(String newMember)
{
member.add(newMember);
}
public void bookrecord(String newrecord)
{
bookrecord.add(newrecord);
}
public void libraryloan(String newloan)
{
libraryloan.add(newloan);
}
}
This reminds of an assignment for my first object oriented course. I get the feeling you also just started development and need some tips to get started.
Keep in mind we won't spoonfeed the answer to you since it is frowned upon to use stackoverflow to get complete answers to college assignments.
Your library or (arrayclass) should store an Array of BookRecord objects. Currently your arraylists hold String Objects. You should re-read what objects and classes are, to better understand the underlying concepts. You want your Library to hold an arraylist of bookrecords.
FYI: An Arraylists is a class available in java that allows the addition and removal of elements. It has some advantage related to arrays but also has some cons.
Your library object will use 'for loops' or 'iterators' to go through your arraylist of records. In order to implement features such as search for book you need to learn how to iterate over elements in an arraylist to search for strings. Google is your friend here. Here is an example what someone in your position should search for:
-searching through an arraylist, java
-iterating over arraylist, java
-how to use indexof java stack overflow
Finally, it makes more sense to call methods of the BookRecords from the Libraryclass. A bookRecord has one and only one Library. A library has many books. Hence, the library will hold references (contain) the books and will call getters and setters on the books.

Using Arrays.binarySearch on an array of Objects and looking for a String within the object

OK so I have the following Object class:
public class IntoleranceFood implements Comparable<IntoleranceFood>{
private int scoreInt;
public String foodName;
public IntoleranceFood(String food, int score) {
super();
this.foodName = food;
this.scoreInt = score;
}
//getters and setters
public String getFood() {
return foodName;
}
public void setFood(String food) {
this.foodName = food;
}
public int getScore() {
return scoreInt;
}
public void setScore(int score) {
this.scoreInt = score;
}
#Override
public String toString() {
return "Intolerance Food [Name=" + foodName + ", Score=" + scoreInt + "]";
}
#Override
public int compareTo(IntoleranceFood arg0) {
return toString().compareTo(arg0.toString());
}
}
And then in my Activity I have created an array for these objects to go into, and filled up the array with "IntoleranceFood" Objects:
int numFoodItemTypes = db.intoleranceFoodItemTypesTotal();
IntoleranceFood[] foodArray = new IntoleranceFood[numFoodItemTypes];
Cursor cAllFoodTypes = db.intoleranceFoodTypesList();
int foodItem = 0;
do{
foodArray[foodItem] = new IntoleranceFood(cAllFoodTypes.getString(0), 0);
foodItem++;
}while(cAllFoodTypes.moveToNext());
I managed to sort the array by implementing Comparable and the compareTo method in my Object class:
Arrays.sort(foodArray);
But I want to then search the array using binary search, and look for the position in the array where a certain Object with a specific food name (String) resides. But I dont know how to get the following code working, and specifically in terms of:
-binarySearch(Object[] array, Object value)
I don't know what to put in "Object value" so this:
Arrays.binarySearch(foodArray, "Cereal");
Is clearly wrong! But I'm not sure how to search the Object array for an Object containing the String food name "Cereal".
Thanks.
Yes so after the very useful reply below, I realsied what I need to be doing is:
IntoleranceFood searchOb = new IntoleranceFood("Cereal",0);
int searchIndex = Arrays.binarySearch(foodArray, searchOb);
And that works!
In my opinion your mistake is
Arrays.binarySearch(foodArray, "Cereal");
because "Cereal" is not the Object you are looking for and your array doesnt contain this object. The second parameter should be an instance of the IntoleranceFood class and "Cereal" is just a property of that class.
For your problem i would use a HashMap or another Map who fits your problem best!
Maybe this article will help you : How to sort a HashMap in Java

Print whole structure with single call (like JSON.stringify) in Java?

How to print any class instance in Java? Similar to JSON.stringify() in Javascript. Not necessary JSON, any format of output will do.
public class User {
public String name, password;
public int age;
public ArrayList<String> phones;
public static void login() {
//do something
}
}
User X = new User;
X.name = "john connor";
X.password = "skynet";
X.age = "33";
X.phones.add("1234567");
X.phones.add("7654321");
System.out.println(printClass(X))
Should output something like:
{ name:"john connor", password: "skynet", age: "33", phones:
["1234567", "7654321"], login: void function() }
You can use Apache's commons-lang's ToStringBuilder.reflectionToString
Of course, reflection is slow, so only do this with your test code. for normal use, please use eclipse's "Source" menu -> generate toString() (or intellij's generate toString()) which gives you a decent string.
There could be many ways to achieve what you need. Though i would be interested in why you need.
Override the toString() method.
see: http://www.javapractices.com/topic/TopicAction.do?Id=55
If the generation algorithm gets too long, then consider a separate class say UserPrettyPrinter.
public interface UserPrettyPrinter {
string print(User);
}
public class PrintUserInJSON implements UserPrettyPrinter {
string print(User user) {
//implement the algo here
}
}
you can also implement:
public class PrintUserInXML implements UserPrettyPrinter {
string print(User user) {
//implement the algo here
}
}
Either in conjugation to number-2 or as a standalone class, you can write
public class PrintObjectBasicAlgo {
String print(Object obj) {
/* i write pseudo code here. just ask if you cannot implement this
this would help: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
Class class = Obj.getClass();
Filed[] allVariables = class.getAllFieldsByReflection();
ArrayList<String> keys = new ArrayList<String>;
ArrayList<String> values = new ArrayList<String>;
for(Field field : allVariables) {
Object value = reflectionGetValueOfField( field, obj );
keys.add( field.getName());
values.add(value.toString());
}
now that you have the keys and values, you can generate a string in anyway you like
*/
}
}
You may see Visitor Pattern. it might be helpful.
You have two options here. The simple one is just to override the toString function for your class. I dont see why you dont do this really. In this case its as simple as
String toString(){
return "{ name:\""+name+", password: \""+passowrd....
}
The second option is to use reflection. This would be slightly (though not really) better if you had some sorta external class used for "printing classes". The pseudo code for that would be
StringBuilder s = new StringBuidler();
for(Field f : fields){
s.append(f.getName() + "\" :\"" + f.get()+ "\"");
}
return s.toString();
However this would be costly as reflection always is. Also if you just properly override the toString functions in the first place your printClass function could literally just be
String printClass(Object o){ return o.toString();}
Which of course again begs the question of why do you need a printClass function?
One option is to use Google Gson.
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
class Project {
private int year = 1987;
private String name = "ROBOCOP-1";
private boolean active = false;
private List<String> list = new ArrayList<String>() {
{
add("PROTECT THE INNOCENT");
add("UPHOLD THE LAW");
add("SERVE THE PUBLIC TRUST");
add("CLASSIFIED");
}
};
}
public class GsonExample {
public static void main(String[] args) {
Project obj = new Project();
Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println(gson.toJson(obj));
}
}

Categories

Resources