如何使用共享首选项保存列表视图

时间:2019-11-22 16:23:29

标签: java sharedpreferences

我已经制作了一个简单的购物清单应用程序,用户可以在其中向列表视图添加商品。我的问题是,当我离开应用程序时,项目无法保存。我想我需要使用共享的首选项,但是实现起来并没有太多的希望(我对编码来说是相当陌生的)。如果有人知道如何实现共享的首选项,那么我的项目就会保存起来。

我的代码:

public class CreateAList extends AppCompatActivity {
    //ArrayList for data
    private ArrayList<String> list = new ArrayList<>();
    ListView list_view;
    ArrayAdapter arrayAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_alist);
        //find view by id
        list_view = findViewById(R.id.list_view);
        arrayAdapter = new ArrayAdapter(CreateAList.this, android.R.layout.simple_list_item_1,list);
        list_view.setAdapter(arrayAdapter);



        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {

                //Inflating is the process of adding a view(.xml) to activity on runtime
                PopupMenu popupMenu = new PopupMenu(CreateAList.this,view);
                popupMenu.getMenuInflater().inflate(R.menu.pop_up_menu,popupMenu.getMenu());

                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {

                            switch (menuItem.getItemId()){

                                case R.id.item_update:
                                    //function for update
                                    AlertDialog.Builder builder = new AlertDialog.Builder(CreateAList.this);
                                    View v = LayoutInflater.from(CreateAList.this).inflate(R.layout.item_dialog,null,false);
                                    builder.setTitle("Update Item");
                                    final EditText editText = v.findViewById(R.id.editItem);
                                    editText.setText(list.get(i));


                                    //set custom view to dialog
                                    builder.setView(v);

                                    builder.setPositiveButton("Update", new DialogInterface.OnClickListener(){
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!editText.getText().toString().isEmpty()){
                                                list.set(i, editText.getText().toString().trim());
                                                arrayAdapter.notifyDataSetChanged();
                                                Toast.makeText(CreateAList.this, "Item Updated", Toast.LENGTH_SHORT).show();
                                            }else{
                                                editText.setError("add item here!");
                                            }
                                        }
                                    });

                                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int i) {
                                            dialog.dismiss();
                                        }
                                    });

                                    builder.show();

                                    break;

                                case R.id.item_delete:
                                    //function for delete
                                    Toast.makeText(CreateAList.this, "Item Deleted", Toast.LENGTH_SHORT).show();
                                   list.remove(i);
                                   arrayAdapter.notifyDataSetChanged();

                                   break;

                            }

                        return true;
                    }
                });
                    popupMenu.show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.add_item:

                //function to add

                addItem();

                break;

        }

        return true;
    }
//method for adding item
    private void addItem() {
        AlertDialog.Builder builder = new AlertDialog.Builder(CreateAList.this);
        builder.setTitle("Add new Item");

        View v = LayoutInflater.from(CreateAList.this).inflate(R.layout.item_dialog,null,false);

        builder.setView(v);
        final EditText editItem = v.findViewById(R.id.editItem);
        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (!editItem.getText().toString().isEmpty()){
                    list.add(editItem.getText().toString().trim());
                    arrayAdapter.notifyDataSetChanged();
                }else{
                    editItem.setError("Add Item Here!");
                }

            }
        });
}

2 个答案:

答案 0 :(得分:1)

最好通过教程了解共享偏好。这样您将学到更多。还要寻找Android提供的用于存储数据的SQLite数据库。我认为如果列表视图中有简单对象,那将是更好的方法。

这是一个很好的教程:https://medium.com/@evancheese1/shared-preferences-saving-arraylists-and-more-with-json-and-gson-java-5d899c8b0235

答案 1 :(得分:0)

void putSharedPreferencesStringSet(字符串键,设置值)

{
    SharedPreferences.Editor edit = getContext().getSharedPreferences("SHARED_PREFERENCE_NAME", 0).edit();
    edit.putStringSet(key, value);
    edit.apply();
}

void putSharedPreferencesStringSet(String key, String value)
{
    SharedPreferences.Editoredit = getContext().getSharedPreferences("SHARED_PREFERENCE_NAME", 0).edit();
    edit.putString(key, value);
    edit.apply();
}

String getSharedPreferencesString(String key)
{
    SharedPreferences prefs = AppConstants.appContext.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, 0);
    return prefs.getString(key, 0);
}

void removeSharedPreferencesString(String key)
{
    SharedPreferences edit = AppConstants.appContext.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, 0);
    edit.remove(key);
    edit.apply();

}

//以上功能是关于add,get和remove sharedPrefrences的

将商品添加到购物车中时,如果需要使用数据库的另一种方法