Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

aakarshrestha
aakarshrestha
6,509 Points

Why the checkbox state isn't consistent?

Here is my code. Checkbox state is not consistent when the app is refreshed. MainActivity File:

package com.example.aakarshrestha.topiapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView mListView;
    ArrayList<UserProfile> mUserNameArrayList;
    CustomAdapter mAdapter;
    Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mUserNameArrayList = getAllUserNames(); //create a function to get data in list

        mListView = (ListView) findViewById(R.id.listView);
        mAdapter = new CustomAdapter(this, mUserNameArrayList);
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        mListView.setAdapter(mAdapter);

        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refresh();
            }
        });

    }

    private ArrayList<UserProfile> getAllUserNames() {

        ArrayList<UserProfile> nameArrayList = new ArrayList<>();

        UserProfile userName = new UserProfile();
        userName.setUsername("Apple");
        nameArrayList.add(userName);

        UserProfile userName1 = new UserProfile();
        userName1.setUsername("Microsoft");
        nameArrayList.add(userName1);

        UserProfile userName2 = new UserProfile();
        userName2.setUsername("Linux");
        nameArrayList.add(userName2);

        UserProfile userName3 = new UserProfile();
        userName3.setUsername("HP");
        nameArrayList.add(userName3);

        UserProfile userName4 = new UserProfile();
        userName4.setUsername("Dell");
        nameArrayList.add(userName4);


        return nameArrayList;
    }

    private void refresh() {
        mListView.setAdapter(mAdapter);
    }
}

CustomAdapter File:

package com.example.aakarshrestha.topiapp;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;

import java.util.ArrayList;

public class CustomAdapter extends BaseAdapter{

    Context mContext;
    private  static ArrayList<UserProfile> mUserNameArrayList = new ArrayList<>();
    private LayoutInflater mInflater;
    ViewHolder mHolder;
    SharedPreferences mSharedPreferences;

    public CustomAdapter(Context context, ArrayList<UserProfile> userNameArrayList) {
        mContext = context;
        mUserNameArrayList = userNameArrayList;
        mInflater = LayoutInflater.from(mContext);

        mSharedPreferences = context.getSharedPreferences(MainActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }

    @Override
    public int getCount() {
        return mUserNameArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return mUserNameArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.listview_item, null);
            mHolder = new ViewHolder();
            mHolder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox);
            convertView.setTag(mHolder);

        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }

        mHolder.mCheckBox.setChecked(mSharedPreferences.getBoolean(mUserNameArrayList.get(position).getUsername(), false));

        mHolder.mCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences.Editor editor = mSharedPreferences.edit();

                if (mHolder.mCheckBox.isChecked()) {
                    editor.putBoolean(mUserNameArrayList.get(position).getUsername(), true);
                    editor.apply();
                } else {
                    editor.putBoolean(mUserNameArrayList.get(position).getUsername(), false);
                    editor.apply();
                }
            }
        });


        mHolder.mCheckBox.setText(mUserNameArrayList.get(position).getUsername());
        return convertView;
    }

    static class ViewHolder {
        CheckBox mCheckBox;
    }
}

UserProfile File;

package com.example.aakarshrestha.topiapp;

public class UserProfile {

    private String username;
    private boolean isSelected;


    public UserProfile() {
    }

    public UserProfile(String username, boolean isSelected) {
        this.username = username;
        this.isSelected = isSelected;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

    @Override
    public String toString() {
        return username;
    }
}

Any help is very much appreciated! I have spent so much time to figure it out but failed everytime!