Clicking One Button Effecting All - android

So, I have this android app that is supposibly a board game. It has multiple buttons on it, and when selected, I want the selected one to gain a boarder. But, for some reason, when pressing one, it selectes everything or just doesn't deselect. What am I forgetting to do or doing wrong? Because logically, it shouldn't change anything other than that tile. Their is no For loop with setImageBitmap!
onClickListener:
//set onCLickListener on each tile
public void setOnClickListenerOnTile(TileClass tileI){
ImageButton tile = (ImageButton) findViewById (tileI.getId());
tile.setOnClickListener(new OnClickListener (){
#Override
public void onClick (View V){
Log.i(TAG, "tileOnClick");
ImageButton tile = (ImageButton) findViewById (V.getId());
/*Following code checks if...
*1. if no tile is selected
*2. if the tile that is clicked is also the one that is selected
*3. if the tile selected is different than the one that is clicked*/
//if 1. happens, then add boarder
if (selectedTile == 0){
Log.i(TAG, "First Choice: 1");
//set tile with boarder
tile.setImageBitmap(modifyTile(1,color.blue, mapTile[findTileById(tile.getId(), mapTile)].tilePic));
//remember what tile is selected
selectedTile = V.getId();
}
//else if 2. happens, then remove boarder
else if (selectedTile == V.getId()){
Log.i(TAG, "First Choice: 2");
//set tile without boarder
tile.setImageBitmap(mapTile[findTileById(tile.getId(), mapTile)].tilePic);
tile.setImageBitmap(blankTileBitmap);
tile.refreshDrawableState();
//remember what tile is selected
selectedTile = 0;
}
//else if 3. happens, then remove the boarder on the selectedTile and add boarder on the clickedTile
else if (selectedTile != V.getId() && selectedTile != 0){
Log.i(TAG, "First Choice: 3");
//remove old boarder
ImageButton tempIB = (ImageButton) findViewById (selectedTile);
tempIB.setImageBitmap(mapTile[findTileById(selectedTile, mapTile)].tilePic);
//add new boarder
tile.setImageBitmap(modifyTile(1,color.blue, mapTile[findTileById(tile.getId(), mapTile)].tilePic));
//remember what tile is selected
selectedTile = V.getId();
}
}
});
}
modifyTile:
//Method function:
//to modify a tile
//modificationNum code:
//1: add boarders
//2: remove boarders
//Param: accepts the type of modifications as first parameter,
//color ID as listed in color resource (not Color),
//and a bitmap of the tile
//
public Bitmap modifyTile (int modificationNum, int color, Bitmap bitmap){
int count, count2;
Log.i(TAG, "modifyTile has been called!");
//first, find out which modification todo
//if modificationNum == 1, then it is to add a border
if (modificationNum == 1){
if (bitmap == null){
Log.i(TAG, "null error");
}
//set tile boarders on the top
for (count = 1; count < tileLength; count++){
bitmap.setPixel(count, 1, getResources().getColor(color));
}
//sides...
for (count = 1; count < (tileLength); count++){
bitmap.setPixel(1, count, getResources().getColor(color));
bitmap.setPixel((tileLength - 1), count, getResources().getColor(color));
}
//set tile boarders on the bottom
for (count = 1; count < tileLength; count++){
bitmap.setPixel(count-1, tileLength-1, getResources().getColor(color));
}
}
getAllTileId:
//get id of every tile (may take a long time) (not done)
public int[] getAllTileId (){
int count, count2;
Log.i(TAG, "getAllTileId has been called!");
//set up variables...
//have to set up a view for TableLayout so that I can find the tile's id using Tags (it has to be it's childs)
View v = (TableLayout) findViewById (R.id.mapTable);
ImageButton imageButton;
int temp, globalCount;
int results[] = new int[50];
for (count = 0, globalCount = 0; count < 9; count++ ){
if (count % 2 == 0){
temp = 6;
}
else{
temp = 5;
}
for (count2 = 0; count2 < temp; count2++, globalCount++){
imageButton = (ImageButton) v.findViewWithTag ("land" + (count + 1) + (count2 + 1));
results[globalCount] = imageButton.getId();
Log.i(TAG, "land #" + (count+1) + (count2+1) + "'s id = " + results[globalCount]);
}
}
Log.i(TAG, "getAllTileId length" + results.length);
return results;
}
findTileById:
//find a tile in an array using it's id
public int findTileById (int id, TileClass[] map){
Log.i(TAG, "findTileById has been called!");
int count=0;
for (count = 0; count < map.length && map[count].getId() != id; count++);
if (count >= map.length){
Log.i(TAG, "findTileById FAIL");
}
return count;
}
EDIT:
Here is onCreate:
//onCreate
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_board);
//**TEST AREA, DELETE AFTER**
//**TEST AREA END**
//get the way to convert from dp to pixels and set up tileLength (in pixels)
metrics = getResources().getDisplayMetrics();
dpToPixels = metrics.density;
tileLength = (int) Math.ceil(44 * dpToPixels);
//set tilePic dimensions
tilePic = new int[tileLength * tileLength];
Log.i(TAG, "tileLength = " + tileLength + " and dpToPixels = " + dpToPixels);
//set up colors
blue = getResources().getColor(R.color.blue);
//set up blank selected tile bitmap
selectedTileBitmap = Bitmap.createBitmap(tileLength, tileLength, Bitmap.Config.ARGB_8888);
//set tile boarders
selectedTileBitmap = modifyTile (1, color.blue, selectedTileBitmap);
//set up blank tile bitmap
blankTileBitmap = Bitmap.createBitmap(tileLength, tileLength, Bitmap.Config.ARGB_8888);
for (count = 0; count < tileLength; count++){
for (count2 = 0; count2 < tileLength; count2++){
blankTileBitmap.setPixel(count, count2, getResources().getColor(color.white));
}
}
//first... get map tile ids...
mapTileId = new int [50];
mapTileId = getAllTileId ();
//set up mapTile
mapTile = new TileClass[50];
for (count = 0; count < 50; count++){
//first... get the tile (which is an ImageButton)
tempIB = (ImageButton) findViewById (mapTileId[count]);
//next step is to create a stringModifier to get the coordinates of the tile through it's tag
stringModifier = new StringBuilder (tempIB.getTag().toString());
//create the tile...
mapTile [count] = new TileClass (tempIB.getId(), Integer.parseInt(stringModifier.substring(4, 5)), Integer.parseInt(stringModifier.substring(5,6)), blankTileBitmap);
Log.i(TAG, "count = " + count);
Log.i(TAG, "test count" + mapTile[count].getId());
}
//set up all the bitmap of the tiles on screen
for (count = 0; count < 50; count++){
tempIB = (ImageButton) findViewById (mapTile [count].getId());
tempIB.setImageBitmap(mapTile[count].tilePic);
}
Log.i(TAG, "Finished setting up mapTile.");
//get id of every tile
//set up each tile with an onClick
for (count = 0; count < 50; count++){
setOnClickListenerOnTile(mapTile[count]);
}
}

