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);
}
Related
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));
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.
I have a list that is populated with data taken from database.
The data of the list are passed to the view to display them. For each id taken from the database, I want to add a day to the calendar, then, I added the id what I need in an array, in order to have them sorted.
The problem is the loop in the list, instead of iterating based on the number of id in the array, the cycle continues without stopping ... I hope I explained, this is all the code
private Integer[] id_nome_op;
public void checkOperatori() {
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String OPERATORI = "SELECT _id, ...... ORDER BY _id ASC";
Cursor cur = db.rawQuery(OPERATORI, null);
int count = cur.getCount();
id_nome_op = new Integer[count];
nome_op = new String[count];
cognome_op = new String[count];
for (int i = 0; i < count; i++) {
cur.moveToNext();
id_nome_op[i] = cur.getInt(0);
nome_op[i] = cur.getString(1);
cognome_op[i] = cur.getString(2);
mWeekView.setData(nome_op, cognome_op);
}
cur.close();
db.close();
}
#Override
public List<WeekViewEvent>onMonthChange(int newYear, int newMonth) {
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
final String strDate = simpleFormat.format(calendarioFooter.getTime());
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String tabella_op = "SELECT m._id, m.id_operatore, ...........";
Cursor cur = db.rawQuery(tabella_op, null);
while (cur.moveToNext()) {
startTime = (Calendar) calendarioFooter.clone();
id_appuntamento = cur.getString(0);
id_operator = cur.getInt(1);
dat = cur.getString(2);
ora_iniz = cur.getString(3);
ora_fin = cur.getString(4);
id_servizio = cur.getString(5);
id_client = cur.getString(6);
nome_cliente = cur.getString(7);
cognome_cliente = cur.getString(8);
nome_operatore = cur.getString(9);
colore_serv = cur.getInt(10);
tipo_serv = cur.getString(11);
int giorno_ok = Integer.parseInt(dat.substring(8, 10));
int ora_inizio = Integer.parseInt(ora_iniz.substring(0, 2));
int minuto_inizio = Integer.parseInt(ora_iniz.substring(3, 5));
int ora_fine = Integer.parseInt(ora_fin.substring(0, 2));
int minuto_fine = Integer.parseInt(ora_fin.substring(3, 5));
int size = id_nome_op.length;//array id
for(int i = 1; i< size; i++){
if (i == 1) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
} else if (i == 2) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
startTime.add(Calendar.DATE, 1);
} else if (i == 3) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
startTime.add(Calendar.DATE, 2);
}
startTime.set(Calendar.HOUR_OF_DAY, ora_inizio);
startTime.set(Calendar.MINUTE, minuto_inizio);
startTime.set(Calendar.MONTH, newMonth - 1);
startTime.set(Calendar.YEAR, newYear);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.HOUR_OF_DAY, ora_fine);
endTime.set(Calendar.MINUTE, minuto_fine);
WeekViewEvent event = new WeekViewEvent(id_appuntamento, getEventTitle(startTime), startTime, endTime);
event.setColor(colore_serv);
events.add(event);
}
}
cur.close();
db.close();
return events;
}
I custom listview with adapter extend BaseAdapter.
In method getView I have a button Add, and I set listener to it
item.btnAddBasket.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showChooseSize(products.get(pos), pos);
DialogFragmentCustom.setPosition(pos);
}
});
And I have two method, which are call when I press button Add.
public void showChooseSize(ProductInfo productInfo, int pos) {
ArrayList<Stock> stocks = new ArrayList<Stock>();
stocks.addAll(productInfo.getStock());
ArrayList<String> colors = new ArrayList<String>();
ArrayList<String> sizes = new ArrayList<String>();
if (stocks != null && stocks.size() > 0) {
for (int i = 0; i < stocks.size() - 1; i++) {
colors.add(stocks.get(i).getColorName());
sizes.add(stocks.get(i).getSize());
}
}
if (sizes != null && sizes.size() > 0) {
HashSet<String> hs_size = new HashSet<String>(); // remove elements
// duplicate
hs_size.addAll(sizes);
sizes.clear();
sizes.addAll(hs_size);
if (sizes.size() == 1) {
size = sizes.get(0);
} else {
for (int j = 0; j < sizes.size() - 1; j++) {
size = size + sizes.get(j) + ", ";
}
size = size + sizes.get(sizes.size() - 1);
}
a_sizes = null;
if (size.split(",") != null) {
a_sizes = size.split(",");
}
if (a_sizes == null) {
a_sizes[0] = "This product do not have size";
}
if (a_sizes != null && a_sizes.length > 0) {
Config.isWishList = true;
((Activity) context).setTheme(R.style.ActionSheetStyleIOS7);
ActionSheetChooseSize.setProductInfo(productInfo);
ActionSheetChooseSize.createBuilder(context, ((FragmentActivity) context).getSupportFragmentManager()).setOtherButtonTitles(a_sizes)
.setCancelableOnTouchOutside(true).setListener(this).show();
isShowChooseSize = true;
} else {
addToBag(productInfo, pos);
}
}
Method add product into Bag when press button Add, it inside my adapter
public void addToBag(ProductInfo productInfo, int pos) {
// Config.productSaleInfos.add(products.get(pos));
Config.productSaleInfos.add(productInfo);
Config.numProductSale = Config.productSaleInfos.size();
Config.numProductWishlist = Config.numProductWishlist - 1 < 0 ? Config.numProductWishlist - 1 : 0;
//SlideMenuFragment.setNumWish(Config.numProductWishlist + "");
new DeletionItemWishlist(context).execute(products.get(pos));
products.remove(pos);
notifyDataSetChanged();
float sumaryPrice = 0;
for (int i = 0; i < products.size(); i++) {
String price = products.get(i).getSalePrice();
int index = price.indexOf(",");
if (index > -1) {
price = price.replace(",", "");
}
float p = Functions.getFloatFromString(price);
sumaryPrice = sumaryPrice + p;
}
basket.setText(Config.numProductSale + "");
subtotal.setText(Html.fromHtml("<b>Subtotal: </b>" + "<font color=\"#FF7F00\">" + sumaryPrice + " ฿</font>"));
Functions.showLog(context, "add bag success!");
}
But notifyDataSetChanged(); is not working in my code. Can you help me please?
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.