需要有关保存数组列表的更多详细信息

时间:2019-01-15 23:07:15

标签: java android android-studio mobile

相关:Save ArrayList to SharedPreferences

我有一个用于输入值的编辑文本,一个用于将其添加到ArrayList并保存的按钮,一个用于检索和显示该值的按钮,以及一个用于重置ArrayList的按钮。但是收集按钮会不断显示2。

public class test extends AppCompatActivity {

    ArrayList arrayList = new ArrayList();

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


        Button button = findViewById(R.id.create);
        Button button1 = findViewById(R.id.recup);
        Button button2 = findViewById(R.id.reset);
        final EditText editText = findViewById(R.id.editText);
        final TextView textView = findViewById(R.id.textView);

        //Initialize ArrayList
        loadData();

        //Button for add variable in arraylist and save
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nombre = editText.getText().toString();
                arrayList.add(nombre);

                saveData();

            }
        });

        //Button for look arrayList.get(0)
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText(String.valueOf(arrayList.get(0)));
            }
        });

        //Button for reset
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.remove("task list");
                editor.commit();
            }
        });
    }

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

    //load data
    private void loadData() {
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("task list", null);
        Type type = new TypeToken<ArrayList>() {
        }.getType();
        arrayList = gson.fromJson(json, type);

        }
    }

0 个答案:

没有答案