Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output an object to the Logcat console

I would like to take a look at an object, similar to a print_r(an_object) in php, or a console.log(an_object) in javascript (in browser), but for Android.

I tried this

public void a_method( SomeClass the_arg )
{ 
    Log.d( "an_id" , the_arg );
}

This generates an error message:

Error:(23, 10) error: no suitable method found for d(String,View) method Log.d(String,String,Throwable) is not applicable (actual and formal argument lists differ in length) method Log.d(String,String) is not applicable (actual argument View cannot be converted to String by method invocation conversion)

like image 267
dsdsdsdsd Avatar asked Apr 23 '16 18:04

dsdsdsdsd


People also ask

What is Logcat output?

Logcat is a command-line tool that dumps a log of system messages, including stack traces when the device throws an error and messages that you have written from your app with the Log class. This page is about the command-line logcat tool, but you can also view log messages from the Logcat window in Android Studio.

Which class do we use to send some output to Logcat?

The Log class allows you to create log messages that appear in logcat. Generally, you should use the following log methods, listed in order from the highest to lowest priority (or, least to most verbose): Log. e(String, String) (error)

How do I show objects in console?

Answer: Use console. log() or JSON. stringify() Method You can use the console. log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.


2 Answers

Convert object to JSON. You can use Gson.

val gson = Gson()
val json = gson.toJson(yourObject)
Log.e(TAG, json)

Or

Log.e(TAG, Gson().toJson(yourObject))
like image 45
Aditya Patil Avatar answered Sep 30 '22 02:09

Aditya Patil


You cannot print an object to the console in Java as you would in javascript.

You have three solutions.

1) Use debugger. Place a breakpoint and debug in android studio. Then you can inspect the full object in scope.

2) Serialize your object (for example to JSON) and print the result to console.

3) Override toString method of your object to give you all the information you want and call Log.d("myTag", yourObj.toString())

I highly recommend first method. I used to avoid Debugger but learning how to use the debugger was the best thing I did. It increases your efficiency and makes debugging super easy

like image 131
Arijoon Avatar answered Sep 30 '22 02:09

Arijoon