Reducing the Amount of Casts on a View - android

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.

Related

What would be the equivalent foreach loop look like in 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;
}

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);
}

Get Index Of The Shuffled Item After collections.shuffle

I am trying to do a jigsaw puzzle app in android. In this, I have split a Bitmap into many small chunks. These chunks are then displayed in a GridViewNow I need to shuffle them. Then, I need to know each image chunk's actualPosition(where the piece was supposed to be, its actual location in the image) and its currentPosition(where the piece is currently located). actualPosition and currentPosition are 2 integer arrays. So is there a way that I can get each image chunk's currentPosition and actualPosition after the shuffling so that after every move that the user make I can check wether every image chunk's actualPosition equals its currentPosition. If so the user wins the game. Can anyone please help me out.
Below is the number puzzle game in pure Java that works. Can be run from command line.
It re-prints the whole matrix after every move (not pretty). It demos the basic game.
I hope most of the code is self explanatory. This shows the basic 2-dim mapping of the game, position tracking, validating based on numbers. Have fun.
package madhav.turangi.basic.game;
import java.util.Random;
import java.util.Scanner;
public class NumberPuzzle {
int size;
int[][] arr;
int spaceRow;
int spaceCol;
int turnsTook;
public NumberPuzzle(int size) {
this.size = size;
arr = new int[size][size];
}
void init()
{
for(int r=0; r<size; r++)
{
for(int c=0; c<arr[r].length; c++)
{
arr[r][c] = r*size + c + 1; // row-column of cell to its value equation
}
}
spaceRow = spaceCol = size - 1; // bottom-right cell index
}
int readUserInput()
{
int value = -1;
boolean valid = false;
do {
System.out.printf("To move space [0 - Up, 1 - Down, 2 - Left, 3 - Right] : ? ");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
try
{
value = Integer.parseInt(line);
valid = (value>=0 && value<=3);
}
catch(NumberFormatException ne)
{
}
if(! valid) System.out.println("== Invalid ==");
} while (! valid);
return value;
}
void swap(int aRow, int aCol, int withRow, int withCol)
{
int temp = arr[aRow][aCol];
arr[aRow][aCol] = arr[withRow][withCol];
arr[withRow][withCol] = temp;
}
boolean moveUp()
{
if(spaceRow != 0)
{
int newSpaceRow = spaceRow - 1;
swap(spaceRow, spaceCol, newSpaceRow, spaceCol);
spaceRow--;
return true;
}
else
{
return false;
}
}
boolean moveDown()
{
if(spaceRow != size-1)
{
int newSpaceRow = spaceRow + 1;
swap(spaceRow, spaceCol, newSpaceRow, spaceCol);
spaceRow++;
return true;
}
else
{
return false;
}
}
boolean moveRight()
{
if(spaceCol != size-1)
{
int newSpaceCol = spaceCol + 1;
swap(spaceRow, spaceCol, spaceRow, newSpaceCol);
spaceCol++;
return true;
}
else
{
return false;
}
}
boolean moveLeft()
{
if(spaceCol != 0)
{
int newSpaceCol = spaceCol - 1;
swap(spaceRow, spaceCol, spaceRow, newSpaceCol);
spaceCol--;
return true;
}
else
{
return false;
}
}
void shuffle()
{
Random rnd = new Random(System.currentTimeMillis());
boolean moved = false;
int attemptCount = 1;
int maxMoves = 20;
for(int moveCount=0; moveCount<maxMoves; moveCount++, attemptCount++)
{
int randomMoveDir = rnd.nextInt(4);
moved = move(randomMoveDir);
if(! moved) moveCount--; //ensure maxMoves number of moves
}
System.out.printf("Shuffle attempts %d\n",attemptCount);
}
boolean move(int dir)
{
boolean moved = false;
switch(dir)
{
case 0 : // up
moved = moveUp();
break;
case 1 : // down
moved = moveDown();
break;
case 2 : // left
moved = moveLeft();
break;
case 3 : // right
moved = moveRight();
break;
}
return moved;
}
void prnArray()
{
System.out.println("-- -- -- -- --");
for(int[] row : arr)
{
for(int cellValue : row)
{
String v = (cellValue == 16 ? "" : String.valueOf(cellValue));
System.out.printf("%4s", v);
}
System.out.println();
}
System.out.println("-- -- -- -- --");
}
boolean validate()
{
for(int r=0; r<size; r++)
{
for(int c=0; c<arr[r].length; c++)
{
if(arr[r][c] != (r*size + c + 1))
{
return false;
}
}
}
return true;
}
boolean oneTurn()
{
int dir = readUserInput();
boolean moved = move(dir);
boolean won = false;
if(moved)
{
turnsTook++;
prnArray();
won = validate();
}
else
{
System.out.println("= Invalid =");
}
return won;
}
void play()
{
init();
System.out.println("Before shuffle");
prnArray();
shuffle();
prnArray();
boolean won = false;
while(! won)
{
won = oneTurn();
}
System.out.printf("Won in %d\n", turnsTook);
}
public static void main(String[] args)
{
NumberPuzzle puzzle = new NumberPuzzle(4);
puzzle.play();
}
}

