Is it possible to watch variables at runtime?

前端 未结 2 1618
刺人心
刺人心 2021-02-05 12:54

I know the basics of debugging, and I know I can add watches to a variable that stop the program\'s execution on a given condition. But I didn\'t want to stop the program every

相关标签:
2条回答
  • 2021-02-05 13:49

    If you know the basics of debugging, you can easily add watches to a variable that stop the program's execution on a given condition. If you didn't want to stop the program every time you want to see the value of a variable then the easy way to see the value of a variable is to use Toasts. A toast provides a sample value of any variable in an operation in a small popup. Toasts automatically disappear after a set timeout.

    A simple code example:

    Context context = getApplicationContext();
    CharSequence text = "Hello toast!";
    int duration = Toast.LENGTH_SHORT;
    
    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
    

    In order to see the variable value in a Toast:

       int var=1;
       Toast.makeText(getApplicationContext(), "vlaue is "+var, Toast.LENGTH_LONG).show();
    

    In order to see the variable type in a Toast:

       Toast.makeText(getApplicationContext(), "type is "+var.getClass().getName(), Toast.LENGTH_LONG).show();
    
    0 讨论(0)
  • 2021-02-05 13:50

    When your program has stopped on a breakpoint click the icon at the far right of the debugger menu (see image below). You can type in methods or variable names into this window and see what they would be.

    You can type any expression you like (as long as it is within the scope of where you broke your code) and input any hard-coded values or objects all without re-running your project.

    To add a variable to your watch list

    Start by putting a break point in the class where you'd want to watch a specific variable. Run the code and once it hits your breakpoint from the Variables window frame you should see all of the variables that are accessible. Simply choose the one you'd want to watch and then right click and choose "Add to watches" from the drop-down.

    Keep debugging and you should see the variable from the Watches window frame update when appropriate based on your code.

    0 讨论(0)
提交回复
热议问题