How can I " printf " variables in android to check my code? - android

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

Related

Unable to get a "null" value from Firebase snapshot in Unity on android

I want to do x when FirebaseRef snapshot.Value == null. This works in the Unity Editor everytime but when I do this on the Android device, it fails every time. The app doesn't crash, it just doesn't do anything.
auth is working fine.
database is working fine (I'm getting all other values when the values exist) but when the value doesn't exist, that's where I have the issue.
Here is my sudo code, any help would be appreciated.
ref.Child("Location/That/Doesnt/Exist").GetValueAsync().ContinueWithTask(Task => {
if (task.IsFaulted){
//Do something
}
else if (task.IsCompleted){
DataSnapshot snap = task.Result;
if(snap.Value == null){
//This is what hangs. I get here and it just does nothing.
}
}
});
I'm so lost. I'm not sure how to figure this out. I get no errors but it's like the function just stops there.
Thanks all!
EDIT
So what I'm doing to get around this is to create a DB entry in the path with key == "0" and value == 0. Then I say if the ChildCount is greater than 1 and that child has more than 1 child, proceed.
I feel like this is a really poor approach.
I was getting the same error. I caught an exception of this, and i got NullReference, it's seems that on android when it's not found on database return Null, so you have to convert this:
if(snap.Value == null){
}
to this:
if (snap==null && snap.Value==null)
You are trying to access to snap.Value when snap object is null.
Sorry my english, i hope this helps you.
try trailing slash
"Location/That/Doesnt/Exist/"

Is it possible to see which functions are called in Logcat?

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();

Android Where do you put code to modify fields in dialogfragments?

I am creating a DialogFragment that I use for my login dialog. I want to have autocompletion for the email addresses that are used as user ids. I found a good tutorial here, but it didn't really deal with using a DialogFragment.
My current code is:
DialogFragment dialog = new LoginDialogFragment();
AutoCompleteTextView emailLoginId = (AutoCompleteTextView) findViewById(R.id.login_user_id);
if (null == emailLoginId) {
Log.d(tag, "EmailLoginId is null!");
}
// get list of drivers
ArrayAdapter<String> driverList = dbHelper.getAllDriverEmailStringAdapter();
Log.d(tag, "Driver List size is " + driverList.getCount());
emailLoginId.setAdapter(driverList);
dialog.show(getSupportFragmentManager(), "LoginDialogFragment");
As you can see, I'm creating the dialog, then attaching the list of names. Unfortunately, this gives me a null pointer exception on the line:
emailLoginId.setAdapter(driverList);
I'm sure this will probably be some embarrassingly simple oversight on my part, but that's okay, if it gets me moving forward.
I've tried this same code, with appropriate modifications, in the onStart() and onCreateView() portions of the LoginDialogFragment. In all cases, it can't find the fields, either the login id field, or the password field.
When calling from within the onStart() and onCreateView() routines, I used:
AutoCompleteTextView emailLoginId = (AutoCompleteTextView) getActivity().findViewById(R.id.login);
Is that wrong?
The only other thing I can figure that might be causing the problem is that the dialog isn't actually created until dialog.show(getSupportFragmentManager(), "LoginDialogFragment") is called, but that doesn't jibe with the documentation and you'd still think this would work in the onStart() routine at the very least.
Thanks, in advance, for your time.

Checking if part of a bundle exists in Android

I am working on an application, and from a list view I create a bundle that includes the item selected and the previous item. What I need to determine is if the previous item actually gets bundled through. If it exists, I want the information, but if it doesn't exist, then I need to set my text views to reflect that. But I get a null pointer exception if it doesn't exist when trying to load the receiving activity (the bundling activity does not cause the crash as I found during debugging - I get to the point where I'm testing for the data in the bundle before it crashes). So I've included the code from the receiving activity.
Bundle evmBundle = this.getIntent().getExtras();
final EVMData evm = (EVMData) evmBundle.getSerializable("evm");
final Project project = (Project) evmBundle.getSerializable("project");
if (!evmBundle.getSerializable("prvEVM").equals(null)){
final EVMData prvEvm = (EVMData) evmBundle.getSerializable("prvEVM");
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText(prvEvm.getAc().toString());
}
else{
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText("0");
}
I know something is getting passed through in the bundle for "prvEVM" because it showed up as part of the bundle in the debugger.
I also tried pulling it out of the bundle first and then trying to compare it. After pulling it out of the bundle, prvEvm is null (looking at the variables in the debugger), so I thought something like this might work:
if (!prvEvm.equals(null)){
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText(prvEvm.getAc().toString());
}else{
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText("0");
}
But I get a NullPointerException because prvEvm is Null. So I tried flipping the if test around, but got the same results. I should note that no matter how I set this up, if prvEvm is not null, all configurations here work - the requested data is put in the TextView. Basically, I need to be able to get around this null pointer exception. I know the object is null, I want to test for that so that if it is, that object isn't used. It will only be null once.
Don't use equals(null) as you call a method (equals) on a null object. Instead, compare to null:
if (prvEvm != null){
besides, equals(null) always returns false.

Android: How can I print a variable on eclipse console?

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;

Categories

Resources