问题
I am trying to save an ArrayList<Plant> (myPlantList) to a file with this method.
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();
}
}
I get an error (that does not crash the application) java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable. It is safe to assume that the BitmapDrawable it is referring to is the Plant.image. How do I serialize this ArrayList<Plant> including the Plant Images. I was reading about compressing BitMapDrawables with the .compress method, but I don't see how I could do that to each Plant while still saving the ArrayList<Plant> to 1 file.
Here is the relevant portion of the Plant Class.
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;
}
}
EDIT: The Drawable is obtained from the camera. A Picture is taken with the camera and stored as a Drawable in the newPlant Activity (below).
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;
}
}
}
}
来源:https://stackoverflow.com/questions/50081231/serialize-object-that-contains-a-drawable-android-java