while casting objects in java this rule must apply
Instances of classes can also be cast to instances of other classes,
with one restriction: The class of the object you're casting and the
class you're casting it to must be related by inheritance; that is,
you can cast an object only to an instance of its class's sub- or
super class-not to any random class.
I don't understand how this casting will work since i have not seen any relationship through inheritance in the android documentation:
TelephonyManager manager = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
the above is casting a context object to a TelephonyManager ?
In your code snippet, the casting is applied to the return value of getSystemService(), not a Context object. The getSystemService() method's signature indicates only that it shall return an Object. And the documentation indicates that the exact class (a subclass of the Object class -- duh) depends on the argument to the method.
The method getSystemService() in Context returns an Object. Since every single reference type in Java extends Object, it's allowed to attempt to cast it to anything.
Keep in mind that you're not casting a Context instance, but the result of getSystemService.
It's not casting Context, it's casting the return value of Context.getSystemService(String), which is declared to return Object. The actual return type obviously has an inheritance relationship with Object, no matter what it is. But if it doesn't have an inheritance relationship with TelephonyManager, the cast will fail at run time.
This part of the Android API is very badly designed. They could easily have improved the type safety and avoided the ugly casting by providing methods like Context#getTelephonyManager(). For that matter, they still could.
Related
I have to following variable declaration:
var baseItemList: MutableList<BaseDataItem>? = null
when writing the line:
baseDataItemsList?.get(position).getObjectTypeNum()
I'm getting an error saying that:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type BaseDataItem?
but, get method doesn't return a BaseDataItem?, only a BaseDataItem since the BaseDataItem inside the brackets is without a question mark.
Can someone explain me this error, and why i have to add this question mark?
Looking at this code:
baseDataItemsList?.get(position)?.getObjectTypeNum()
The call ?.get(position) returns the position if baseDataItemsList is not null, but otherwise returns null. So even though baseDataItemsList.get() would return a non-nullable BaseDataItem (only possible to call if baseDataItemsList is not nullable), the null-safe baseDataItemsList?.get() call returns a nullable BaseDataItem?, where the null condition indicates that baseDataItemsList is null. So you must use ?.getObjectTypeNum() to account for this.
Side note: in my opinion combining var with a mutable collection is often a code smell, because you're making something mutable in two different ways, which makes it more error-prone to work with.
Make use of Kotlins scope functions, for example the let scope to avoid that warning:
baseDataItemsList?.let { baseDataItemList ->
baseDataItemList.get(position).getObjectTypeNum()
}
That way you assert that baseDataItemList cannot be null inside the let scope. If you want to read more about that topic, take a look into the documentation
I have a ViewModel in which there is a method which has the following line of code:
billDate.set(!TextUtils.isEmpty(SampleApp.getInstance().getAccountManager().getDueDate()) ?
String.format(SampleApp.getInstance().getApplicationContext().getString(R.string.due),
SampleApp.getInstance().getAccountManager().getBillingDueDate()) :
SampleApp.getInstance().getApplicationContext().getString(R.string.missing_due_date));
I have a test class using Mockito to test the different methods in ViewModel. But it is failing with NullPointerException at this line:
String.format(SampleApp.getInstance().getApplicationContext().getString(R.string.due),
Below is the log:
java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1283)
at java.util.regex.Matcher.reset(Matcher.java:309)
at java.util.regex.Matcher.<init>(Matcher.java:229)
at java.util.regex.Pattern.matcher(Pattern.java:1093)
at java.util.Formatter.parse(Formatter.java:2547)
at java.util.Formatter.format(Formatter.java:2501)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2940)
While running a test case, I see the log showing some error related to Pattern
Can somebody suggest, how to test the String.format() method?
First of all, you should not be importing android view packages into your ViewModel. So skip using things like TextUtils inside ViewModels.
As to the getApplicationContext().getString(), create an interface for this. Something like:
interface StringProvider {
String getString(int resource);
}
Then pass that interface in your ViewModel constructor and use that to get the string you want.
When you initialize the ViewModel, you can pass a concrete implementation of StringProvider like this:
class StringProviderImpl implements StringProvider {
String getString(int resource) {
return SampleApp.getInstance().getApplicationContext().getString(resource);
}
}
This way, for your unit tests, you can just mock StringProvider and don't have to worry about dealing with contexts inside your ViewModel and the related test code.
You don't need to test the String.format method. That is not your code, and your goal should be to test your own code. But your code is using that method, so you need to test your code. This is the part you are trying to validate or mock out as I understand it:
String.format(SampleApp.getInstance().getApplicationContext().getString(R.string.due), SampleApp.getInstance().getAccountManager().getBillingDueDate())
which makes several calls to SampleApp to get an instance. Since those calls to SampleApp.getInstance are static method calls, you won't be able to mock them out. There isn't enough code posted to know what SampleApp is or what SampleApp.getInstance() returns or to know if any of the subsequent calls on that instance are returning null, but one of them is. So I think to solve this you need to look at the what the getInstance method returns. If you can't touch that code and you're hoping to only modify your test classes, you may not be able to test this with mockito due to the static method.
But otherwise you will need to build a way for your tests so the call to SampleApp.getInstance returns a mock object as the instance instead of whatever real instance I presume it is returning now. Then you can mock out the subsequent methods like getApplicationContext and getString to make them return canned responses so that the string.format call will not fail on a null input.
One note of caution--if you do end up making the static getInstance method return a mock, but sure you have proper cleanup when your test is done to set it back to what it was returning originally so you don't inadvertently modify something that might cause another unrelated unit test to fail. That is always a risk if you change something returned by a static method in a unit test since you are effectively changing it for all tests.
Considering that the test fails after the AccountManager was already used, you should have set up the SampleApp as a mock or fake already.
SampleApp app = SampleApp.getInstance()
AccountManager am = app.getAccountManager();
Context context = app.getApplicationContext();
billDate.set(!TextUtils.isEmpty(am.getDueDate()) ?
String.format(context.getString(R.string.due), am.getBillingDueDate()) :
context.getString(R.string.missing_due_date);
Now you only need to make sure to mock the Context you provide with with app.getApplicationContext() or the SampleApp itself, if you use app.getString() directly.
doReturn(dueFormatString).when(context).getString(R.string.due);
doReturn(dueMissingString).when(context).getString(R.string.missing_due_date);
But in general you should abstract the Context away. Not using it will simplify your code and therefore your testing a lot.
Also consider using context.getString() instead of String.format() for formatting a string you load from a resource. It's as easy as adding the format arguments as parameters to the call.
context.getString(R.string.due, am.getBillingDueDate())
In my application rather than following the regular hierarchy of the ActiveAndorid,
I'm explicitly calling with the .initialize() method by passing the getApplicationContext.
However, the TableInfo returned doesnt have any Tables from the model class that I'm creating.
I tried debug their code and it seems an issue with the classloader they are using.
My code is:
ActiveAndroid.initialize(getApplicationContext());
TestModel model=new TestModel();
model.value="hello";
model.save();
You should not use getApplicationContext. It might not return the context of your application. The naming of getApplicationContext is misleading.
More info here: getApplication() vs. getApplicationContext()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the meaning of “this” in Java?
I'm still very new to learning Android programming, and I noticed that "this" was used often in parameters for method calls in the language. I'm following The New Boston tutorials through YouTube, but he never really explains quite detailed enough what the 'this' statement means. Can somebody please explain it to me? Maybe dumb it down a bit?
this refers to the instance of the class you are currently coding within.
You cannot use it in a static context because in this situation you are not within any object context. Therefore this doesn't exist.
public class MyClass {
public void myMethod(){
this.otherMethod(); // Here you don't need to use 'this' but it shows the concept
}
private void otherMethod(){
}
public static void myStaticMethod(){
// here you cant use 'this' as static methods don't have an instance of a class to refer to
}
}
In android class.this is used to pass context around.
Formal definition of context: It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities.
That means if you need to access resources (including R and user interface) you will have to use context.
In java this means the instance of the class that you are in. For example MainActivity.this points to the current instance of the MainActivity. So by using MainActivity.this.foo you are accessing the foo field of MainActivity class.
public class YourClass {
private int YourInt;
public setTheInt(int YourInt) {
this.YourInt = YourInt;
}
}
"this" is used to see whether an attribute or function belongs to the class we're working on, clearer.
Also, you see that setTheInt operation gets an integer named as the same as your attribute. In that function's namespace, YourInt is not this class's YourInt, but a reflection of the integer coming from setTheInt's calls. "this" helps here to divide the outer and the inner "YourInt"s.
I need to use getString() from most of the modules in my application.
But for some strange reason, it is tied to Application or Context, so that means I need to pass to each and every class in my application, the Application reference as a parameter.
This clearly violates one of the most basic principles of object oriented design.
Is there a way around this?
The 'strange reason' is that since the string resources are tied to your application, there is no way to access them without some sort of handle to it (the Context). If most of your classes that are not activities need to access string resources, you might want to rethink your design a bit. A simple way to not depend on a Context is to load the strings and pass them to your classes in the constructor.
Yes, there is a workaround - if you happen to (or can) pass a View (any View-derived class) to the constructor, and you assign it to a data member, then you can access the string resources from anywhere in your class:
String str_via_res = yourView.getContext().getString(R.string.str_via_res);
Otherwise, you will have to pass a Context to every class that needs access to these string resources.
you can extend android.app.Application class to create a static method to pass on the context across all classes in your application.
Refer : PhoneApp.java