Category:Outline of biologyQ:
Signature of a method called from a MainActivity class
I am trying to use a public void method of a MainActivity class. How can I know whether it was called directly or from a different class? My code is as follows:
MainActivity class:
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TestMethod();
}
});
}
public void TestMethod() {
Log.d("log_tag", "called from " + this.getClass().getSimpleName());
}
}
The output is:
I/log_tag﹕ called from android.app.Activity@3e26e3d8
So, I wonder how can I know if it was called from onCreate or from Button onClick?
A:
you should use getCallingClass() to get the current class where the method is called and use it's class name to identify the method calling, if it matches the class you want to know
onCreate(){
String clsName = getCallingClass().getSimpleName();
if(clsName.equals("MainActivity")){
//The calling class is MainActivity
}
}
Q:
Uncertainty in comments
I believe the program below is a valid JavaScript program and it compiles to a valid code. But in my opinion, it is not correct. How do you know that it's not correct?
If the program was a valid code ac619d1d87
Related links:
Comments