two array dimensional ArrayIndexOutOfBoundException and NullPointerException - android

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

Related

use shuffelArray as global variable

We are trying to use this array of integers in other methods. Setting the final shuffled Array to a global variable has become next to impossible. We have set other variable as global. The goal here is to have a new int [] fix array every time a button is clicked. We have been able to generate a random int [] ar but can not utilize the array in other methods. So our questions after making the random int [] ar how can we use it in the onClickBtnOne method? Code with comments below
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3,btn4,btn5,btn6;
String T1,T2,T3,T4,T5,T6;
int test[] = new int[7];
int count = 0;
int v1,v2,v3,v4,v5,v6;
int[] fix = {3,2,1,4,6,5};
// Trying to not use above values
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
main(null);
}
// end onCeate
public static void main(String args[]) {
int [] fix = {1,2,3,4,5,6};
shuffleArray(fix);
// Want to USE this fix shuffleArray
//==================================
for (int i = 0; i < fix.length; i++) {
System.out.print(fix[i] + ",");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int [] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void onClickBtnOne(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
count = count + 1;
v1 = count;
test[v1] = count;
if(fix[0] == test[v1]){
// Need a global fix[] here
// =========================
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
The array you are trying to use does not have an add method you need to put the values in from another variable like this ar[i] = a; So if you use this type of Array declaration List value = new ArrayList<>(); where you declared the other global variable life will be much easier. Modified code below
This will do the shuffle NOTICE value.clear() without this the List will grow each time it is initialized
public void shf(View view){
value.clear();
for (int i = 1; i <= 6; i++) {
value.add(i);
}
Collections.shuffle(value);
}
And here is your test method call value.get(index) Arrays are ZERO based
public void on1(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
if(value.get(0) == 1){
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}

My code throws ArrayIndexOutOfBoundException but i think it's ok

here is my 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];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.

Android array error

This is my code:
public ArrayList generare_diferente(){
int rezultat;
ArrayList<String> termeni= new ArrayList<String>();
int termA=parseInt(String.valueOf(randomBetween(1, 20)));
int termB=parseInt(String.valueOf(randomBetween(1, 20)));
if(termA<termB){
int aux; aux=termA; termA=termB; termB=aux;
rezultat=termA-termB;
String diff = termA + "-" + termB;
termeni.add(String.valueOf(rezultat));
termeni.add(diff);
Log.v("termeeeeni", String.valueOf(termeni));
}
return termeni;
}
public void generare_3_diferente() {
ArrayList<String> scaderea1 = new ArrayList<String>();
ArrayList<String> scaderea2 = new ArrayList<String>();
ArrayList<String> scaderea3 = new ArrayList<String>();
int raspuns_corect;
int[] raspunsuri = new int[]{0, 0, 0, 0};
int i = 0;
do {
scaderea1 = generare_diferente();
scaderea2 = generare_diferente();
scaderea3 = generare_diferente();
Button scadere1 = (Button) findViewById(R.id.scadere1);
Button scadere2 = (Button) findViewById(R.id.scadere2);
Button scadere3 = (Button) findViewById(R.id.scadere3);
scadere1.setText((CharSequence) scaderea1.get(1));
scadere2.setText((CharSequence) scaderea2.get(1));
scadere3.setText((CharSequence) scaderea3.get(1));
}
while (scaderea1.get(0) == scaderea2.get(0) || scaderea2.get(0) == scaderea3.get(0) || scaderea3.get(0) == scaderea1.get(0));
raspunsuri[1]= Integer.parseInt(scaderea1.get(0));
raspunsuri[2]= Integer.parseInt(scaderea2.get(0));
raspunsuri[3]= Integer.parseInt(scaderea3.get(0));
pozitia_corecta = parseInt(String.valueOf(randomBetween(1, 3)));
raspuns_corect = raspunsuri[pozitia_corecta];
TextView rezultat = (TextView) findViewById(R.id.Rezultat);
rezultat.setText(raspuns_corect);
}
I'm getting this error:
java.lang.RuntimeException: Unable to start activity : java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.pinguin.MyActivity.generare_3_diferente(MyActivity.java:93)
at .onCreate(MyActivity.java:24)
I don't understand why, the array should not have the size 0.
thank you!
your code seems wrong. because in generare_diferente() if termA<termB or equal you return empty array and then in generare_3_diferente() you try to read data from empty list.
first you should handle this issue.then I think your random number are not generate so termA and termB both is zero or anything and if statement are not true.
change code like this
public ArrayList generare_diferente(){
int rezultat;
ArrayList<String> termeni= new ArrayList<String>();
int termA=random.nextInt(max - min + 1) + min ;
int termB=random.nextInt(max - min + 1) + min ;
if(termA<termB){
int aux; aux=termA; termA=termB; termB=aux;
rezultat=termA-termB;
String diff = termA + "-" + termB;
termeni.add(String.valueOf(rezultat));
termeni.add(diff);
Log.v("termeeeeni", String.valueOf(termeni));
}
return termeni.clone();
}
public void generare_3_diferente() {
ArrayList<String> scaderea1 = new ArrayList<String>();
ArrayList<String> scaderea2 = new ArrayList<String>();
ArrayList<String> scaderea3 = new ArrayList<String>();
int raspuns_corect;
int[] raspunsuri = new int[]{0, 0, 0, 0};
int i = 0;
do {
scaderea1 = generare_diferente();
scaderea2 = generare_diferente();
scaderea3 = generare_diferente();
Button scadere1 = (Button) findViewById(R.id.scadere1);
Button scadere2 = (Button) findViewById(R.id.scadere2);
Button scadere3 = (Button) findViewById(R.id.scadere3);
if(scaderea1.size()>0 && scaderea2.size()>0 && scaderea3.size()>0){
scadere1.setText((CharSequence) scaderea1.get(1));
scadere2.setText((CharSequence) scaderea2.get(1));
scadere3.setText((CharSequence) scaderea3.get(1));
}else{
scadere1.setText("something");
scadere2.setText("something");
scadere3.setText("something");
break;
}
}
while (scaderea1.get(0) == scaderea2.get(0) || scaderea2.get(0) == scaderea3.get(0) || scaderea3.get(0) == scaderea1.get(0));
if(scaderea1.size()>0 && scaderea2.size()>0 && scaderea3.size()>0){
raspunsuri[1]= Integer.parseInt(scaderea1.get(0));
raspunsuri[2]= Integer.parseInt(scaderea2.get(0));
raspunsuri[3]= Integer.parseInt(scaderea3.get(0));
}else{
raspunsuri[1]= Integer.parseInt("0");
raspunsuri[2]= Integer.parseInt("0");
raspunsuri[3]= Integer.parseInt("0");
}
pozitia_corecta = parseInt(String.valueOf(randomBetween(1, 3)));
raspuns_corect = raspunsuri[pozitia_corecta];
TextView rezultat = (TextView) findViewById(R.id.Rezultat);
rezultat.setText(raspuns_corect);
}

working with canvas : The specified child already has a parent. You must call removeView() on the child's parent first

I visit so many solutions regarding this issue but can't catch it clearly .When ever I run the project first time it works perfectly but when I run it second time then it fire this error in logCat
The specified child already has a parent. You must call removeView() on the child's parent first
where is the error in that code segment ?where should I change in code. any suggestion is acceptable .Thanks in advance ..
Main.java
public class MainActivity extends Activity {
List<PieDetailsItem> piedata = new ArrayList<PieDetailsItem>(0);
EditText edt3;
Button btnChart;
public String s15;
public String[] strArray;
public ImageView mImageView ;
public LinearLayout finalLayout ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
finalLayout = (LinearLayout) findViewById(R.id.pie_container);
mImageView = new ImageView(this);
edt3 = (EditText) this.findViewById(R.id.editText1);
btnChart = (Button) findViewById(R.id.button1);
btnChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*if(mImageView != null) {
finalLayout.removeView(mImageView);
}
else {*/
s15 = edt3.getText().toString();
/*System.out.println("value 1 is --->"+s10);
System.out.println("value 2 is --->"+s12);*/
System.out.println("value 3 is --->"+s15);
String domain = s15;
strArray = domain.split("\\,");
for (String str : strArray) {
System.out.println(str);
}
// }
openChart();
}
});
}
private void openChart(){
Integer[] items = new Integer[strArray.length];
//double[] distribution = new double[strArray.length];
for (int i = 0; i < items.length; i++) {
items[i] = Integer.parseInt(strArray[i]);
System.out.println("xxxxxx"+items[i]);
}
PieDetailsItem item;
int maxCount = 0;
int itemCount = 0;
// int items[] = { 20, 40, 10, 15, 5 };
int colors[] = { -6777216, -16776961, -16711681, -12303292, -7829368 };
// String itemslabel[] = { " vauesr ur 100", " vauesr ur 200",
// " vauesr ur 300", " vauesr ur 400", " vauesr ur 500" };
for (int i = 0; i < items.length; i++) {
itemCount = items[i];
item = new PieDetailsItem();
item.count = itemCount;
// item.label = itemslabel[i];
item.color = colors[i];
piedata.add(item);
maxCount = maxCount + itemCount;
}
int size = 200;
int BgColor = 0xffa11b1;
Bitmap mBaggroundImage = Bitmap.createBitmap(size, size,
Bitmap.Config.ARGB_8888);
View_PieChart piechart = new View_PieChart(this);
piechart.setLayoutParams(new LayoutParams(size, size));
piechart.setGeometry(size, size, 2, 2, 2, 2, 2130837504);
piechart.setSkinparams(BgColor);
piechart.setData(piedata, maxCount);
piechart.invalidate();
piechart.draw(new Canvas(mBaggroundImage));
piechart = null;
//ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mImageView.setBackgroundColor(BgColor);
mImageView.setImageBitmap(mBaggroundImage);
//LinearLayout finalLayout = (LinearLayout) findViewById(R.id.pie_container);
finalLayout.addView(mImageView);
}
}
You're adding mImageView to the layout multiple times. A view can only be part of 1 ViewGroup. You need to either add it only once, or create a second ImageView if you really want 2 of them in the layout.

Trying to set textview

Here is my class it goes in to infinite loop please check where I am going wrong ... I am trying to get id's of image view making it random and then trying to set text view with imageview's description
public class Object {
int ObectIds[];
LinearLayout HUDDisplay;
int HudDisplayText[] = {R.id.HUD_Text_Element1,
R.id.HUD_Text_Element2,
R.id.HUD_Text_Element3,
R.id.HUD_Text_Element4,
R.id.HUD_Text_Element5,
R.id.HUD_Text_Element6,
R.id.HUD_Text_Element7};
TextView[] text;
View v;
Object(Context context,View vs) {
super();
ObectIds = new int[8];
HUDDisplay=(LinearLayout)vs.findViewById(R.id.HUD_Display);
for (int i = 0; i < 8; i++) {
ObectIds[i] = (R.id.imageView1) + i;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
randomize(vs);
setTextView();
}
public void setTextView()
{
for(int i=0;i<8;++i)
{
text[i] =(TextView) HUDDisplay.findViewById(HudDisplayText[i]);
text[i].setText(v.getContentDescription());
}
}
public void randomize(View vs) {
for (int i = 0; i < 8; i++) {
while (true) {
shuffleArray(ObectIds);
v = vs.findViewById(ObectIds[i]);
Log.d("Image", "Image Id's " + v.getId());
if (!v.isClickable()) {
v.setClickable(true);
break;
}
}
}
}
static void shuffleArray(int[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i >= 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Hey man I observed your code & found error in code :
Please compare following code with your code... Constructor
for (int i = 0; i < 8; i++) {
ObectIds[i] = **HudDisplayText[i]**;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
You have a while(true) loop that you break from only if v is not clickable. What happens if v is clickable? Nothing in your code ever sets v to not clickable, and views by default are not clickable.
I notice you're using the Object class. Object is basically the root of which all classes extend. If you call super() in the constructor, it will call the super class constructor, which is Object as well... That might be the problem.
Try looking for tutorials on how to start with Java/Android, since you are also using variables names that are not recommended. E.g. in Java,:
- a Class starts with a Capital
- a variable, starts with lowercase
- a function starts with lowercase:
public class Captial
{
private int anIntegerStartsWithLowerCase;
private void functionsAreLowerCaseAsWell()
{
}
}
Also take a look at your loop... It looks like it is never ending

Categories

Resources