TextView OnTouch is not working

I have table layout in which I am adding textviews dynamically.
I m setting OnTouch listener on text view. On MotionEvent.ACTION_DOWN I show popup and on MotionEvent.ACTION_UP. I am removing that popup but I want if touch is removed from the textview then also the pop should remove I have tried with MotionEvent.ACTION_MOVE ,MotionEvent.ACTION_OUTSIDE but both are not working
public void addButton_with_filter(final Test test,
TableRow.LayoutParams rowParams, Activity context) {
ArrayList<Integer> filteredquestionno;
TableLayout tl = new TableLayout(context);
tl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
LinearLayout filterlayout = (LinearLayout) findViewById(R.id.filterlayout);
filterlayout.removeAllViewsInLayout();
filterlayout.setBackgroundResource(R.drawable.background1);
int j = 0;
int k = 0;
filteredquestionno = getLayoutFilteredQuestionNumber(test
.getQuestions());
int size = filteredquestionno.size();
if (size == 0) {
Toast.makeText(this,
"NO QUSTION IS AVAILABLE OF THIS FILTER TYPE !",
Toast.LENGTH_LONG).show();
}
int norows = (size / 10) + 1;
{
for (int i = 0; i < norows; i++) {
TableRow currentRow = new TableRow(FilterActivity.this);
// currentRow.setBackgroundResource(R.drawable.background1);
while (j < 10 && k < size) {
j++;
final TextView qindex = new TextView(FilterActivity.this);
qindex.setGravity(Gravity.CENTER);
int index = filteredquestionno.get(k);
Question question = test.getQuestionAtIndex(index);
if (question != null) {
if (submited == true) {
if (question.isSkipped()) {
qindex.setBackgroundResource(R.drawable.skipped_answer);
} else if (question.isCorrectlyAnswered()) {
qindex.setBackgroundResource(R.drawable.correct_answer);
} else if (question.isAttempted()) {
qindex.setBackgroundResource(R.drawable.wrong_answer);
} else {
qindex.setBackgroundResource(R.drawable.unattempted_question);
}
} else if (submited == false) {
if (question.isSkipped()) {
qindex.setBackgroundResource(R.drawable.skipped_answer);
} else if (question.isAttempted()) {
qindex.setBackgroundResource(R.drawable.attempted_question);
} else {
qindex.setBackgroundResource(R.drawable.unattempted_question);
}
enter code here }
} else {
qindex.setBackgroundResource(R.drawable.unattempted_question);
}
qindex.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
qindex.setTextSize(11);
if ((index + 1) < 10) {
qindex.setText("0" + (index + 1));
} else {
qindex.setText("" + (index + 1));
}
k++;
qindex.setId(k);
qindex.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
String text = (String) qindex.getText();
String t = text.trim();
int questionindex = Integer.parseInt(t);
LayoutInflater questionbutton_inflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View questionbutton_view = questionbutton_inflater
.inflate(R.layout.filterbutton, null);
final PopupWindow questiontext_popupwindow = new PopupWindow(
questionbutton_view,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
questiontext_popupwindow
.setContentView(questionbutton_view);
TextView tv = (TextView) questionbutton_view
.findViewById(R.id.texttoadd);
tv.setText(text);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
questiontext_popupwindow.showAsDropDown(qindex,
0, -125);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
questiontext_popupwindow.dismiss();
test.setLastQuestionAttempted(questionindex - 1);
FilterActivity.this.finish();
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
questiontext_popupwindow.dismiss();
}
return true;
}
});
currentRow.addView(qindex, rowParams);
}
j = 0;
tl.addView(currentRow);
}
filterlayout.addView(tl);
}
Typical mistake - you create pop-up every time MotionEvent fires. So the previously created pop-up cannot be dismissed, because you lost the link to it - another time your program enters onTouch() you will not have the link to your pop-up (because it is declared in onTouch()). Make your pop-up a field of OnTouchListener. And create it ONLY ONCE.
Step-by-step:
MotionEvent.ACTION_DOWN fires - you create and show pop-up, it is on screen
MotionEvent.ACTION_UP fires - you create new pop-up and dismissing it, but not the old one

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