Serialize包含Drawable Android Java的Object

时间:2018-04-28 21:28:18

标签: java android bitmap drawable serializable

我正在尝试使用此方法将ArrayList<Plant>myPlantList)保存到文件中。

public static void savePlants(Context c){
    try {
        FileOutputStream fOS = c.openFileOutput("plantArrList", c.MODE_PRIVATE);
        ObjectOutputStream oOS = new ObjectOutputStream(fOS);
        oOS.writeObject(myPlantList);
        oOS.close();
        fOS.close();
    } catch (IOException io) {
        io.printStackTrace();
    }
}

我收到错误(不会导致应用程序崩溃)java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable。可以安全地假设它所引用的BitmapDrawable是Plant.image。如何序列化此ArrayList<Plant>,包括植物图像。我正在阅读有关使用BitMapDrawables方法压缩.compress的信息,但我不知道如何在Plant保存ArrayList<Plant>的同时对每个Plant执行此操作文件。

以下是public class Plant implements Serializable{ private String name; private String date; private Drawable image; private String waterFrequency; public Plant(String n, Drawable i, String wF){ this.name = n; Date time = Calendar.getInstance().getTime(); this.date = MyApplication.gson.toJson(time); this.image = i; this.waterFrequency = wF; } } 类的相关部分。

newPlant

编辑:Drawable是从相机获得的。使用相机拍摄照片并将其作为Drawable存储在public class newPlant extends AppCompatActivity implements OnClickListener { private ImageButton plantCam; private FloatingActionButton savePlant; private EditText newPlantName; private EditText newPlantWF; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.newplant); plantCam = (ImageButton)findViewById(R.id.newPlantImage); savePlant = (FloatingActionButton)findViewById(R.id.savePlant); newPlantName = findViewById(R.id.newPlantName); newPlantWF = findViewById(R.id.newPlantWF); plantCam.setOnClickListener(this); savePlant.setOnClickListener(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Bitmap bitmap = (Bitmap)data.getExtras().get("data"); plantCam.setImageBitmap(bitmap); } public void onClick(View v){ switch(v.getId()){ case R.id.newPlantImage:{ Log.d("plantCam", "clicked"); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent,0); break; }case R.id.savePlant:{ Log.d("SavePlant", "clicked"); Plant temp = new Plant(newPlantName.getText().toString(), plantCam.getDrawable(), newPlantWF.getText().toString()); Log.d("plantBeingAdded", temp.toString()); MyApplication.myPlantList.add(temp); MyApplication.savePlants(this); Log.d("SavePlant", "finished saving plant" + MyApplication.myPlantList.toString() + " end list"); finish(); break; } } } } 活动(下方)中。

unix2dos

0 个答案:

没有答案