What would be the equivalent foreach loop look like in android - android

What would be the equivalent foreach loop look like in android java I am porting the below code to android .This for loops is working for c#.
foreach (XmlNode candidate in parent.ChildNodes)
{
if (candidate is XmlElement && candidate.Name == element.Name)
{
if (candidate == element)
{
return index;
}
index++;
}
}
below is my function for android which gets error in the for loop:
private static int FindElementIndex(Element element)
{
Node parentNode = element.getParentNode();
if (parentNode.equals(Node.DOCUMENT_NODE))
{
return 1;
}
Element parent = (Element)parentNode;
int index = 1;
//how should be the foreach of the below to be changed?
for (Node candidate : parent.getChildNodes()) {
if (candidate.equals(Node.ELEMENT_NODE) && candidate.getNodeName() == element.getNodeName())
{
if (candidate == element)
{
return index;
}
index++;
}
}
Log.d("Log_d","Couldn't find element within parent");
//throw new ArgumentException("Couldn't find element within parent");
}

// parent.ChilNodes is some type of colleciton like arraylist
some update it show be for not foreach
for(XmlNode candidate : parent.ChildNodes)
{
if (candidate instanceOf XmlElement && candidate.Name == element.Name)
{
if (candidate == element)
{
return index;
}
index++;
}
}

I changed the function and for loop in the function like this
private static int FindElementIndex(Element element)
{
Node parentNode = element.getParentNode();
if (parentNode.equals(Node.DOCUMENT_NODE))
{
return 1;
}
Element parent = (Element)parentNode;
int index = 1;
NodeList nodes = parent.getChildNodes();
for (int k = 0; k < nodes.getLength(); k++) {
Node candidate = nodes.item(k);
if (candidate.equals(Node.ELEMENT_NODE) && candidate.getNodeName() == element.getNodeName()) {
return index;
}
index++;
}
Log.d("Log_d","Couldn't find element within parent");
//throw new ArgumentException("Couldn't find element within parent");
return 0;
}

Related

Compare elements of two arraylist of different sizes and order in android

I am not getting the result true even when the first element of both arraylists are same.i want to check my checkbox when result matches.I have implemented it in my recyclerview I want to compare the elements of the arraylists but both are different in size.I found a solution online and implemented it like:.
List<String> list1 = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
list1.add(data.get(i).getChannel_names());
}
List<String> list2 = new ArrayList<>();
for (int i = 0; i < listNewsChannelsSelected.size(); i++) {
list2.add(listNewsChannelsSelected.get(i).getSelectedChannelsFromApi());
}
private boolean equalLists(List<String> one, List<String> two) {
if (one == null && two == null) {
return false;
}
if (one != null && two == null) {
return false;
}
one = new ArrayList<>(one);
two = new ArrayList<>(two);
Collections.sort(one);
Collections.sort(two);
return one.equals(two);
}
if (equalLists(list1,list2)) {
holder.mCheckBox.setChecked(true);
} else {
holder.mCheckBox.setChecked(false);
}
I just tested it and saw that there is nothing wrong in the code. (Bit modified to test in java). I am getting the result as TRUE so the code is correct.
Try to check your API data. It seems to be incorrect (not what you are expecting it to be). Try to generate logs (print api data in loop).
public class Main {
public static void main(String args[]){
List<String> list1 = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list1.add(""+i);
}
List<String> list2 = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list2.add(""+i);
}
if (equalLists(list1,list2)) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
private static boolean equalLists(List<String> one, List<String> two) {
if (one == null && two == null) {
return false;
}
if (one != null && two == null) {
return false;
}
one = new ArrayList<>(one);
two = new ArrayList<>(two);
Collections.sort(one);
Collections.sort(two);
return one.equals(two);
}

Remove all ImageViews using Tag

how does one iterate through a view's children and remove all ImageViews with a Tag that StartsWith a particular string?
All examples I can find this iterator;
for (int pos = 0; pos < mat.getChildCount(); pos++)
{
Object tag = mat.getChildAt(pos).getTag();
if (tag != null)
{
String s = tag.toString();
if (s.startsWith("Z"))
{
mat.removeView(mat.getChildAt(pos));
}
}
}
do a test, then remove the object.
The issue is both 'pos' and getChildCount change throughout the process. If I want to remove the first item and then the 2nd item (which after the first remove is actually the first item) it won't work, as pos is now 1 (ie 2nd item).
thanks
There are a few options.
for (int pos = 0; pos < mat.getChildCount();) {
if (remove) {
mat.removeViewAt(pos);
continue;
}
// only increment if the element wasn't removed
pos++;
}
for (int pos = 0; pos < mat.getChildCount(); pos++) {
if (remove) {
mat.removeViewAt(pos);
// balance out the next increment
pos--;
}
}
// don't remove views until after iteration
List<View> removeViews = new ArrayList<>();
for (int pos = 0; pos < mat.getChildCount(); pos++) {
if (remove) {
removeViews.add(mat.getChildAt(pos));
}
}
for (View view : removeViews) {
mat.removeView(view);
}
// count in reverse
for (int pos = mat.getChildCount() - 1; pos >= 0; pos--) {
if (remove) {
mat.removeViewAt(pos);
}
}

