【问题标题】:Create file of an ArrayList of java class创建java类的ArrayList文件
【发布时间】:2017-01-15 10:02:27
【问题描述】:

我正在制作一个 Android 应用程序,它会在某人生日时提醒我。

我现在可以添加名称和相应的日期。 但是,我目前坚持的是储蓄部分。我已经尝试查找一些解决方案,但无法将其移植到我的需要。由于它是一个 ArrayList 而不是一个简单的 String 它不能被序列化(如果我是正确的?)因此不能被保存。那么还有其他方法可以保存这种数据吗?

这是我的代码:

Item.java:

public class Item implements Serializable{
  private String name;
  private String date;

  public Item(String name, String date){
      this.name = name;
      this.date = date;
  }

  public String getName(){
      return name;
  }

  public String getDate(){
      return date;
  }

  public void setName(String name){
      this.name = name;
  }

  public void setDate(String date){
      this.date = date;
  }
}

MainActivity.java:

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
static RecyclerviewAdapter adapter;

static ArrayList<Item> itemList = new ArrayList<>();

private static String nameText;
private static String birthString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);

    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);

    recyclerView.setLayoutManager(llm);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    adapter = new RecyclerviewAdapter(itemList);
    recyclerView.setAdapter(adapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AddBirthday();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        month++;
        birthString = day + "-" + month + "-" + year;
        itemList.add(new Item(nameText, birthString));
        adapter.notifyDataSetChanged();
        saveArrayList(getContext(), itemList);
    }
}

private void AddBirthday() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Name");

    final EditText input = new EditText(this);
    input.setInputType(InputType.TYPE_CLASS_TEXT);
    builder.setView(input);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            nameText = input.getText().toString();

            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
}

public static void saveArrayList(Context c, ArrayList<Item> arrayList) {

}  
}

【问题讨论】:

  • 请说明您查找了哪些保存选项以及它们如何不适合您的需要。否则这听起来“太宽泛了”。
  • ArrayList 是一个可序列化的类。
  • 我已经尝试使用共享首选项来执行此操作,但读到这样做效率不高。然后我尝试使用文件输出,但并没有真正了解如何将它与 ArrayList 一起使用。我是否提供了足够的信息?我真的很想知道如何做到这一点

标签: java android file arraylist


【解决方案1】:

在 Java 中序列化或反序列化 ArrayList 没有问题:

    List<Item> list = new ArrayList<>();

    list.add(new Item("A", "2006"));
    list.add(new Item("B", "2016"));


    // Serialize
    FileOutputStream fos = context.openFileOutput("list.ser", Context.MODE_PRIVATE);
    ObjectOutputStream os = new ObjectOutputStream(fos);
    os.writeObject(list);
    os.close();
    fos.close();


    // Deserialize

    FileInputStream fileIn = context.openFileInput("list.ser");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    list = (List<Item>) in.readObject();
    in.close();
    fileIn.close();

    // Implement toString() in Item
    System.out.println(list);

【讨论】:

  • 但这是一个字符串列表,我使用的是一个对象 Item.java 的列表,所以我想知道如何将它放入文件中。
  • 我编辑了我的答案以证明它会以相同的方式工作。试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 2012-07-14
  • 2015-01-03
  • 1970-01-01
相关资源
最近更新 更多