Ok, I found my problem.
The user is able to click a button before onCreate is done, which is also before a lot of the arrays that are used to find / initialize other buttons are initialized. So, when the user clicks the button too fast, the array references to every button.

Related

How can i add as well as remove layout pragmatically in android?

I want to work as AutoCompleteTextview. But I am not using auto complete text view in my project. I have used edit text and taking it the value for sorting the value of adapter using those values of adapter I am creating a dynamic button. But actually, I want to delete dynamically created button. When a user enters new value in edit text at that case it sorts new value in adapter according to the button has to created. But, my problem is that dynamically created button does not get deleted when a user enters new text on edit text view. It has to looking like this:
if (!s.equals("")) {
final String query = s.toString().trim();
filteredTags.clear();
((ViewManager) btnTag.getParent()).removeView(btnTag);
for (int i = 0; i < TagArray.size(); i++) {
final String tagName = TagArray.get(i).gettagName();
if (tagName.contains(query)) {
filteredTags.add(TagArray.get(i));
}
}
count1 = filteredTags.size();
layout = (LinearLayout) dialog.getCustomView().findViewById(R.id.layoutTags);
layout.setOrientation(LinearLayout.VERTICAL); //Can also be done in xml by android:orientation="vertical"
layout.setWeightSum(1);
float rowneed = ((float) count1 / 5);
k = 0;
for (int i = 0; i < ceil(rowneed); i++) {
row1 = new LinearLayout(getContext());
row1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
/* layout.setVisibility(View.VISIBLE);
row.setVisibility(View.VISIBLE);*/
for (int j = 0; j < 5; j++) {
btnTag = new Button(getContext());
btnTag.setHeight(15);
btnTag.setWidth(0);
btnTag.setMinimumWidth(155);
btnTag.setMinimumHeight(135);
mTagList1 = new ArrayList<>();
if (k < count1) {
btnTag.setText(filteredTags.get(k).gettagName());
btnTag.setId(k);
k++;
btnTag.setVisibility(View.VISIBLE);
} else {
btnTag.setVisibility(View.INVISIBLE);
}
Log.e("count", " " + k + " " + count1 + " " + ceil(rowneed) + " " + edtTag.getText().toString());
btnTag.setTextSize(7);
btnTag.setGravity(0);
row1.addView(btnTag);
}
layout.addView(row1);
}
for (int btnId = 0; btnId < filteredTags.size(); btnId++) {
btnTag = (Button) dialog.getCustomView().findViewById(btnId);
final int finalId1 = btnId;
btnTag.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TagNameArray.add(new Tags(filteredTags.get(finalId1).gettagId(), filteredTags.get(finalId1).gettagName()));
// Log.e("button","Button clicked index = " + finalId +" "+ TagArray.get(finalId1).gettagName()+" "+TagNameArray.size());
}
});
}
}
Add this line of code :
layout.removeAllViews();
layout.invalidate();
row.removeAllViews();
row.invalidate();
This might help you, give me a feedback for what you got, wish I help you
set a dynamic tag for btnTag for example
btnTag.setTag(DynamicTagInt++);
and then
row1.removeView(btnTag.findViewById(DynamicTagInt));
//DynamicTagInt= the desired button that you want to delete
or by the ID of the button for example
row1.removeView(btnTag.findViewWithTag(k));

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

