I wanted to print the value of a variable on the console for my debugging purpose, but System.out.println doesn't work.
System.out.println and Log.d both go to LogCat, not the Console.
Window->Show View->Other…->Android->LogCat
I'm new to Android development and I do this:
1) Create a class:
import android.util.Log;
public final class Debug{
private Debug (){}
public static void out (Object msg){
Log.i ("info", msg.toString ());
}
}
When you finish the project delete the class.
2) To print a message to the LogCat write:
Debug.out ("something");
3) Create a filter in the LogCat and write "info" in the input "by Log Tag". All your messages will be written here. :)
Tip: Create another filter to filter all errors to debug easily.
Writing the followin code to print anything on LogCat works perfectly fine!!
int score=0;
score++;
System.out.println(score);
prints score on LogCat.Try this
I think the toast maybe a good method to show the value of a variable!
Ok, Toast is no complex but it need a context object to work, it could be MyActivity.this, then you can write:
Toast.maketext(MyActivity.this, "Toast text to show", Toast.LENGTH_SHORT).show();
Although Toast is a UI resource, then using it in another thread different to ui thread, will send an error or simply not work
If you want to print a variable, put the variable name.toString() and concat that with text you want in the maketext String parameter ;)
toast is a bad idea, it's far too "complex" to print the value of a variable. use log or s.o.p, and as drawnonward already said, their output goes to logcat. it only makes sense if you want to expose this information to the end-user...
If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.
The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.
By the way, in case you dont know what is the exact location of your JSONObject inside your JSONArray i suggest using the following code: (I assumed that "jsonArray" is your main variable with all the data, and i'm searching the exact object inside the array with equals function)
JSONArray list = new JSONArray();
if (jsonArray != null){
int len = jsonArray.length();
for (int i=0;i<len;i++)
{
boolean flag;
try {
flag = jsonArray.get(i).toString().equals(obj.toString());
//Excluding the item at position
if (!flag)
{
list.put(jsonArray.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonArray = list;
Related
I know, there is a way to see which functions are called in log-cat is to write a log message on top for every function like this
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("myTag","onDestroy function is called!");
// some logic
}
But it becomes irritating when you have more function.
So, I wonder if there is a way to see which functions are called in adb-logcat without writing log messages for every function.
I hope they can be fetched from somewhere in the stack but I couldn't find it.
You can try Hugo. In that case you have to annotate your methods with #DebugLog only. Then Hugo will generate logs for you (and will print out arguments and return value!). Example from GitHub:
#DebugLog
public String getName(String first, String last) {
SystemClock.sleep(15); // Don't ever really do this!
return first + " " + last;
}
And log output:
V/Example: ⇢ getName(first="Jake", last="Wharton")
V/Example: ⇠ getName [16ms] = "Jake Wharton"
Instead of printing log in every function. I (or most of the people) would suggest you to put debug.
To use debug first create breakpoints inside every function you want to check. To apply breakpoints simply left click in the area to the left of your code (refer image the pink circle represents a break-point).
Then to use Debug you have to press this button after successfully running your application.
As soon as the first method is called your application will pause at the break-point, then you can use F8 (or F6 if you are using eclipse settings) to move to next line, to move to next break-point you can press F9(or F8 if you are using eclipse settings). this way to can check all the functions being called.
This break-point method is really helpful if you just want to make sure that a particular function is being called.
Other than this if you still insist to know the details of all the functions you can store the stacktrace.
final StackTraceElement[] trace = new Throwable().getStackTrace())
StackTraceElement STrace = trace[1];
String className = STrace.getMethodName();
I'm trying to fill a list view with data i'm receiving from and odata service in json format. The data is already fetched and can be accessed with getIODataEntry().
I'm appending the respective values to a string to see an output in LogCat and split the string afterwards to fill my listView with the single values.
ListView listView_CarrierCollection = null;
...
private void showData() {
Log.d("debug", "log 1");
String carrierCollection = "";
for(int i=0; i<getIODataEntry().size(); i++) {
carrierCollection += getIODataEntry().get(i).getPropertyValue("Carrname");
carrierCollection += ";";
}
Log.d("debug", carrierCollection);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(carrierCollection.split(";")));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.custom_textview, list);
listView_CarrierCollection.setAdapter(arrayAdapter);
Log.d("debug", "log 2");
}
everything works, but only after my devices' screen has turned off and has being turned on again or after i close and reopen the app. The logs instead are prompted instantly to logcat, but the listView only contains the data after reopening the app.
Am i missing something out? Every hint would be appreciated!
EDIT:
Finally got it to work - turned out it had nothing to do with the posted code above. I had some listeners, that were trying to update a TextField in a Fragment. It seems as if MyFragment.textfield.setText("test"); blocked any further operations in some way. Surrounding it with runOnUiThread(new Runnable(){ ... }) solved it for me and got the whole thing to work.
Nevertheless thank you for your ideas and help!
Late to the party but may help someone else in the future
In my case, I wasn't calling notifyDataSetChanged() when i was updating my mutable array list. Therefore it was only working when i was tuning sceen off and on again. But after calling notifyDataSetChanged() it worked as usual.
Hope it helps ;)
I have tried so many things and I can't seem to get a grip on how to use logging correctly I currently want to log a variable but nothing seems to work can some provide a novice with a dumbed down version please I just want to learn. any help would be appreciated here's my code so far.
public void loadLeagueInformation() {
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date(0));
Log.v(TAG, "TIME:" + gmtTime);
}
Usually from an Activity MyActivity
Log.d("MyActivity", "String date " + gmTime);
I'm not sure if you have already formatted gmTime to your liking. If not you can use SimpleDateFormat
The format is Log.d(String tag, String msg). A common way of doing things is to use the package and/or the class name for tag.
For all of my Android classes I do the following (example)...
package com.mycompany.myapp;
...
public class MyActivity extends Activity {
protected final String TAG = this.getClass().getName();
...
}
Doing this means that TAG will be com.mycompany.myapp.MyActivity. If you do this for all Android classes then you are guaranteed that all of the TAG fields will start com.mycompany.myapp and it's easy to create a filter for logcat to identify all of your 'tags'.
Whenever I need to log something I simply do (example)...
Log.d(TAG, "Hello World");
In your LogCat window, what is the setting in the drop down box? Is it error? If it was so, then it would show only Logs that are errors i.e. Log.e(TAG,"..") Same would apply for the other options.
Since your are using Log.v(..) , set it to verbose.
Now, add a filter from the left panel, and enter your tag in the "By Log Tag" field. Select it when you run your application.
So I'm trying to make a calculator app (just to get a hang of android development), and I noticed with some testing that the parseInt conversion from "String tack1" is causing the app to crash. Can someone tell me why? I can't seem to figure it out and I've been searching the internet for quite a while now. (hehe I'm a noob so please go easy) In the code below, I've modified a couple lines to make it seem obvious what it's supposed to print however it still crashes. Here's the code:
equals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oC = 1; //operator checker is on 1 (for plus)
switch(oC){ //check for operator clicked
case 0: break;
case 1:
tack1 = "1"; //INSERTED THIS TO MAKE OUTPUT OBVIOUS
tack1 = tack1.trim(); tack2 = tack2.trim(); //INSERTED BEFORE TO DEAL WITH WHITESPACE
numOne = Integer.parseInt(tack1); //CRASHES HERE
answer.setText(numOne);
modeChecker = 0; oC = 0;break;
NOTES ON PROGRAM(some of comments repeated and other stuff as well):
The tack1 = "1"; is to make output obvious
The tack1.trim() is to deal with whitespace
Yes whatever is in tack is a number and an integer (not even a negative integer)
Yes numOne is an integer and is defined wayy above (not in code listed here)
Sorry the indents are all messed up(after case 1) because of the comments I added
This is a section of my onClick method, so closing brackets aren't included in here.
Can someone please help me?
THANKYOU :D
I'd be willing to bet it's actually crashing on the following line AFTER the call to parseInt.
You're calling setText(int) on your TextView. When you pass an int to this method, that int is a pointer to a string resource...you're probably expecting an auto-conversion to a string. Since you are passing it an int that is generated in your application, it's extremely unlikely that this int also points to a string resource in your res/values/strings.xml file. What you really want to do is change numOne to a string first, which you can do inline:
Change
answer.setText(numOne);
to
answer.setText(String.valueOf(numOne));
and you're good to go.
I have a problem which i'm trying to solve, I've been trying to fetch my data from an intent using mRowId below which I've been constantly returned a NullPointerException from fetchDrug() on LogCat.
Doing some troubleshooting using debugging, I've realized my variable mRowId is not Null and is pointing to something but I don't know what its pointing.
How can i check what is my variable mRowId pointing ? Or will normally such variables be gibberish that is incomprehensible?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drug_info);
//Defining the views
mDrugText = (TextView) findViewById(R.id.drug);
mContentText = (TextView) findViewById(R.id.content);
Bundle extras = getIntent().getExtras();
mRowId = extras.getLong(DrugsDbAdapter.KEY_ROWID);
if(mRowId == null) {
Log.e("mRowId is null", "ok");
} else {
Cursor drug = mDbHelper.fetchDrug(mRowId);
//Managing Cursor to pluck values to display
startManagingCursor(drug);
mDrugText.setText(drug.getString(drug.getColumnIndexOrThrow(DrugsDbAdapter.KEY_DRUG)));
mContentText.setText(drug.getString(drug.getColumnIndexOrThrow(DrugsDbAdapter.KEY_CONTENT)));
}
}
Instead of printf, use the existing log functionality in the SDK.
Output will appear in the logcat window of Eclipse (probably best option, since it's reasonably real-time and you can filter the display), or you can pull the logs off the device/emulator manually.
For example:
Log.i ( "MyApp", "Drug = " + drug.getString ( drug.getColumnIndexOrThrow ( DrugsDbAdapter.KEY_DRUG ) ) );
Use the debug function of eclipse and walk trough the code step by step. It gives the values of all variables.
Often objects will have a "toString()" method to represent the object in a human readable form; you could pass that into a Log.e() call. In your case, it appears to be a numeric (long) rather than an object, so you can directly display it in your log.
Once you know the row id you're trying to fetch, you could verify that its valid by examining your database (using the sqlite3 command which is built into the emulator, or extracting the file to your development machine and using any of myriad sqlite tools).
If the row id is valid, I'd suggest looking into your database helper code to see how the fetchDrug() method is using it. It's possible the null pointer has nothing to do with the parameter, but with other items in that method.
Here are a couple of options to consider:
Option 1: Set a breakpoint in onCreate in Eclipse. You can find more detail on debugging Android apps in Eclipse here: http://developer.android.com/guide/developing/debugging/debugging-projects.html
Option 2: Add Log statements to your code and view the output in logcat. You can read more about logging in Android here: http://developer.android.com/reference/android/util/Log.html