Search code examples
androidbuttonandroid-studioandroid-arrayadapter

Adding a set of buttons to ListView and then setting adapter and setting button texts


Hi guys I'm having difficulty figuring out why my buttons wont display the right text and display junk code. I am running a serverRequest then creating the buttons after the details are gotten and I surely did test I am getting the right string back from the server.

public void getCourses(User user) {
    ServerRequest serverRequest = new ServerRequest(this);
    serverRequest.fetchUserCoursesDataInBackground(user, new getUserCallback() {
        @Override
        public void doneString(String[] returnedString) {
            if (returnedString == null) {
                System.out.println("DONE EMPTY");
            } else {
                userLocalStore.storeUserCourses(returnedString);
                final ListView listView = (ListView) findViewById(R.id.viewCourseList);
                final ArrayList<Button> list = new ArrayList<>();
                View v = getWindow().getDecorView();

                for (int i = 0; i < returnedString.length; i++) {
                    System.out.println("This is in for loop:" +returnedString[i]);
                    Button button = new Button(v.getContext());
                    button.setText(returnedString[i]);
                    button.setId(i);
                    button.setHeight(40);
                    button.setWidth(100);
                    list.add(button);
                }
                if (list.isEmpty()) {
                    System.out.println("List is empty bro");
                } else {
                    final ArrayAdapter adapter = new ArrayAdapter(v.getContext(), android.R.layout.simple_list_item_1, list);
                    listView.setAdapter(adapter);
                    System.out.println("Adding adapter");
                }
            }
        }

this is the whole code. I will show you what it is displaying on the application

this is the bug


Solution

  • I see 3 problems in this code:

    1st i assume java can mess this 1 up:

    replace> final ArrayList list = new ArrayList<>();

    with> final ArrayList list = new ArrayList();

    2nd you are using a layout "android.R.layout.simple_list_item_1" for the ArrayAdapter which is an xml layout including a text view thus you screenshot shows 2 text views and not buttons.

    3rd new ArrayAdapter() constructor takes a list of Strings. so if you...

    replace> final ArrayAdapter adapter = new ArrayAdapter(v.getContext(), android.R.layout.simple_list_item_1, list);

    with> final ArrayAdapter adapter = new ArrayAdapter(v.getContext(), android.R.layout.simple_list_item_1, returnedString);

    you will see buttons with the text that you are printing in your loop.