如何从共享首选项保存和显示项目

时间:2020-08-21 13:19:58

标签: android listview arraylist gson sharedpreferences

说明:
我已经使用共享首选项GSON概念的概念在列表视图中使用“心脏图标”进行保存/取消保存。 My Design(fig.1) 。我只能像 Retrieved titles in a listview (fig.2) 中那样显示标题,但无法检索带有如图3所示标题的心形图标。 The desired output (figure 3)

问题:我在列表视图中显示共享首选项中的图像时遇到问题。

以下代码块来自CustomListAdapter ::

public class CustomListAdapter extends ArrayAdapter {
    private final Activity context;
    private final String[] infoArray;
    List<Object> selectlist = new ArrayList<Object>();
    public static final String PREFERENCE_NAME = "favourite";
    private final SharedPreferences sharedpreferences;
    List<Object> favourites;
    int[] image;

    public CustomListAdapter(Activity context, String[] infoArrayParam, int[] imageIds){

        super(context,R.layout.listview_row , infoArrayParam);
        this.context=context;
        this.infoArray = infoArrayParam;
        this.image = imageIds;

        sharedpreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

    }


    public View getView(final int position, View view, ViewGroup parent) {
        
        LayoutInflater inflater = context.getLayoutInflater();
        final View rowView = inflater.inflate(R.layout.listview_row, parent, false);
        TextView nameTextField = (TextView) rowView.findViewById(R.id.textView2);


        final ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView4);
        imageView.setOnClickListener(new View.OnClickListener(){
            @SuppressLint({"NewApi", "ResourceType"})
            @Override
            public void onClick(View view) {
                view.setSelected(!view.isSelected());
                boolean favSelected = view.isSelected();

                if (favSelected) {
                    imageView.setImageResource(R.drawable.ic_baseline_favorite1_24);
                     imageView.setTag(position);
                     imageView.setId(R.drawable.ic_baseline_favorite1_24);
                     Object chk = infoArray[position];
                    selectlist.add(chk);
                    view.setSelected(true);
                    saveData(context, selectlist);

                }
               else{
                    imageView.setImageResource(R.drawable.ic_baseline_favorite_border_24 );
                    imageView.setTag(position);
                    imageView.setId(R.drawable.ic_baseline_favorite_border_24);
                    view.setSelected(false);
                    removeFavorite(context,selectlist);

                    

                }


            }

            private boolean saveData(Context context, List<Object> selectlist){
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
                SharedPreferences.Editor aSharedPreferencesEdit = sharedPreferences.edit();
                Gson gson = new Gson();
                String json = gson.toJson(selectlist);
                aSharedPreferencesEdit.putString("task list",json);
                aSharedPreferencesEdit.apply();

                return false;
            }


            private ArrayList<Object> loadData(Context context){
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
                Gson gson = new Gson();
                String json = sharedPreferences.getString("task list", null);
                System.out.println("The value of jsonnnnnnnn is " + json);
                Type type = new TypeToken<List<Object>>(){}.getType();
                System.out.println("The value of typpppppppppe is " + type);
                return gson.fromJson(json, type);
            }

            public void removeFavorite(Context context, List<Object> selectlist) {

                ArrayList<Object> favourites = loadData(context);
                if (favourites != null) {
                    favourites.remove(selectlist);
                    saveData(context, favourites);
                }
            }







            private boolean favOnClick(int position,View v, List<Object> selectlist){
                ImageView button = (ImageView) v.findViewById(R.id.imageView4);
                String tag = button.getTag().toString();
                if (tag.equalsIgnoreCase(valueOf(position))){
                    saveData(context, selectlist);
                    button.setTag(position);
                    button.setImageResource(R.drawable.ic_baseline_favorite1_24);
                }
                else {
                    removeFavorite(context,selectlist);
                    button.setTag(position);
                    button.setImageResource(R.drawable.ic_baseline_favorite_border_24);


                }
                return true;
            }
        });
        nameTextField.setText(infoArray[position]);
        imageView.setImageResource(image[position]);
        return rowView;

    }


}

以下代码块用于DashBoard:

public class DashBoard extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
    ListView listView;
    Toolbar mActionBarToolBar;
    Context context;
    List<Object> selectlist ;
    private ArrayAdapter<Object> adapter;


    int[] drawableIds = new int[]{R.drawable.ic_baseline_favorite1_24, R.drawable.ic_baseline_favorite_border_24};

    String[] infoArray = {
        //Listed


    };

    protected void onCreate(Bundle savedInstanceState) {

        SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

        CustomListAdapter listItems = new CustomListAdapter(this, infoArray,drawableIds);
        listView = (ListView) findViewById(R.id.listviewId);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                //To do

        }
        });

        listView.setAdapter(listItems);

     }

     @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
     public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
                switch (id) {
                    case R.id.navigation_notifications:

                        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                        Gson gson = new Gson();
                        String json = sharedPreferences.getString("task list", null);
                        System.out.println("The value of jsonnnnnnnn is " + json);
                        Type type = new TypeToken<List<Object>>(){}.getType();
                        System.out.println("The value of typpppppppppe is " + type);
                        selectlist = gson.fromJson(json, type);
                        if (selectlist == null){
                            selectlist= new ArrayList<>();

                         }
                        adapter = new ArrayAdapter<Object>(DashBoard.this,
                                android.R.layout.simple_list_item_1, (selectlist));

                        listView.setAdapter(adapter);


                    }
                return false;
            }
        }

      
      

参考: How to save dynamically added items in Listview with sharedpreferences?
任何帮助将不胜感激。

谢谢。

0 个答案:

没有答案