how to save a hashmap and an image to the same file - java

I wanted to know how to save and load a HashMap(String, List(Object)) to a file.The Object class is shown below:
public class FlashCard implements Serializable{
private String question;
private Picture picture;
private ArrayList<String> answers = new ArrayList<>();
private ArrayList<Picture> pictures = new ArrayList<>();
public FlashCard(){
}
// Method should set a list of answers
public void setAnswers(ArrayList<String> answers){
this.answers = answers;
}
// Method should add an answer to a list of answers
public void setAnswer(String answer){
answers.add(answer);
}
// Method should set a list of answers
public void setPictures(ArrayList<Picture> pictures){
this.pictures = pictures;
}
// Method should add an answer to a list of answers
public void setPicture(Picture picture){
pictures.add(picture);
}
public void setQuestion(String question){
this.question = question;
}
public ArrayList<String> getAnswers(){
return answers;
}
public ArrayList<Picture> getPictures(){
return pictures;
}
public String getQuestion(){
return question;
}
}
The picture class converts from any picture format to a BufferedImage image.I read that the BufferedImage class is not serializable. Does it mean that I cannot save both of them into the same file?Thanks.

You should be able to extend BufferedImage and have that class implement Serializable. Something like this:
public class SerializableImage extends BufferedImage implements Serializable{
...
}
Then use SerializableImage in place of BufferedImage and you should be good to go!

Related

Make list of non public class

