Caused by: java.lang.ArrayIndexOutOfBoundsException: length=8; index=8 - android

hi dear here I am posting my whole class where I am getting problem. First I explain my problem. I am generating an arrayList "Items" using spinners and the elements in spinners and arrays are exactly same then After comparing array length and ArayList size I want to jump on next activity but problem is occoured in comparing arrays now please help me for this problem
Thanks here is my activity
package com.example.mine4.pantryrecipes;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.List;
import java.util.ArrayList;
import android.view.View;
import android.widget.Toast;
import android.widget.Button;
import android.widget.TextView;
public class AddItem extends Activity {
MultiSelectionSpinner spinner1,spinner2,spinner3,spinner4;
Button button1;
TextView tv;
private int count = 0;
List<String> Items=new ArrayList<>();
List<String> veg=new ArrayList<>();
List<String> spice=new ArrayList<>();
List<String> dairy=new ArrayList<>();
ArrayList<Boolean> subset = new ArrayList<>();
String[] arrayRecipe = { "chicken","vegetable oil","ginger",
"onion", "garlic","potatoes","tomatoes","roasted peanuts", "peanut butter"};
String[] arrayRecipe2 = { "chicken","garlic","vegetable oil", "tomatoes",
"Dijon mustard","breadcrumbs","Parmesan cheese","unsalted butter"};
String[] arrayRecipe3 = { "chicken", "vegetable oil","unsalted butter",
"sugar", "garlic", "sauce"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
button1=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.tv);
String[] arrayItems = {"chicken"};
String[] arrayVeg = { "vegetable oil", "ginger",
"garlic","potatoes" ,"tomatoes","onion"};
String[] arraySpice = { "roasted peanuts", "sauce","Dijon mustard" };
String[] arrayDairy = { "breadcrumbs", "Parmesan cheese", "unsalted butter","sugar", "peanut butter" };
spinner1 = (MultiSelectionSpinner) findViewById(R.id.mySpinner1);
spinner2 = (MultiSelectionSpinner) findViewById(R.id.mySpinner2);
spinner3 = (MultiSelectionSpinner) findViewById(R.id.mySpinner3);
spinner4= (MultiSelectionSpinner) findViewById(R.id.mySpinner4);
spinner1.setItems(arrayItems);
spinner2.setItems(arrayVeg);
spinner3.setItems(arraySpice);
spinner4.setItems(arrayDairy);
}
public void onClick(View v)
{
Items=spinner1.getSelectedStrings();
veg=spinner2.getSelectedStrings();
spice=spinner3.getSelectedStrings();
dairy=spinner4.getSelectedStrings();
Items.addAll(veg);
Items.addAll(spice);
Items.addAll(dairy);
// for(int i=0;i<Items.size();i++)
// tv.append(Items.get(i));
compareArray();
//count++;
}
public void compareArray()
{
for(int j = 0 ; j < arrayRecipe.length ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
if(subset != null) {
if ((arrayRecipe.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, TenIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe", Toast.LENGTH_LONG).show();
}
if ((arrayRecipe2.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, EightIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe2", Toast.LENGTH_LONG).show();
}
if ((arrayRecipe3.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, EightIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe3", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Un-Matched", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
Intent intn = new Intent(AddItem.this,Exmain.class);
startActivity(intn);
}
}
and the major problem occured in this code which is array indexOutOfBound
for(int j = 0 ; j < arrayRecipe.length ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
thanks again for helping me

array.Length() always count from 1 not form zero use
arrayRecipe.length -1 in your for loop

Use This
for(int j = 0 ; j < (arrayRecipe.length)-1 ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}

Two problems:
You're using the size of arrayRecipe to bound the index of arrayRecipe, arrayRecipe2 and arrayRecipe3 All three arrays are different in size, hence leading to your error. You need 3 different for loops, one for each arrayRecipe.
Your i and j are in the wrong places.
Items.get(j) should be Items.get(i) as you are using Items.size to limit the size of i. Likewise, arrayRecipe.get(i) should be arrayRecipe.get(j).
Also, it is true that getLength() and getSize() start counting from 1 rather than 0 so the index of the final slot is (getLenght() - 1), but by using < as the clause in your for loop handles that.

Related

Open a actvity when a if statement comes true

Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);

two array dimensional ArrayIndexOutOfBoundException and NullPointerException

i wrote a code for calculating some weights. they are integer weights.
and i need to save them in every time the button is clicked.
please help me. i cant see why the compiler gives me an error when i try to push the button for the second time. here is my complete code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the exception it throws:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
UPDATEEEEEEEE
i fixed the problem with arrayindexoutofboundexception by changing W[2][] to W[20][]. but in some clicks it gives me this error:
java.lang.NullPointerException
and it's not clear in which clicks. sometimes it's in the second click. or some times it's in fourth click. please help.
W[clicks] = W[clicks - 1];
in above line, you have get error because you have only define size of the array
int W[][] = new int[2][];
so it assigned W[0][] and W[1][] only
When click on second time variable clicks value is 2 then compiler gives ArrayIndexOutOfBoundException
EDITED.............................................................
you have got null value because of your bad logic and not proper way to build two dimensional array. Pls use debug tool to find the actual problem to implement logic and use two dimensional array like below example in java or android:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));

Multiple loops not giving desired Result

I am working on a methods in which when I use a single loop with condition it checks both if and else conditions. But when I add more than one loop with condition it only checks else condition I do not know where is problem. please help me for that
here is my code
public void compareArray() {
ArrayList<Boolean> subset = new ArrayList<>();
for (int j = 0; j < (arrayBeef1.length); j++) {
for (int i = 0; i < Items.size(); i++) {
if ((arrayBeef1[j].equals(Items.get(i)))) {
subset.add(true);
break;
}
}
}
if (subset != null) {
if (arrayBeef1.length == subset.size()) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, BeefRecipes.class);
startActivity(nextClass);
finish();
} else {
Toast.makeText(getApplicationContext(), "Un-Matched", Toast.LENGTH_LONG).show();
}
}
for(int j = 0 ; j < (arrayBeef2.length) ; j++) {
for (int i = 0; i < Items.size(); i++) {
if ((arrayBeef2[j].equals(Items.get(i)))) {
subset.add(true);
break;
}
}
}
if (subset != null) {
if (arrayBeef2.length == subset.size()) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, BeefRecipes.class);
startActivity(nextClass);
finish();
} else {
Toast.makeText(getApplicationContext(), "Un-Matched", Toast.LENGTH_LONG).show();
}
}
where Item array is dynamic array which is populated through spinner and beefArray1 and two are
String[] arrayBeef1 = { "carrot","ginger",
"onion","beef","unsalted butter"};
String[] arrayBeef2 = { "garlic","olive oil", "onion",
"Dijon mustard","beef","salt","carrot","rosemary"};
and Items arraList is produced with similar items
please help what should I do with this method

