复选框状态未正确保存在SharedPreference中

时间:2019-04-06 16:33:34

标签: java android list checkbox sharedpreferences

我有一个使用列表的RecyclerViewer。在列表中有复选框。如果用户按下复选框,则更新后的列表将保存在sharedPreferences中。当我返回该活动时,仍会选中这些框,但是当我选择新的复选框时,只会传递新选中的框。如果我也希望保存旧复选框,则必须取消选中并重新选中它们。知道为什么吗?

下面是代码。

public class InterestActivity extends AppCompatActivity {

    private static final String TAG = "InterestActivity";
    SharedPreferences prefs;
    SharedPreferences.Editor mEditor;
    String key = "Key";

    //const
    private static final int VERIFY_PERMISSIONS_REQUEST = 1;

    //location
    private FusedLocationProviderClient fusedLocationClient;

    //Firebase
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mRef;
    private FirebaseMethods mFirebaseMethods;
    private String userID;

    private Context mContext;


    List<Interest> lstInterest;
    StringBuffer interestList = null;
    //RecyclerViewAdapter adapter;

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

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mContext = InterestActivity.this;

        if (checkPermissionArray(Permissions.PERMISSIONS)) {

        } else {
            verifyPermissions(Permissions.PERMISSIONS);
        }
        //Firebase
        setupFirebaseAuth();


        //adapter = new RecyclerViewAdapter(this, lstInterest);


        lstInterest = new ArrayList<>();

        lstInterest.add(new Interest("BMX", R.drawable.bmx_tn, false));
        lstInterest.add(new Interest("Bowling", R.drawable.bowling_tn, false));
        lstInterest.add(new Interest("Camping", R.drawable.camping_tn, false));
        lstInterest.add(new Interest("Dance", R.drawable.dance_tn, false));
        lstInterest.add(new Interest("Fishing", R.drawable.fishing_tn, false));
        lstInterest.add(new Interest("Frisbee Golf", R.drawable.frisbeegolf_tn, false));
        lstInterest.add(new Interest("Golfing", R.drawable.golfing_tn, false));
        lstInterest.add(new Interest("Hunting", R.drawable.hunting_tn, false));
        lstInterest.add(new Interest("Kayaking", R.drawable.kayaking_tn, false));
        lstInterest.add(new Interest("Mountain Biking", R.drawable.mountainbiking_tn, false));
        lstInterest.add(new Interest("Programming", R.drawable.programming_tn, false));
        lstInterest.add(new Interest("Rock Climbing", R.drawable.rockclimbing_tn, false));
        lstInterest.add(new Interest("Skateboarding", R.drawable.skateboarding_tn, false));
        lstInterest.add(new Interest("Slack Line", R.drawable.slackline_tn, false));
        lstInterest.add(new Interest("Video Games", R.drawable.videogames_tn, false));
        lstInterest.add(new Interest("Yoga", R.drawable.yoga_tn, false));

        loadData();

        RecyclerView interestRv = (RecyclerView) findViewById(R.id.interest_recyclerview_id);
        final RecyclerViewAdapter interestAdapter = new RecyclerViewAdapter(this, lstInterest);

        interestRv.setLayoutManager(new GridLayoutManager(this, 2));
        interestRv.setAdapter(interestAdapter);


        Button btnButton = (Button) findViewById(R.id.btnInterestSave);
        btnButton.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {


                interestList = new StringBuffer();

                for (Interest i : interestAdapter.checkedInterest) {


                    interestList.append(i.getTitle());
                    interestList.append(",");
                    saveData();

                    Log.d(TAG, "onClick: interest adapter " + interestAdapter.checkedInterest);

                }
                if (interestAdapter.checkedInterest.size() > 0) {
                    Toast.makeText(InterestActivity.this, interestList.toString(), Toast.LENGTH_SHORT).show();

                    addUserInterest(interestList.toString());

                }

                Intent intent = new Intent(InterestActivity.this, MainActivity.class);
                startActivity(intent);
                //getUserLocation();


            }
        });


    }

    private void saveData() {
        SharedPreferences sharedPreferences = getSharedPreferences("shared preference", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(lstInterest);
        editor.putString("task list", json);
        editor.apply();
    }

    private void loadData() {


        SharedPreferences sharedPreferences = getSharedPreferences("shared preference", MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("task list", null);
        Type type = new TypeToken<List<Interest>>() {
        }.getType();
        lstInterest = gson.fromJson(json, type);


    }


         /*
     `````````````````````````````````````firebase```````````````````````````````````````````````
    */

    //Send data to firebase interest DB.
    private void addUserInterest(String interest) {

        Log.d(TAG, "addUserInterest: use to save interest to database user_interest_post");


        mRef.child(mContext.getString(R.string.dbname_user_interest_post))
                .child(userID)
                .child(mContext.getString(R.string.string_interest))
                .setValue(interest);

        mRef.child("user_profile_post")
                .child(userID)
                .child("interest")
                .setValue(interest);


    }  

下面是我从recyclerViewer获取检查状态的地方。我相信问题就在这里。

        holder.setItemClickListener(new ItemClickListener(){
            @Override
            public void onItemClick(View v, int pos){

                CheckBox chk = (CheckBox) v;



                if (chk.isChecked()) {
                    checkedInterest.add(mData.get(pos));

                    Log.d(TAG, "onItemClick: checked state 1 " + checkedInterest);
                }else if(!chk.isChecked()){
                    checkedInterest.remove(mData.get(pos));
                    Log.d(TAG, "onItemClick: checked state 2 " + checkedInterest);
                }


                //Integer pos =  (int) holder.chk.getTag();
                //Toast.makeText(mContext, mData.get(position).getTitle() + " Clicked!", Toast.LENGTH_SHORT).show();

                if (mData.get(pos).isSelected()) {
                    mData.get(pos).setSelected(false);
                } else {
                    mData.get(pos).setSelected(true);

                }
            }
        } );

1 个答案:

答案 0 :(得分:0)

创建布尔值:

已检查私有布尔值= false;

然后将侦听器添加到您的复选框:

chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       if (buttonView.isChecked()){
           Log.d(TAG, "button is checked!");
           checked = true; //Change boolean value 'True" because it's checked!
       }else {
           Log.d(TAG, "button is not checked!");
           checked = false; //Change boolean value 'False' because it's unchecked!
       }            
    }
});

现在,您可以通过以下方式检查您的复选框是否已选中:

if(checked){
    //condition true
}else{
    //condition false
}

如果您也想将复选框状态保存在SharedPreferences中,只需在您的SharedPref中输入 Boolean 值“ checked ”。