Android result of a method as a static property - android

Will the code below be effective? I mean, will it actually be run just one and the result will be cached in the property, so the next call will not re-run the method anymore?
public static final String LOG_TAG = MyApplication.getContext().getApplicationInfo().name;
Somehow I cannot find it anywhere.
comment.
Since you guys seem to focus on not important things, here's the changed code:
public static final String SomeVar = MyApplication.someMethod();

You can't do that, since Application.getContext() method isn't static.
EDIT: I see you edited your question: So if your MyApplication.someMethod() method is static, than ofcourse it works, and someMethod() will be only called once, unless your class gets destroyed and recreated by the garbage collector.

I'm not sure. I usually get it this way:
My(Activity)Class.class.getSimpleName();

Related

Android DB controller error

Hello everyone :) can you explain why I get this and tell me what how I have to change my code. Waiting for the answers. Have a nice day:)
controller
cannot be used in a static method. You need to make the controller object static to be able to use in a static method.
It appears that you are attempting to use a non-static member field inside a static method. This is not allowed since you need an instance of the class to access the member field. You have two choices:
Make the member field a static class variable by adding the static modifier to its declaration.
Remove the static modifier from the method to make it non-static.
You should definitely prefer the second solution over the first. As a general rule of thumb, all methods and variables should be non-static unless you have a very good, specific reason to make them static. One common use of static variables is for final constants. You also might find a situation where all instances of a class share a single value. Note that these are the exception, not the rule.

public or private, does it really matter with Android variables

inside of a single activity, when defining components to be used only within that activity, what's the real difference between the following definitions:
Button btnPower = null;
//or
private Button btnPower = null;
//or
public Button btnPower = null;
public void somethingUsingTheButton(){
btnPower = (Button)findViewById(R.id.btnpower_id);
}
are there some "under the hood" conventions that should be thought about (garbage cleanup, memory, etc) that would suggest to always use private over public, if the entity itself is only ever going to be used inside the class it's written in?
Private fields promote encapsulation
It's a generally accepted convention to use private unless you need to expose a field or method to other classes. Getting in this as a habit will save you a lot of pain in the long run.
However, there isn't anything inherently wrong with a public field or method. It causes no difference for garbage collection.
In some cases some types of access will affect performance, but they are probably a bit more advanced than the topic of this question.
One such case has to do with inner classes accessing outer class fields.
class MyOuterClass
{
private String h = "hello";
// because no access modifier is specified here
// the default level of "package" is used
String w = "world";
class MyInnerClass
{
MyInnerClass()
{
// this works and is legal but the compiler creates a hidden method,
// those $access200() methods you sometimes see in a stack trace
System.out.println( h );
// this needs no extra method to access the parent class "w" field
// because "w" is accessible from any class in the package
// this results in cleaner code and improved performance
// but opens the "w" field up to accidental modification
System.out.println( w );
}
}
}
well,
one important point is that defining variables as private is the standard in java programming.
So calling directly variables on objects will at least appear strange for other people that may possibly read your code.
One other thing I'd say is that if you are not alone coding on a project is always a good practice to limit the visibility of the attributes that are key on the class implementation to avoid strange work around that other developers may come up with.
I personally don't know if those modifiers are used to compiling and optimization purpose.
to conclude as I think every experienced java coder I strongly sujest to use this pattern in the definition of attributes.
The scope of visibility has nothing to do with the garbage collector or memory management
You will want to reduce the scope of visibility as much as possible so your code can be easier to maintain.
private and public are both keywords of Java that have the purpose of Object Orientated Design. I suggest you read up about this: http://docs.oracle.com/javase/tutorial/java/concepts/
If you are only going to use those variables (objects) in your activity, then I would suggest you make those variables private.
I hope this helps.
Edit:
I'm not sure if using the private, public or no keyword will optimize you app from a memory point of perspective. As far as I can tell I think it does not and you should use what makes your code most readable, intuitive and maintainable.
If your variable declaration is inside the Activity's scope, it acts normally as a scoped variable normally would.
It is, however, bad programming practice to use variables from one method in another method when they're not parameters.
Example:
Bad:
void Foo()
{
int foo = 5;
System.out.println(Bar());
}
int Bar()
{
return foo + 5;
}
This will actually throw a syntax error because foo is declared outside of scope for Bar()
Good:
int foo;
void Foo()
{
foo = 5;
System.out.println(Bar(foo)); //prints 10
}
int Bar(int foo)
{
return foo + 5;
}