How to update first and second page view in view pager.?

I have View-pager with nine images. I am setting images in view using bitmap. When i choose nine images from gallery first time, its show all nine images perfectly. Also when i choose another nine images from gallery with keep first first or second view same,view-pager display with updated images. But my problem is when I am trying to change all nine images with first and second. they display error like OutOfMemoryEror. so my question is. How to update first and second(next) view in view-pager. any one can help me.? than x in advance.
Activity code
if(ab != null){
arr = ab.split(",");
for(int i = 0; i <arr.length; i++){
// Toast.makeText(getApplicationContext(), "done: "+ arr[i], Toast.LENGTH_LONG).show();
imgFile = new File(arr[i]);
if(imgFile.exists()){
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
System.out.println("This my - bit : "+myBitmap+"ara - lenth : "+arr.length);
bitmapArray.add(myBitmap);
System.out.println("This bit-aray : "+bitmapArray.size()+" : "+bitmapArray.size() + "ara pos : "+arr[i]);
//Toast.makeText(getApplicationContext(), "This is bitmap array : "+ bitmapArray, Toast.LENGTH_LONG).show();
}
}
}else{
}
Adapter code
if(l == 1){
// layout.removeView(imageView);
// container.removeView(layout);
if(bitmapArray != null){
for(int j = 0; j < bitmapArray.size(); j++){
if(j == position){
j = position;
imageView.setImageBitmap(bitmapArray.get(j));
}
}
} //Toast.makeText(getApplicationContext(), ""+bitmapArray.get(j)+"size "+bitmapArray.size(), Toast.LENGTH_SHORT).show();
else{
imageView.setImageResource(res[position]);
bitarray.clear();
bitmapArray.clear();
sharedpreferences.edit().remove("imgpath").commit();
}
}
if(l == 2){
//layout.removeView(imageView);
//container.removeView(layout);
if(bitmapArray != null){
for(int j = 0; j < bitmapArray.size(); j++){
if(j == position){
j = position;
imageView.setImageBitmap(bitmapArray.get(j));
}
}
} //Toast.makeText(getApplicationContext(), ""+bitmapArray.get(j)+"size "+bitmapArray.size(), Toast.LENGTH_SHORT).show();
else{
imageView.setImageResource(res[position]);
bitarray.clear();
bitmapArray.clear();
sharedpreferences.edit().remove("imgpath").commit();
}
}

Any memory efficient method to play frame animation on Android?

I have a requirement that asks for a looping of 100 images that are around 13kb each. At first I tried to use AnimationDrable and load them programatically like this:
public void animationPlay(){
frameAnimation = new AnimationDrawable();
String index = "00000";
for(int i = 1; i <= 100; i++)
{
if(i<10 ){
index = "0000" + i;
}else if(i< 100){
index = "000" + i;
}else if(i< 10000){
index = "00" + i;
}
String finalString = "acting_10_confetti" + index;
int frameIdentifier = getResources().getIdentifier(finalString, "drawable", getPackageName());
frameAnimation.addFrame(getResources().getDrawable(frameIdentifier), 70);
}
ImageView view = (ImageView) findViewById(R.id.imageView);
view.setBackground(frameAnimation);
frameAnimation.start();
}
The problem is as soon as I add the 10th frame, the app crashes with Out of Memory Error.
Has anyone came across this problem before?

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.

Categories

Resources