Unit Test proto3 generated objects with verify

I am using proto3 for an Android app and I am having a problem with object equality, which makes it really hard on testing, especially for verify methods
Here is a unit-test representing the problem:
#Test
public void test_equal () {
PlayerCards playerCards1 = new PlayerCards();
playerCards1.playerId = 1;
playerCards1.cards = new int[]{2};
PlayerCards playerCards2 = new PlayerCards();
playerCards2.playerId = 1;
playerCards2.cards = new int[]{2};
assertThat(playerCards1.toString(), is(playerCards2.toString())); // pass
assertThat(PlayerCards.toByteArray(playerCards1),
is(PlayerCards.toByteArray(playerCards2))); // pass
assertThat(playerCards1, is(playerCards2)); // <----- fail
}
It is quite clear that the method equals is not working properly, checking the produced code (attached at the bottom) no equals, hashcode are generated.
I can workaround the assertThat by using .toString method but I cannot find any other way for verifications,
eg. verify(anyMock).anyMethod(playerCards)
I am afraid that this may also affect my runtime if am not extremely careful on checks.
Is there any way to generate equals, hashcode?
If not, can I at least extend, override verify so as to use toString when checking against proto-generated objects?
code-snippets:
My proto file is:
syntax = "proto3";
option java_multiple_files = true;
option optimize_for = LITE_RUNTIME; // existing or not has no effect.
option java_package = "com.package.my";
option java_outer_classname = "Proto";
option objc_class_prefix = "ABC";
package com.package.protos;
message PlayerCards {
int64 playerId = 1;
repeated int32 cards = 2;
}
I generate the files through gradle build and use the following properties
buildscript {
// ...
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
}
}
apply plugin: 'com.google.protobuf'
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.1.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
javanano {
// Options added to --javanano_out
option 'ignore_services=true'
option 'enum_style=java'
option 'generate_intdefs=true'
}
}
}
}
}
dependencies {
// ...
compile 'io.grpc:grpc-protobuf-nano:1.0.2'
}
The generated output:
// Generated by the protocol buffer compiler. DO NOT EDIT!
package com.package.my.nano;
#SuppressWarnings("hiding")
public final class PlayerCards extends
com.google.protobuf.nano.MessageNano {
private static volatile PlayerCards[] _emptyArray;
public static PlayerCards[] emptyArray() {
// Lazily initializes the empty array
if (_emptyArray == null) {
synchronized (
com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) {
if (_emptyArray == null) {
_emptyArray = new PlayerCards[0];
}
}
}
return _emptyArray;
}
// optional int64 playerId = 1;
public long playerId;
// repeated int32 cards = 2;
public int[] cards;
public PlayerCards() {
clear();
}
public PlayerCards clear() {
playerId = 0L;
cards = com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY;
cachedSize = -1;
return this;
}
#Override
public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output)
throws java.io.IOException {
if (this.playerId != 0L) {
output.writeInt64(1, this.playerId);
}
if (this.cards != null && this.cards.length > 0) {
for (int i = 0; i < this.cards.length; i++) {
output.writeInt32(2, this.cards[i]);
}
}
super.writeTo(output);
}
#Override
protected int computeSerializedSize() {
int size = super.computeSerializedSize();
if (this.playerId != 0L) {
size += com.google.protobuf.nano.CodedOutputByteBufferNano
.computeInt64Size(1, this.playerId);
}
if (this.cards != null && this.cards.length > 0) {
int dataSize = 0;
for (int i = 0; i < this.cards.length; i++) {
int element = this.cards[i];
dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano
.computeInt32SizeNoTag(element);
}
size += dataSize;
size += 1 * this.cards.length;
}
return size;
}
#Override
public PlayerCards mergeFrom(
com.google.protobuf.nano.CodedInputByteBufferNano input)
throws java.io.IOException {
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
return this;
default: {
if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) {
return this;
}
break;
}
case 8: {
this.playerId = input.readInt64();
break;
}
case 16: {
int arrayLength = com.google.protobuf.nano.WireFormatNano
.getRepeatedFieldArrayLength(input, 16);
int i = this.cards == null ? 0 : this.cards.length;
int[] newArray = new int[i + arrayLength];
if (i != 0) {
java.lang.System.arraycopy(this.cards, 0, newArray, 0, i);
}
for (; i < newArray.length - 1; i++) {
newArray[i] = input.readInt32();
input.readTag();
}
// Last one without readTag.
newArray[i] = input.readInt32();
this.cards = newArray;
break;
}
case 18: {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
// First pass to compute array length.
int arrayLength = 0;
int startPos = input.getPosition();
while (input.getBytesUntilLimit() > 0) {
input.readInt32();
arrayLength++;
}
input.rewindToPosition(startPos);
int i = this.cards == null ? 0 : this.cards.length;
int[] newArray = new int[i + arrayLength];
if (i != 0) {
java.lang.System.arraycopy(this.cards, 0, newArray, 0, i);
}
for (; i < newArray.length; i++) {
newArray[i] = input.readInt32();
}
this.cards = newArray;
input.popLimit(limit);
break;
}
}
}
}
public static PlayerCards parseFrom(byte[] data)
throws com.google.protobuf.nano.InvalidProtocolBufferNanoException {
return com.google.protobuf.nano.MessageNano.mergeFrom(new PlayerCards(), data);
}
public static PlayerCards parseFrom(
com.google.protobuf.nano.CodedInputByteBufferNano input)
throws java.io.IOException {
return new PlayerCards().mergeFrom(input);
}
}
Proved a missing documentation.
Googling around I noticed the following property in a pom (!?) file generate_equals=true.
After adding this to gradle generation options the methods equals, hashcode generated!
ie.
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.1.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
javanano {
// Options added to --javanano_out
option 'ignore_services=true'
option 'enum_style=java'
option 'generate_intdefs=true'
option 'generate_equals=true' // <--- this one
}
}
}
}
}