Instantiate variables in class instead of onCreate() wrong?

Is something wrong with this construct in Android?
class A extends Activity {
private Object myObject = new Object();
#Override
protected void onCreate(Bundle savedInstanceState) {
//myObject = new Object();
}
}
Because at some point(s) later I get (sometimes, not reproducible yet) exceptions because myObject is null. I don't know if it's because I have to initialize in onCreate.
Edit: Additional details:
The actual class of myObject is List<Object> (Where Object is a domain specific type)
At some point later in the activity I'm storing myObject as a static field of a "Parameter passer" class and starting other Activity (because I'm avoiding to implement Parcelable. If this is good or bad practice should not be discussed here, unless that's causing my error). In the other Activity I pick up myObject. There it's (sometimes) null.
Edit 2: I don't understand why this object becomes null if I'm storing a reference to it as static field of my parameter passer class (a standalone, dedicated class). That's how garbage collection works, right, it just removes when the objects are not referenced anymore. So since I have a static reference this object should not be removed. According to this thoughts, if they are correct, the problem should be somewhere else.
When you start a new activity your old one goes on the block for possible garbage collection (including any classes instantiated in it, including your parameter passer class), so your object is not necessarily going to be available (which is why you see an intermittent failure.).
I see two option:
1) Pass it along in the bundle with your intent that starts the new activity. As you were trying to avoid this, probably not your best choice.
2) Extend the Application class and store the object in there.
EDIT
I think the accepted answer to this SO Question might fix your issue (and explain what is actually happening).
No. That code is just fine. You can create objects in the constructor.
You may want to check a previous question about it Instance variable initialization in java and the section 3.2.4. Field Defaults and Initializers which basically states that the first case:
private Object myObject = new Object();
is identical to an initialization in the class constructor. (NOTICE onCreate is NOT the constructor).
So, myObject should never be null, except in the case the "new Object()" instruction failed, generating an exception.
Isn't this possible your code is changing the contents of myObject later on the code?

Problem referring to R globally

I'm trying to declare some final Strings for using as keys later, but I keep getting a null pointer exception.
private final String KEY = getString(R.string.key);
This is declared at the top of my activity, before onCreate(). Does the problem stem from referring to R in the class?
The problem is, that you cannot access the getString(..) there.
Why dont you just save the int value?
private static final int KEY = R.string.key
and than where you need it call the yourContext.getString(KEY);
:)
These initializers will be called when the object is constructed, which may be before it has a valid context.
Don't call getString() before onCreate(). You won't be able to have the strings final, though.

why we should keep urimatcher definition in static flower brackets in content provider?

I got a doubt regarding the content provider.
Everytime when i am write the content provider, i am placing the URI MATCHER definition in the static brackets but the URI MATCHER is declared a private data member of the class. Only definition(new UriMatcher) is being placed in the static brackets.
Will anyone please let me know the reason. I tried googling but not able to find the answer. Me too will try please let me know if anyone knows already.
Thanks & Regards,
SSuman185
It is a static initialization block.
When you define a member or class variable the value must fit on a single line (even if you space it over more), and it cannot include complicated logic.
For member variables you can do this complicated initialization in the Constructor.
Essentially a static initialization block is a constructor for your class variables, allowing you to use more complicated expressions when initializing. It is only executed once, when the class is first loaded, no matter how many instances are created.
A private member just means the variable is not accessible to other classes, it is still accessible to the class itself. So the static initialization block only creates the URIMatcher once (when the class is loaded), no matter how many instances there are.

Categories

Resources