Android Studio - undefined label: 're' - android

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()){
}

Related

Android AccessibilityService performAction() method not working

I am developing an accessibility service for Android. The service calls an app, and that app has a RecyclerView. Then I want to click on an element of the RecyclerView with performAction(AccessibilityNodeInfo.ACTION_CLICK) but it is not working. I know there are a few similar questions but none of them works for me. Also I checked the official documentation for the class of the performAction method https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo
This is my code:
#Override
public void onAccessibilityEvent(Accessibility event){
AccessibilityNodeInfo source = event.getSource();
if(source != null){
List<AccessibilityNodeInfo> list = source.findAccessibilityNOdeInfosByText("mystring");
list.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
This is my configuration xml file:
<accessibility-srvice xmlns...
android:accessibilityFeedbackType = "feedbackGeneric"
android:AccessibilityFlags = "flagDefault"
android:canPerformGestures = "true"
android:canRetrieveWIndowCOntent = "true"
I think I misunderstood something, but i don't know what can be. Any help is appreciated.
The simple answer is that while finding the node by text is fine, that particular node was not the node with the desired onClick event. The solution is to call
list.get(0).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK)
The clarifying discussion is below
I think .performAction(AccessibilityNodeInfo.ACTION_CLICK) is right, but there might be some other concerns. Sorry for posting as an answer but a comment is too small.
Are you sure the onAccessibilityEvent is being called? I don't think that is the right event, but I can't be sure. Maybe put a log in there to ensure it's calling the event when you expect it to be called.
Also, looking at the source might restrict your search, maybe instead of event.getSource() try using rootInActiveWindow (I use Kotlin so it might have a method, see https://developer.android.com/reference/android/accessibilityservice/AccessibilityService#getRootInActiveWindow(int))
EDIT: 28 March 2022
I have run this code on my own accessibility service and it does click the button. But it's very prone to overflow.
var ranOnce = false // prevent overflow
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
if (event == null) return
if (event.eventType == TYPE_WINDOW_STATE_CHANGED) return
if (event.source != null && !ranOnce) {
val nodeList = rootInActiveWindow.findAccessibilityNodeInfosByText("Menu")
//event.source.findAccessibilityNodeInfosByText("Menu") // <-- always nothing in list
Log.d("onAccessibilityEvent", "List of nodes: $nodeList")
if (nodeList.size > 0) {
android.util.Log.d("onAccessibilityEvent", "Node info: ${nodeList[0]}")
ranOnce = true
nodeList[0].performAction(AccessibilityNodeInfo.ACTION_CLICK) //<-- caused an infinite loop!
} else {
Log.d("onAccessibilityEvent", "No nodes found")
}
} else {
Log.d("onAccessibilityEvent", "event.source is null!")
}
}

LiveMutableData and copies update to same value?

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 want to make a for loop, but it won't compile

for(sudoku.get((int)(0)).doubleValue(); == sudoku.get((int)(1)).doubleValue();) {
sudoku.remove((int)(1));
Sudoku.add(Double.valueOf(SketchwareUtil.get random((int)(1)),
((int)(9))));
}
The error wants me to remove the "==" in the condition.
This is the first time I have tried to use "for" for something that isn't a repeat a set amount of time.
I think that there is small typo mistake in semicolon :
for(; sudoku.get((int)(0)).doubleValue() == sudoku.get((int)(1)).doubleValue();) {
sudoku.remove((int)(1));
Sudoku.add(Double.valueOf(SketchwareUtil.get random((int)(1)),
((int)(9))));
}

Using if/if else/else statements for collision detection. How to improve?

I am currently developing a game in AndEngine and I have set up my collision detection with the enemies by checking each car against every individaul index of the enemy array as for some reason, a for loop does not work. This is extremely inconvinient as not only does it make increasing and decreasing enemies a chore, but it looks awful! It looks something like this:
if (rManager.getInstance().iceArray[0].getIceSprite().collidesWith(rManager.getInstance().carArray[r].getCarSprite()))
{
rManager.getInstance().carArray[r].setCarSpeed(1f);
} else if (rManager.getInstance().iceArray[1].getIceSprite().collidesWith(rManager.getInstance().carArray[r].getCarSprite())) {
rManager.getInstance().carArray[r].setCarSpeed(1f);
} else if (rManager.getInstance().iceBergArray[0].getIceBergSprite().collidesWith(rManager.getInstance().carArray[r].getCarSprite())) {
rManager.getInstance().carArray[r].setCarSpeed(0f);
} else {
rManager.getInstance().carArray[r].setCarSpeed(0.5f);
}
The for loop I tried was like this with [r] being every car of the car array, but it doesn't seem to do anything.
for (int h = 0; h < rManager.getInstance().snowArray.length; h++)
{
if (rManager.getInstance().snowArray[h].getSnowSprite().collidesWith(rManager.getInstance().carArray[r].getCarSprite())) {
String temp = rManager.getInstance().carArray[r].toString();
Log.e("SNOW", "SNOWWWWW!" + rManager.getInstance().snowArray[h].toString());
rManager.getInstance().carArray[r].setCarSpeed(0.2f);
}
}
Thanks!!
You should use factory pattern or strategy pattern to remove out the if else.
Please see the link below to take reference.
http://www.cumps.be/nl/blog/read/design-patterns-strategy-pattern
or Strategy Pattern with no 'switch' statements?
EDIT :
Base on your code, the startegy pattern should implement follow pesudo code below. I have made some of assumption base on your code already posted above.
You will create a dictionary contains logics and appropriate action as below:
Dictionary<Func<RManager, int, bool>, Action<Car>>
ruleUpdates =
new Dictionary<Func<RManager, int, bool>, Action<Car>>();
Each Func<Ice, Car, bool> you should implement like this
private bool ZeroElementEqualIcePrite(RManager rManager, int r)
{
return rManager.getInstance().iceArray[0].collidesWith(rManager.getInstance().carArray[r].getCarSprite());
}
and Action should implement as below:
public static void DoUpdateOneLevel(Car car)
{
car.setCarSpeed(1f);
}
From there we can implement similar with all of logics following your code with the same way.
You can initialize the dictionary following below
ruleUpdates.Add(FirstElementEqualIcePrite, DoUpdateOneLevel);
ruleUpdates.Add(SecondElementEqualIcePrite, DoUpdateOneLevel);
ruleUpdates.Add(FirstElementEqualIceBergPrite, DoUpdateZeroSpeed);
ruleUpdates.Add(SecondElementEqualIceBergPrite, DoUpdateZeroSpeed);
After that you just loop go through each key of executionList as below.
foreach (KeyValuePair<Func<RManager, int, bool>, Action<Car>>
ruleUpdate in ruleUpdates)
{
if (ruleUpdate.Key.Invoke(rManager, r))
{
ruleUpdate.Value.Invoke(rManager.getInstance().carArray[r]);
break;
}
}
Hope this help. Following the strategy your code will clean and easy to changed does not care much about if / then / else logic as well. You can easy extent it in future.

Code not reaching if statement

I have the following code:
public void click(View v)
{
Button b = (Button) v;
TextView viewEditText = (TextView) findViewById(R.id.functionTextView);
String editText = viewEditText.getText().toString();
if (b.getId() == R.id.backspace)
{
if (viewEditText.length() > 0)
{
if (editText.substring(editText.length() - 1, editText.length()) == ".")
{
periodTrue = false;
}
viewEditText.setText(viewEditText.getText().toString().substring(0, viewEditText.length() - 1));
}
}
}
In this code I check to see if the character being backspaced is a period, if the previous condition is true. It sets the variable periodTrue to false. This tells the app that another period can be added.
Everything works with the backspace key as normal, except it never makes it inside the if statement where the variable is set. It throws no errors and I have checked with
viewEditText.append(editText.subString(editText.length()-1, editText.length()); to verify that the returned character is ".".
I don't know why it's not working, and it throws no errors or warnings either, on compile or run time. So I've come to you to see if a different perspective can show what I'm obviously doing wrong.
if (editText.substring(editText.length() - 1, editText.length()) == ".")
This won't work as you're comparing the references of the two Strings, which will be different. (More in-depth explanation in this question: How do I compare strings in Java?)
Use the following instead:
if (".".equals(editText.substring(editText.length() - 1, editText.length())))

Categories

Resources