使用SharedPreferences保存变量

时间:2019-07-12 12:50:22

标签: android sharedpreferences

我想使用SharedPrefences记录数据,我想在我选择的RecyclerView中注册“ ChipNumberRooms”键。但是它不会保存数据。当我单击RecyclerView时,我希望它进行注册。

  @Override
    protected void onCreate(Bundle savedInstanceState) {
 SharedPreferences prefs = getSharedPreferences("...", Context.MODE_PRIVATE);

        final String chipNumberNew =prefs.getString("ChipNumberrr", "0");
}

      recyclerViewNew.addOnItemTouchListener(new ProductsNewAdapter(this,
                recyclerViewNew, new ClickListener() {
            @Override
            public void onClick(View view, final int position) {

                DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

DatabaseReference refRooms = mDatabase.child(chipNumberNew).child("Rooms");

SharedPreferences prefs = getSharedPreferences("...", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();

                editor.putString("ChipNumberRooms", chipNumberNew);
                editor.commit();

                refRooms.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
              for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                     ....
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

1 个答案:

答案 0 :(得分:-1)

首先,创建一个AppPreference类,并在您的类中创建一些getter和setter,如下所示:-

<source src="https://vid.ly/7f4q4w" type="video/webm">

这是我根据您的需要更改代码的代码,然后在其中设置方法的值以获取价值,只需调用get方法