I have this method in nearly all my classes.
//listener - info
private void clickInfoListener(final ImageView iv, final int title, final int text){
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
materialHelper.showInfoDialog(MainActivity.this, iv, title, text);
}
});
}
Accessing this static method in a helper class
public static void showInfoDialog(Context context, final ImageView iv, final int title, final int text){
iv.setImageResource(R.drawable.ic_info_touched);
//
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(text);
builder.setPositiveButton(R.string.gotIt, null);
builder.show();
//
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
iv.setImageResource(R.drawable.ic_info_primary);
}
}, 25);
}
I am getting lint warning of "static member being accessed by instance reference". I don't know how to not use "this" here. So I have two options.
1) Ignore the lint warning
2) Drop the "static" in my helper method.
Which is better? Or propose a third solution.
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.
Since static variables belong to a class, we can access them directly using the class name. So, we don't need any object reference. We can only declare static variables at the class level. We can access static fields without object initialization.
The static method cannot invoke the instance member as well as methods of the class. Because static methods are accessed without the object reference of the class but we cannot access the instance variables and method without an object reference.
In C# it is not legal to access a static method or member variable through an instance, and trying to do so will generate a compiler error (C++ programmers, take note). Some languages distinguish between class methods and other (global) methods that are available outside the context of any class.
The warning is saying that you're calling a static method showInfoDialog
through an instance materialHelper
instead of through the class MaterialHelper
itself. This is "bad" because it suggests the method is actually an instance method that depends on some state in the instance.
The solution is to replace
materialHelper.showInfoDialog(...)
everywhere in your code with
MaterialHelper.showInfoDialog(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With