0

hows it going? I'm creating a little training app for a project, its going fine except for a formatting problem im getting. So, ive a csv file with a name and age for a client. an array is created from this, then I've got a scroll View containing a grid layout and i create Image Buttons from the client array. that's all fine. ive got an add client button at the end of this, the button and its activity work fine, but when you come back to the main screen, the buttons are all screwed up (huge, misplaced etc). So i figured i would loop through and delete all the buttons and repopulate the main screen, except, since i programmatically created them, i cant figure out how to find them to delete them. i tried setting their id's to the index of the array, but then i get a null pointer error.

Function where the buttons are created:

public void fillActivity_main(){
    if(listPopulated == false) { // check to see if its aready been created
        populateClientList();//fill array with client objects
        listPopulated = true;
    }
    //setup asset manager
    AssetManager am = getApplicationContext().getAssets();

    //Create the "GridLayout Image Board"
    GridLayout buttonBoard = (GridLayout) findViewById(R.id.buttonboard);
    int idealWidth = buttonBoard.getWidth(); //get width of the board
    int idealHeight = buttonBoard.getHeight() / 2;//same

    //create the Listeners, this is a place holder for now but will eventually use SetCurrentClient() (or maybe just switch to Start screen, with the current client?)
    View.OnClickListener imageClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("CLICK AT: " + v.getId());
            Client temp = clientList[v.getId()];

            Intent i = new Intent(getApplicationContext(), DisplayClient.class);
            System.out.println(temp.getName());
            i.putExtra("name", temp.getName());
            System.out.println(i.getStringExtra("name"));
            i.putExtra("age", Integer.toString(temp.getAge()));
            startActivity(i);

        }
    };
    int j = 0; //used the keep track of the id's we set for the buttons
    for (int i = 0; i < clientList.length; i++) {
        if (clientList[i] != null) {
            //creation and ID setting
            ImageButton imgbutton = (ImageButton) new ImageButton(this);
            imgbutton.setId(i);

            //Layout shit
            imgbutton.setImageResource(R.mipmap.ic_launcher);
            imgbutton.setMinimumWidth(idealWidth);
            imgbutton.setMinimumHeight(idealHeight);

            imgbutton.setOnClickListener(imageClickListener);


            //check and set image
            if(clientList[i].getClientImage().equals(" ")) {
                try{
                    imgbutton.set(am.openFd(clientList[i].getClientImage()));}
                    catch(Exception ex){
                         ex.toString();
               }
                Log.d("ClientImageCheck", "No picture found for " + clientList[i].getName());
            }
            buttonBoard.addView(imgbutton);
            j++;
        }


    }
    //create the new Client Button at the end of all the rest.
    Button newClientButton = (Button) new Button(this);
    newClientButton.setText("+");  // obvious
    newClientButton.setLayoutParams(new LinearLayout.LayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT));
    newClientButton.setWidth(idealWidth);
    newClientButton.setHeight(idealHeight);
    View.OnClickListener newClientListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), CreateClientForm.class);
            startActivityForResult(i, 199);
            //System.out.println("Doing good so far, leaving the createclient form bnut still in main");

        }
    }; // create listener
    newClientButton.setOnClickListener(newClientListener); // assign listener
    buttonBoard.addView(newClientButton); //add the button the buttonBoard, after all the clients have been added
}

Function where i do the deleting:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //Check which request we're responding to
    if (requestCode == 199) {
        // Make sure request was successful
        if (resultCode == RESULT_OK) { 
            // The user made a name and crap.
            Bundle extras = data.getExtras();
            String name = extras.getString("name");
            int age = extras.getInt("age");



            Client temp = new Client(name, age);
            addClientToArray(temp);
            System.out.println(name + "attempted add to array");

        }
    for(int i = 0; i<clientList.length; i++ ){
        View v = findViewById(i);
        ((ViewManager) v.getParent()).removeView(v);
    }
    fillActivityMain();
}

if i've got the logic right, the 'i' in the loop should be the appropriate id. Granted, the teach has kind of thrown us in the deep end for this project, never taken mobile apps or anything, so all this code is the result of me googling issues as i run into them. I've read the basics for Views, intents, etc, but there must be something i'm missing.

I've tried making the gridLayout that the buttons sit on a class variable so i could call it buttonBoard.removeView(i) or something. ive also tried `

for(int i = 0; i<clientList.length; i++ ){
  ImageButton btn = (ImageButton) findViewByid(i);
  ((ViewManager) v.getParent()).removeView(btn);
}
WillShriver
  • 51
  • 1
  • 1
  • 4
  • just realized that my idealwidith is just the width of the board, i think that may be part of the problem, but it doesnt cause a problem on first startup? – WillShriver Mar 21 '15 at 21:07
  • That fixed the size problem, but now it is just adding more buttons to the gridLayout, so if i can figure out how to delete the old ones, ill be good! – WillShriver Mar 21 '15 at 21:49

2 Answers2

0

Can you add the replacement images at the same time that you delete the existing images? If so, try this:

for(int i = 0; i < buttonBoard.getChildCount(); i++) {
ImageButton tempButton = (ImageButton) buttonBoard.getChildAt(i);
tempButton.setVisibility(View.INVISIBLE);
buttonBoard.addView(yourImageButtonHere, i); //adds a new ImageButton in the same cell you are removing the old button from
buttonBoard.removeView(tempButton);
}

This approach should also prevent the GridLayout from rearranging where the children are. I believe the default behavior if you delete a child view is that the GridLayout will re-order the children so there is not empty cell at the beginning of the grid. I hope that makes sense.

Chamatake-san
  • 551
  • 3
  • 10
0

There is so much wrong with this approach.

Mainly you don't have to create the ImageButtons manually and add them to the GridLayout. That is what recycled views such as GridView or RecyclerView are for. In fact you should use those to avoid OutOfMemoryError from having too much images in your layout.

But also you cannot just call setId(i) in the for loop. Android holds many ids already assigned and you can never be sure whether the id is safe. (Unless you use View.generatViewId())

And since you only want to remove all views added to your GridLayout why don't you just call removeAllViews() on the buttonBoard?

Lamorak
  • 10,957
  • 9
  • 43
  • 57