Creating a Gridview for a word search

I am trying to create a word search using a gridview but I'm unsure how to add rows from a JSONArray, but my app keeps crashing at this point and also at gridView.addView(tableRow);
This is my new puzzle class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
public class NewPuzzleActivity extends Activity implements OnRetrieveHTTPData {
//word search data
String[] rows;
String[] words;
char[] letters;
//variables for the grid creation
int letterID = 0;
int rowID = 0;
//found words by the user
String[] wordsFound;
int[] rowFound;
int[] columnFound;
int[]directionFound;
// objects within the game *miscellaneous properties*
boolean firstLetterSelected = false;
int numOFLettersSelected = 0;
int[] lettersSelected;
int[] rowsSelected;
int[] columnsSelected;
String selectedString = "";
int directionSelected = 0;
int lastLetterSelected = -1;
String date;
GridView gridView;
TextView textView;
Toast toast;
public NewPuzzleActivity(){
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
gridView = (GridView) findViewById(R.id.gridView1);
Intent intent = getIntent();
if(intent.hasExtra("rows")){
// initialize the data
rows = intent.getExtras().getStringArray("rows");
addRows();
stringArrayToCharArray();
fillGrid();
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
if(intent.hasExtra("words")){
words = intent.getExtras().getStringArray("words");
wordsFound = new String[words.length];
rowFound = new int[words.length];
columnFound = new int[words.length];
directionFound = new int[words.length];
fillWords();
}
if(intent.hasExtra("date")){
date = intent.getExtras().getString("date");
//textView = (TextView)findViewById(R.id.Title);
//textView.append(date);
}
}
public void letterButonClick(View view){
if(toast != null){
toast.cancel(); // cancel toast message to prevent multiple toast messages
}
TextView textView1 = (TextView) findViewById(view.getId());
textView1.setTextColor(Color.RED);
//works out the column number of the selected letter(s)
columnsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[numOFLettersSelected] == 0) columnsSelected[numOFLettersSelected] = rows.length;
//works out the row number of the selected letter(s)
rowsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())/ rows.length)+1;
if(rowsSelected[numOFLettersSelected] == 0) rowsSelected[numOFLettersSelected] = rows.length;
//fixes the last column
if(columnsSelected[numOFLettersSelected] == rows.length) rowsSelected[numOFLettersSelected]-=1;
lettersSelected[numOFLettersSelected] = Integer.parseInt(view.getTag().toString()) + 4999;
Log.i("Selected Column", Integer.toString(columnsSelected[numOFLettersSelected]));
Log.i("Selected Row", Integer.toString(rowsSelected[numOFLettersSelected]));
if(!firstLetterSelected){
firstLetterSelected = true;
//resets the selected string
selectedString = textView1.getText().toString();
numOFLettersSelected = 1;
}else{
//adds letters to selected string
selectedString += textView1.getText().toString();
//compares to the last letter to work out the direction
if(columnsSelected[numOFLettersSelected] +1 == columnsSelected[numOFLettersSelected - 1] &&
rowsSelected[numOFLettersSelected] +1 == rowsSelected[numOFLettersSelected - 1]){
//direction left / down
directionSelected = 0;
Log.i("Direction", "0");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is down
directionSelected = 1;
Log.i("Direction", "1");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected] - 1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]){
//direction is right-down
directionSelected = 2;
Log.i("Direction", "2");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is left
directionSelected = 3;
Log.i("Direction", "3");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is right
directionSelected = 4;
Log.i("Direction", "4");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]){
//direction is left-up
directionSelected = 5;
Log.i("Direction", "5");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is up
directionSelected = 6;
Log.i("Direction", "6");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]) {
//direction is right-up
directionSelected = 7;
Log.i("Direction", "7");
checkWordFound();
}else{
// not a letter within/ around the the first letter selected, reset any selected letters
//deselect words and select a new letter to starr again
//selected string reset
selectedString = textView1.getText().toString();
for(int i : lettersSelected){
try{
TextView letters = (TextView)findViewById(i);
letters.setTextColor(Color.BLACK);
i++;
}catch (Exception e){
//break
Toast.makeText(getApplication(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
// new letter to be selected
columnsSelected[0] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[0] == 0) columnsSelected[0] = rows.length;
rowsSelected[0] = (Integer.parseInt(view.getTag().toString()) / rows.length)+1;
if(rowsSelected[0] == 0) rowsSelected[0] = rows.length;
if(columnsSelected[0] == rows.length) rowsSelected[0] -= 1;
lettersSelected[0] = Integer.parseInt(view.getTag().toString()) + 4999;
textView1.setTextColor(Color.RED);
}
numOFLettersSelected++;
Log.i("Selected TEXT", selectedString);
}
lastLetterSelected = Integer.parseInt(view.getTag().toString());
}
private void fillGrid(){
int LetterChars = 0;
for(int i = 0; i < rows.length * rows.length; i++){
if(LetterChars >= rows.length){
rowID--;
LetterChars = 0;
}
addLetter((TableRow)findViewById(rowID+4000+ rows.length-1));
TextView textView1 = (TextView)findViewById(i+5000);
textView1.setText(Character.toString(letters[i]));
LetterChars++;
}
}
private void fillWords(){
for(int i = 1; i < rows.length -1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
textView1.setText(words[i-1]);
}catch(Exception e){
textView1.setText("");
}
}
}
}
private void stringArrayToCharArray(){
char[] chars = new char[rows.length * rows.length];
int i = 0;
//selection of strings
for(int j = 0; j< rows.length; j++){
// selection of letters
for(int k = 0; k < rows.length; k++){
try{
chars[i] = rows[j].charAt(k);
}catch (Exception e){
Log.e("Error", "Error when adding chars");
}
i++;
}
}
letters = chars;
}
private void addLetter(TableRow row){
TextView textView1 = new TextView(this);
textView1.setId(letterID+5000);
textView1.setPadding(3,3,3,3);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
TableRow.LayoutParams textLayout = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
textLayout.setMargins(10,0,0,10);
textView1.setTextAlignment(textView1.TEXT_ALIGNMENT_CENTER);
textView1.setGravity(Gravity.CENTER);
textView1.setTag(""+(letterID+1));
textView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
letterButonClick(v);
}
});
textView1.setOnDragListener(new View.OnDragListener() {
//draggin selection *To be implemented*
#Override
public boolean onDrag(View v, DragEvent event) {
return false;
}
});
textView1.setLayoutParams(textLayout);
row.addView(textView1);
letterID++;
}
private void addRows(){
for(int i= 0; i < rows.length;i++){
TableRow tableRow = new TableRow(this);
tableRow.setId(i+4000);
gridView.addView(tableRow);
}
}
private void checkWordFound(){
int foundID = 0;
for(String w: words){
if(selectedString.contains(w)){
//word that have been found
Log.i("Word Found", "Found: " + w);
//highlight words that have been found in the word list
for(int i = 1; i < rows.length-1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
if(textView1.getText().equals(w)){
//textview that contains the found words
textView1.setTextColor(Color.GREEN);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
//add to found
wordsFound[foundID] =w;
columnFound[foundID] = columnsSelected[0];
rowFound[foundID] = rowsSelected[0];
directionFound[foundID] = directionSelected;
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
foundID++;
}
checkCompletion();
//no words are found
}
private void checkCompletion(){
if(Arrays.equals(words, wordsFound)){
new AlertDialog.Builder(this)
.setTitle("Word Search Complete")
.setMessage("Submit Score?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//submit score
submitResults();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
public void homeClicked(View v){
finish();
}
public void submitResults(){
}
#Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Solution Response", responseData);
//debug toasts
Toast.makeText(getApplication(),("Solution Submitted"), Toast.LENGTH_LONG).show();
finish();
}
}
error log
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-04 00:49:18.929 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone D/AndroidRuntime﹕ Shutting down VM
05-04 00:49:18.937 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: sl.lloyd.steve.angrywordsearchthefinalone, PID: 6068
java.lang.RuntimeException: Unable to start activity ComponentInfo{sl.lloyd.steve.angrywordsearchthefinalone/sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.widget.AdapterView.addView(AdapterView.java:461)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.addRows(NewPuzzleActivity.java:320)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.onCreate(NewPuzzleActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The problem is you cannot addView(view) directly to GridView, because it is an AdapterView which does not allow that. So you have to do this operation in your Adapter. You just have to add more data to the adapter and after call notifyDataSetChanged() on the adapter, so your GridView will be added the View by itself.

Check all the view's background in an if statement in Android?

I have many buttons(81) from the left and right part of my layout. All in all, I have 162 buttons. I put those buttons to Button[] and I handle it properly.
private int[] right_lung = { R.id.btn_right_106, R.id.btn_right_113,
R.id.btn_right_114, R.id.btn_right_115, R.id.btn_right_116, R.id.btn_right_121,
R.id.btn_right_122, R.id.btn_right_123, R.id.btn_right_124, R.id.btn_right_125,
R.id.btn_right_129, R.id.btn_right_130, R.id.btn_right_131, R.id.btn_right_132,
R.id.btn_right_133, R.id.btn_right_134, R.id.btn_right_137, R.id.btn_right_138,
R.id.btn_right_139, R.id.btn_right_140, R.id.btn_right_141, R.id.btn_right_142,
R.id.btn_right_143, R.id.btn_right_145, R.id.btn_right_146, R.id.btn_right_147,
R.id.btn_right_148, R.id.btn_right_149, R.id.btn_right_150, R.id.btn_right_151,
R.id.btn_right_152, R.id.btn_right_153, R.id.btn_right_154, R.id.btn_right_155,
R.id.btn_right_156, R.id.btn_right_157, R.id.btn_right_158, R.id.btn_right_159,
R.id.btn_right_160, R.id.btn_right_161, R.id.btn_right_162, R.id.btn_right_163,
R.id.btn_right_164, R.id.btn_right_165, R.id.btn_right_166, R.id.btn_right_167,
R.id.btn_right_168, R.id.btn_right_169, R.id.btn_right_170, R.id.btn_right_171,
R.id.btn_right_172, R.id.btn_right_173, R.id.btn_right_174, R.id.btn_right_175,
R.id.btn_right_176, R.id.btn_right_177, R.id.btn_right_178, R.id.btn_right_179,
R.id.btn_right_180, R.id.btn_right_181, R.id.btn_right_182, R.id.btn_right_183,
R.id.btn_right_184, R.id.btn_right_185, R.id.btn_right_186, R.id.btn_right_187,
R.id.btn_right_188, R.id.btn_right_189, R.id.btn_right_190, R.id.btn_right_191,
R.id.btn_right_192, R.id.btn_right_194, R.id.btn_right_195, R.id.btn_right_196,
R.id.btn_right_197, R.id.btn_right_198, R.id.btn_right_199, R.id.btn_right_200,
R.id.btn_right_205, R.id.btn_right_206, R.id.btn_right_207 };
private Button[] btn_right = new Button[right_lung.length];
private int[] left_lung = { R.id.btn_left_7, R.id.btn_left_13, R.id.btn_left_14,
R.id.btn_left_15, R.id.btn_left_16, R.id.btn_left_20, R.id.btn_left_21,
R.id.btn_left_22, R.id.btn_left_23, R.id.btn_left_24, R.id.btn_left_27,
R.id.btn_left_28, R.id.btn_left_29, R.id.btn_left_30, R.id.btn_left_31,
R.id.btn_left_32, R.id.btn_left_34, R.id.btn_left_35, R.id.btn_left_36,
R.id.btn_left_37, R.id.btn_left_38, R.id.btn_left_39, R.id.btn_left_40,
R.id.btn_left_41, R.id.btn_left_42, R.id.btn_left_43, R.id.btn_left_44,
R.id.btn_left_45, R.id.btn_left_46, R.id.btn_left_47, R.id.btn_left_48,
R.id.btn_left_49, R.id.btn_left_50, R.id.btn_left_51, R.id.btn_left_52,
R.id.btn_left_53, R.id.btn_left_54, R.id.btn_left_55, R.id.btn_left_56,
R.id.btn_left_57, R.id.btn_left_58, R.id.btn_left_59, R.id.btn_left_60,
R.id.btn_left_61, R.id.btn_left_62, R.id.btn_left_63, R.id.btn_left_64,
R.id.btn_left_65, R.id.btn_left_66, R.id.btn_left_67, R.id.btn_left_68,
R.id.btn_left_69, R.id.btn_left_70, R.id.btn_left_71, R.id.btn_left_72,
R.id.btn_left_73, R.id.btn_left_74, R.id.btn_left_75, R.id.btn_left_76,
R.id.btn_left_77, R.id.btn_left_78, R.id.btn_left_79, R.id.btn_left_80,
R.id.btn_left_81, R.id.btn_left_82, R.id.btn_left_83, R.id.btn_left_84,
R.id.btn_left_85, R.id.btn_left_86, R.id.btn_left_87, R.id.btn_left_88,
R.id.btn_left_89, R.id.btn_left_90, R.id.btn_left_91, R.id.btn_left_92,
R.id.btn_left_93, R.id.btn_left_94, R.id.btn_left_95, R.id.btn_left_98,
R.id.btn_left_99, R.id.btn_left_100, };
private Button[] btn_left = new Button[left_lung.length];
Whenever I click on the button, just like in mine sweeper game, many buttons are randomly opened. And when it is opened, I am changing its background into R.drawable.affected. The goal of the game is to open all the buttons in left and right. My question is this, how can I check if all of the buttons are set in R.drawable.affected? Because after that, I will execute a method that will congratulate the user. Thanks in advance.
EDIT:
for (int i = 0; i < btn_right.length; i++) {
final int a = i;
int counter_total_affected = 0;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 1) {
right_lung.add(a);
btn_right[a].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
} else if (counter == 2) {
for (int i = 0; i < 2; i++) {
int n = i;
right_lung.add(a + n);
}
try {
for (int i = 0; i < 2; i++) {
int n = i;
btn_right[a + n].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (counter == 3) {
right_lung.add(a);
btn_right[a].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
} else if (counter == 4) {
for (int i = 0; i < 25; i++) {
int n = i;
right_lung.add(a + n);
}
try {
for (int i = 0; i < 25; i++) {
int n = i;
btn_right[a + n].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (counter == ...) {
//statements...
} else if (counter_total_affected == (btn_left.length + btn_right.length)) {
//CONGRATULATORY METHOD
}
counter++;
}
}
Increment the counter each time you change background of button and compare its value with length of button array. if both are same that means, all button backgrounds are set.
Try this :
for (int i = 0; i < btn_right.length; i++) {
final int b = i;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if btn_right[i].getDrawable().getConstantState().equals
(getResources().getDrawable(R.drawable.affected).getConstantState()))
{
if(counter == btn_right.length){
//Congratulate user...
}
}else{
btn_right[b].setBackgroundResource(R.drawable.affected);
counter++;
}
}
}
U can set Tag:
for (int i = 0; i < btn_right.length; i++) {
final int b = i;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 1) {
right_affected.add(b);
btn_right[b].setBackgroundResource(R.drawable.affected);
btn_right[b].setTag('1');
} else {
//some stuff here...
}
}
}
after congratulate the user set its Tag to 0.
EDIT:
ArrayList<Integer> arrayofId =new ArrayList<Integer>();
#Override
public void onClick(View v) {
if (counter == 1) {
right_affected.add(b);
btn_right[b].setBackgroundResource(R.drawable.affected);
arrayofId.add(b);//need to convert int to Integer.
} else {
//some stuff here...
}
}
To congratulate:
for(int i=0;i<arrayofId.size();i++)
{
// you can get here id of effected buttons
}

Categories

Resources