Reducing the Amount of Casts on a View

I can't seem to figure out how to write this code more efficiently. I'm iterating through views to check validity (text entered) but i find myself casting way too much. According to eclipse i need to cast in order to access the methods on the view. Here's the code:
// Verify Drivers/Vehicles Entered
private boolean checkDriversVehiclesValidity() {
int viewCount = mContainerView.getChildCount();
for (int i = 0; i < viewCount; i++) {
View v = mContainerView.getChildAt(i);
if (v.getId() == R.id.driverVehicleRow) {
for (int j = 0; j < ((LinearLayout) v).getChildCount(); j++) {
View v1 = ((ViewGroup) v).getChildAt(j);
if (v1 instanceof CustomAutoCompleteTextView) {
if (((CustomAutoCompleteTextView) v1).getError() != null) {
v1.requestFocus();
return false;
}
if (v1.getId() == R.id.drivers_field) {
String driverNumber = ((CustomAutoCompleteTextView) v1).getText().toString();
if ("".equals(driverNumber)) {
((CustomAutoCompleteTextView) v1).setError("Driver required");
v1.requestFocus();
return false;
}
} else if (v1.getId() == R.id.vehicles_field) {
String vehicleNumber = ((CustomAutoCompleteTextView) v1).getText().toString();
if ("".equals(vehicleNumber)) {
((CustomAutoCompleteTextView) v1).setError("Vehicle required");
v1.requestFocus();
return false;
}
}
}
}
}
}
return true;
}
For example, after checking for
if (v1 instanceof CustomAutoCompleteTextView)
you can be sure it IS an instance of CustomAutoCompleteTextView, so you can assign it to a properly typed variable like this:
CustomAutoCompleteTextView cv = (CustomAutoCompleteTextView)v1;
and use cv instead of ((CustomAutoCompleteTextView) v1) later.

Indexable Listview in Android

I'm trying to get an indexable list in my list view. I referred this. But while using the code, I'm facing with an error while using Korean Characters in the StringMatcher class. Can anyone explain me the usage of this class? Is this class required for English Characters as well?
Thanks in advance.
There are some changes to be done to make it work. In order to compile the project and get rid of korean text update the StringMatcher class
package com.woozzu.android.util;
public class StringMatcher {
public static boolean match(String value, String keyword) {
if (value == null || keyword == null)
return false;
if (keyword.length() > value.length())
return false;
int i = 0, j = 0;
do {
int vi = value.charAt(i);
int kj = keyword.charAt(j);
if (isKorean(vi) && isInitialSound(kj)) {
} else {
if (vi == kj) {
i++;
j++;
} else if (j > 0)
break;
else
i++;
}
} while (i < value.length() && j < keyword.length());
return (j == keyword.length())? true : false;
}
private static boolean isKorean(int i) {
return false;
}
private static boolean isInitialSound(int i) {
return false;
}
}

Categories

Resources