I have a java file in which I have two classes in which one is public and another is default like this -
import java.util.List;
public class TaskAnswers {
private float ratings;
private List<Image> imageList;
public float getRatings() {
return ratings;
}
public void setRatings(float ratings) {
this.ratings = ratings;
}
public List<Image> getImageList() {
return imageList;
}
public void setImageList(List<Image> imageList) {
this.imageList = imageList;
}
}
class Image {
private String image;
private String caption;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
I want to make a list of Image class type in another class. And when we write like this than that java file is called as what?
Java only allows one public class per source file. Try making the Image class public and you will get compiler errors. You need to call the file TaskAnswers.java since it is a requirement that the name of the source file match the name of the public class contained in that file.
As user #NwDx mentioned the Image class is package protected, which means you will only be able to instantiate it from other Java classes that share the same package. If you need to access the Image class in a separate package, it would be a better design choice to move it into its own public class file rather than making it an inner class.
And the code example you posted in your original problem looks just fine.
If you need the class Image in other packages, you have to make it public, but in this case you need to move it to an inner class of TaskAnswers or make an own class (file).
public class TaskAnswers {
private float ratings;
private List<Image> imageList;
public float getRatings() {
return ratings;
}
public void setRatings(float ratings) {
this.ratings = ratings;
}
public List<Image> getImageList() {
return imageList;
}
public void setImageList(List<Image> imageList) {
this.imageList = imageList;
}
public static class Image {
private String image;
private String caption;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
}
For more information please look in the Java Nested Classes Tutorial
Image class is called as utility class and TaskAnswers is called as functionality implementation class you can use it in following manner and you are using the concept of high cohesion
List<Image> list = new ArrayList<Image>();

Read and write an ArrayList of ArrayLists containing Parcelable Objects to pass in an Intent

I just changed all serializable classes in my project to parcelable classes.
Everything is working fine, except for that one class which is made of an ArrayList containing another ArrayList. I already debugged.
There is no error when writing this ArrayList. But I get an error while reading it.
This is the class where the error happens:
public class Timetable implements Parcelable
{
private int actLap = 0;
private ArrayList<Lap> timetable;
private ArrayList<Location> loggedLocations;
private Date startTime; ...
...
public void writeToParcel(Parcel out, int flags)
{
out.writeInt(actLap);
out.writeTypedList(timetable); //no error here
out.writeTypedList(loggedLocations); ...
...
private Timetable(Parcel in)
{
actLap = in.readInt();
in.readTypedList(timetable, Lap.CREATOR); //error after this line
in.readTypedList(loggedLocations, Location.CREATOR);
startTime = (Date)in.readSerializable();
bestLap = in.readParcelable(Lap.class.getClassLoader());
track = in.readParcelable(Track.class.getClassLoader());
description = in.readString();
}
Here are the other classes:
public class Lap implements Parcelable
{
private ArrayList<Time> sectorTimes = new ArrayList<Time>();
private Time laptime; ...
...
public void writeToParcel(Parcel out, int flags)
{
out.writeTypedList(sectorTimes);
out.writeParcelable(laptime,flags);
}
public static final Parcelable.Creator<Lap> CREATOR = new Parcelable.Creator<Lap>()
{
public Lap createFromParcel(Parcel in)
{
return new Lap(in);
}
public Lap[] newArray(int size)
{
return new Lap[size];
}
};
private Lap(Parcel in)
{
in.readTypedList(sectorTimes, Time.CREATOR);
laptime = in.readParcelable(Time.class.getClassLoader());
}
And this class:
public class Time implements Parcelable
{
private long timeLong;
private String timeString;...
...
public void writeToParcel(Parcel out, int flags)
{
out.writeLong(timeLong);
out.writeString(timeString);
}
public static final Parcelable.Creator<Time> CREATOR = new Parcelable.Creator<Time>()
{
public Time createFromParcel(Parcel in)
{
return new Time(in);
}
public Time[] newArray(int size)
{
return new Time[size];
}
};
private Time(Parcel in)
{
timeLong = in.readLong();
timeString = in.readString();
}
Like I already said, everything works fine (there are more Parcelable classes which I pass with intents (including a single ArrayList) and which I save in files).
So can you guys help me to write and read that double ArrayList?
Thanks in advance
If your code is as posted, then you're just missing the initialization of the ArrayLists, i.e.
private Timetable(Parcel in)
{
// readTypeList() needs an existing List<> to load.
timetable = new ArrayList<Lap>();
loggedLocations = new ArrayList<Location>();
actLap = in.readInt();
in.readTypedList(timetable, Lap.CREATOR);
in.readTypedList(loggedLocations, Location.CREATOR);
...

Android: How to implement Parcelable to my objects? [duplicate]

This question already has answers here:
Parcelable and inheritance in Android
(3 answers)
Closed 7 years ago.
I have this ConstantData class which holds my JSON indexes, I need to pass them between activities with extras. But before that, I have to implement Parcelable to the objects of this class first.
My question is, how should I declare the object within my class here and put every object inside a variable?
I'm a newbie and I'm totally clueless right now. Thank you. Feel free to modify my code below.
ConstantData.java
public class ConstantData{
public static String project_title = "project title";
public static String organization_title = "organization title";
public static String keyword = "keyword";
public static String short_code = "short code";
public static String project_description = "description";
public static String smallImageUrl = "smallImageUrl";
public static String bigImageUrl = "bigImageUrl";
public static String price= "price";
public static String country= "country";
public static ArrayList<Project> projectsList = new ArrayList<Project>();
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
out.writeString(organization_title);
out.writeString(keyword);
out.writeString(short_code);
out.writeString(project_description);
out.writeString(smallImageUrl);
out.writeString(bigImageUrl);
out.writeString(price);
out.writeString(country);
}
public static final Parcelable.Creator<ConstantData> CREATOR
= new Parcelable.Creator<ConstantData>() {
public ConstantData createFromParcel(Parcel in) {
return new ConstantData(in);
}
public ConstantData[] newArray(int size) {
return new ConstantData[size];
}
};
private ConstantData(Parcel in) {
project_title = in.readString();
organization_title = in.readString();
keyword = in.readString();
short_code = in.readString();
project_description = in.readString();
smallImageUrl = in.readString();
bigImageUrl = in.readString();
price = in.readString();
country = in.readString();
}
}
In case my question is not clear enough, you can look up this question: How to send an object from one Android Activity to another using Intents?
There he wrote myParcelableObject, I just don't know how to make the parcelable object.
EDIT
Project.java
public class Project {
public String project_title;
public String organization_title;
public String keyword;
public String short_code;
public String project_description;
public String smallImageUrl;
public String bigImageUrl;
public String price;
public String country;
}
You need to implement the Parcelable interface
public class ConstantData implements Parcelable {
public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
....
out.writeString(country);
out.writeList(projectsList); // <<--
}
private ConstantData(Parcel in) {
project_title = in.readString();
....
country = in.readString();
projectsList = in.readList();
I think for the writing of the projectsList to work, the Project class also needs to implement Parcelable.
See e.g. this class for an example.

Arraylist in parcelable object

I have seen many parcelable examples so far, but for some reason I can't get it to work when it gets a bit more complex.
I have a Movie object, which implements Parcelable. This book object contains some properties, such as ArrayLists.
Running my app results in a NullPointerException when executing the ReadTypedList ! I'm really out of ideas here
public class Movie implements Parcelable{
private int id;
private List<Review> reviews
private List<String> authors;
public Movie () {
reviews = new ArrayList<Review>();
authors = new ArrayList<String>();
}
public Movie (Parcel in) {
readFromParcel(in);
}
/* getters and setters excluded from code here */
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeList(reviews);
dest.writeStringList(authors);
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
public MoviecreateFromParcel(Parcel source) {
return new Movie(source);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
/*
* Constructor calls read to create object
*/
private void readFromParcel(Parcel in) {
this.id = in.readInt();
in.readTypedList(reviews, Review.CREATOR); /* NULLPOINTER HERE */
in.readStringList(authors);
}
}
The Review class:
public class Review implements Parcelable {
private int id;
private String content;
public Review() {
}
public Review(Parcel in) {
readFromParcel(in);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(content);
}
public static final Creator<Review> CREATOR = new Creator<Review>() {
public Review createFromParcel(Parcel source) {
return new Review(source);
}
public Review[] newArray(int size) {
return new Review[size];
}
};
private void readFromParcel(Parcel in) {
this.id = in.readInt();
this.content = in.readString();
}
}
I would be very grateful if someone could just get me on the right track, I have spend quite a bit of time searching for this one !
Thanks in adnvance
Wesley
reviews and authors are both null. You should first initialize the ArrayList. One way to do this is chain the constructor:
public Movie (Parcel in) {
this();
readFromParcel(in);
}
From the javadocs for readTypedList:
Read into the given List items containing a particular object type
that were written with writeTypedList(List)
at the current dataPosition(). The list must have previously been written via writeTypedList(List) with the same object type.
You wrote them with a plain
dest.writeList(reviews);

Calling one variable of a class in another class?

Hi I am new to the java programming. I have a instance variable in a class which I should call to another class.It should not be static as per the requirements.The code given below## `
public class Card {
private String no;
private String text;
public Vector totalCards = new Vector();
public String getNo() {
totalCards.addElement(no);
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getText() {
totalCards.addElement(text);
return text;
}
public void setText(String text) {
this.text = text;
}
}
I need to pass this "totalCards" vector in another class without making it as a static.How can I pass this value.Can anybody help me. Any suggestions appreciated.
Since the variable "totalCards" is public, it can be directly accessed via an instance of Card.
It's a bit unclear exactly what your issue is, but you first need to have an instance of Card. The totalCards Vector will then live in that Card object.
Card myCards = new Card();
Now the object that has access to myCards can access the Vector with:
myCards.totalCards
However, it's considered a better practice by many to make totalCards private and make a getter for it:
myCards.getTotalCards();
You simply write in your class:
public class AnotherClass
{
public Class obj1 = new Class();
public String getNo()
{
Vector v1 = obj1.totalCards;
return v1; //or what do you want
}
You can simply pass totalCards reference to other class because is public. Tell us more about client class. Thanks.
public class Card {
private String no;
private String text;
/* initializing totalCards here is bad, why are you doing this here? If each
card has a list of totalCards, consider doing this in the constructor of a
Card */
private Vector<Card> totalCards = new Vector();
public String getNo() {
//getters should not have side effects like addElement...
totalCards.addElement(no);
return no;
}
public Vector<Card> getCards() {
return totalCards;
}
public void setNo(String no) {
this.no = no;
}
public String getText() {
//getters should not have side effects like addElement...
totalCards.addElement(text);
return text;
}
public void setText(String text) {
this.text = text;
}
}
The other class needs to have an instance of Card. For example by creating a new instance:
public class TheOtherClass {
private Card myCard = new Card();
public void doSomething() {
myCard.totalCards.doAnotherThing();
}
}
By the way: It's considered as bad style to access properties of other classes directly - try to use setters and getters:
public class Card {
private Vector<Card> totalCards = new Vector();
public void getTotalCards() {
return totalCards;
}
}

Categories

Resources