I have a MutableLiveData variable in my AppRepository which is updated and contains my data. This I have no issues with. I also have the following observable to trigger a UI update with the data it holds in my onCreateView function:
viewModel.projectWithContent.observe(viewLifecycleOwner, {
pwc = it
counterList = it.counterList
})
When I tap either to increase or decrease the counter count and then try to push the update to my Room database, it skips it. I have the following check currently:
if(counterList != null) {
try {
for(counter: Counter in counterList!!) {
if(counter.counter_count != pwc?.counterList!![
pwc?.counterList!!.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
It'll always go to Goodbye.
Now. If I put the following just below try
Log.i(LOG_TAG, "PWC: ${pwc?.counterList!![0].counter_count}, " +
"CPWC: ${counterList!![0].counter_count}," +
"VMPWC: ${viewModel.projectWithContent.value?.counterList!![0].counter_count}")
It provides the following output:
PWC: 70, CPWC: 70,VMPWC: 70
Is this a side effect of what I'm doing or?
Thanks
Like #Tenfour04 says, your condition is actually checking they don't match, so "Goodbye" is the output when they do match.
If you don't mind (this is a little long), I just want to recommend some stuff because I feel like you're making life hard for yourself with all the null-checking that's going on - the logic of the code was really hard to read, and I'm guessing that's why you didn't notice the flipped logic too!
First: the ? null safety stuff (and !! which is the opposite of safe, never use it unless you know you have good reason) is there because you have nullable variable types. Normally the IDE would smart cast them to non-null once you've done a null check (like on your first line) - but because they're vars, they can be changed at any time.
That means that a variable that wasn't null before could be now, so you're forced to null-check every single time you access it. But even if the types weren't nullable, because they're vars, they can still change, and the thing you were looking at a moment ago is something different now.
The simple solution is to just make a new variable:
val counters = counterList
if (counters != null) {
...
}
// or if you want to use one of kotlin's scope functions
counterList?.let { counters ->
...
}
Because that new one is a val, it's not going to change what it's pointing at! Once it's null-checked, it's always going to be non-null, so you don't need to use ? anymore.
You have a couple of variables to make - you want to make sure pwc isn't null, and also their counterLists. A quick way to do that is with pwc?.counterList - if pwc is null, it will return null. Otherwise it will move to the next step, and return counterList, which may be null. (Using !! is saying that it definitely never will be null, in which case it shouldn't be nullable at all!)
And you don't actually care about pwc anyway - you're just comparing its counterList to the other, so why don't we pare it back to just those?
val counters = counterList
val pwcCounters = pwc?.counterList
if (counters != null && pwcCounters != null) {
try {
for(counter: Counter in counters) {
if(counter.counter_count != pwcCounters[
pwcCounters.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
There's more we could do here, but just by cleaning up those nulls and using the specific variables we want to work with, does that feel easier to read? And more importantly, easier to understand what's happening and what could happen?
Might be worth throwing it in a function too, stops the call site getting cluttered with these temp variables:
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// do the stuff
}
// when you want to do the thing:
doThing(counterList, pwc?.counterList)
So all your null checking is out of the way, your "temp variables" are the fixed parameters passed to the function, it's all nice and neat.
I know this is a long post for such a short bit of code, but it's a good habit to get into - if you're writing code where you're working with nullable vars and you're wrestling with the null safety system, or you keep repeating yourself to access a particular variable nested inside another object, you can make things a lot easier for yourself! You can imagine how wild this could all get for more complex code.
Also if you care, this is how I'd personally write it, if it helps!
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// for (counter in Counters) is fine too I just like this version
counters.forEach { counter ->
// find returns the first item that matches the condition, or null if nothing matches,
// so no need to handle any exceptions, just handle the potential null!
// (this is a really common Kotlin pattern, lots of functions have a "returns null on failure" version)
val pwcCounter = pwcCounters.find { it == counter }
// remember pwcCounter can be null, so we have to use ? to access its count safely.
// If it evaluates to null, the match just fails
if (counter.count == pwcCounter?.count) Log.i(LOG_TAG, "Hello")
else Log.i(LOG_TAG, "Goodbye")
}
}
I also renamed counter_count to just count since it's a property on a Counter anyway. I feel like counter.count is easier to read than counter.counter_count, y'know? It's the little things
I'm wondering how to make this break statement working ??
i have looked in every site but nothing worked with it, here is the code :
public void check_if_connected(Socket sock){
re:
if (sock.isConnected() == false){
}
break re;
}
it says : Undefined label: 're'.
break labels are not used like gotos they are used to specify which level of looping to break to.
In this case your break and label are at the same depth. An example of a place where you would use a label, is something like:
while(condition1){
breaktohere:
while( condition2 ){
while(contition3){
if(somebreakcondition){
break breaktohere; // breaks out of 2 while loops
}
}
}
}
while(!sock.isConnected()){
}
i wanna ask about how can i do an if-statement using the code below? I have tried it and it give me an error; its say cannot convert void to bool. any suggestion?
if(images.setVisibility(View.GONE)){
Display();
}
You need to get visibilty and check it..
if(images.getVisibility()==View.GONE){
Display();
}
You can simply use below of the two codes:
if(images.getVisibility==view.GONE)
{
Display();
}
the getVisibility() returns an integer.
you can also check with the integer code
i.e.
VISIBLE-0
GONE-8
INVISIBLE-4
2.
if(images.getVisibility==0)
//VISIBLE
if(images.getVisibility==4)
//INVISIBLE
if(images.getVisibility==8)
//GONE
Try this:
if(images.getVisibility()==View.GONE){
Display();
}
Make sure in your code, images.setVisibility() images must be instance of View. then use View.getVisibility() method
if(images.getVisibility() == View.GONE)
Display();
I am trying to automate the contact selection process using Android uiautomator. My UI looks like below image. I am using below code to check each contact
for (String contactName : list) {
UiScrollable scrollable = new UiScrollable(new UiSelector().className(
android.widget.ListView.class).scrollable(true))
.setAsVerticalList();
try {
UiObject obj = scrollable.getChildByText(LIST_VIEW_ITEM, contactName, true);
obj.click();
} catch (Exception e) { }
finally {
scrollable.scrollToBeginning(scrollable.getMaxSearchSwipes());
}
}
This code is inefficient. It takes longtime to find each contact and check. Is there away to loop each row and check ?
Thank you.
.
try following code
for(int i=0;i<n;i++)new UiObject(new UiSelector().className("android.widget.CheckBox").instance(i)).click();
I'm not exactly sure but I think it is supposed to work.
Try making a UiCollection (called checkboxes e.g.) of all the checkboxes and then checkboxes.click().
UiCollection inherits this method from UiObject so I would guess it clicks in each of them, but I haven't tried it. If it works I will edit my answer to remove the doubt :)
button.setBackgroundResource(R.Drawable.abc);
if ( button.getBackground()==getResources().getDrawable(R.drawable.abc))
{
button.setBackgroundResource(R.drawable.xyz);
}
else if( button.getBackground()==getResources().getDrawable(R.drawable.xyz) )
{
button.setBackgroundResource(R.drawable.abc);
}
I want to compare the background images set on the button. The above code has been taken from Stack Overflow... but it doesn't seem to work
Please suggest a better method.
Try this
if ( button.getBackground().getConstantState()==getResources().getDrawable(R.drawable.abc).getConstantState())
{
button.setBackgroundResource(R.drawable.xyz);
}