I have a class with set and get, and In another class.
However, if I use Classname X = new Classname(); I'll not be able to use previous information set before.
Here's part of the code:
public void BuscarID () throws Exception {
//THIS VOID IS FOR SEARCH
ConsumirWS2 http = new ConsumirWS2();
Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
Cliente2 u = new Cliente2();
Type ClienteType = new TypeToken<Cliente2>() {
}.getType();
int i = Integer.parseInt(InterfaceConsu2.jTextFieldID.getText());
u.setCad_pes_id(i);
String s = Integer.toString(u.getcad_pes_id());
String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Clienteid/get/"+s;
String json = http.sendGet(url, "GET");
u = g.fromJson(json, ClienteType);
System.out.println(json + ("\n"));
System.out.println(u.getcad_pes_nome() +("\n") + u.getCad_pes_apelido() +("\n") + u.getCad_pes_cpf() +("\n") + u.getCad_pes_data()+("\n"));
String Date1 = new SimpleDateFormat("dd-MM-yyyy").format(u.getCad_pes_data());
System.out.println(Date1);
InterfaceConsu2.jTextFieldNOME.setText(u.getcad_pes_nome());
InterfaceConsu2.jTextFieldAPELIDO.setText(u.getCad_pes_apelido());
InterfaceConsu2.jFormattedTextFieldCPF.setText(u.getCad_pes_cpf());
InterfaceConsu2.jFormattedTextFieldDATA.setText(Date1);
InterfaceConsu2.jTextFieldID.setText(s);
}
public void alterar () throws Exception {
//THIS VOID IS FOR EDITING THE INFORMATION GET BEFORE
ConsumirWS2 http = new ConsumirWS2();
Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
Cliente2 u = new Cliente2();
Type ClienteType = new TypeToken<Cliente2>() {
}.getType();
u.setCad_pes_nome(InterfaceConsu2.jTextFieldNOME.getText());
u.setCad_pes_cpf(InterfaceConsu2.jFormattedTextFieldCPF.getText());
u.setCad_pes_apelido(InterfaceConsu2.jTextFieldAPELIDO.getText());
int i = Integer.parseInt(InterfaceConsu2.jTextFieldID.getText());
u.setCad_pes_id(i);
//u.setCad_pes_id(InterfaceConsu2.jTextFieldID.getText());
SimpleDateFormat formatter = new SimpleDateFormat ("dd-MM-yyyy");
java.util.Date utilDate = null;
try {
utilDate = formatter.parse(InterfaceConsu2.jFormattedTextFieldDATA.getText());
} catch (ParseException ex) {
Logger.getLogger(InterfaceConsu2.class.getName()).log(Level.SEVERE, null, ex);
}
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
u.setCad_pes_data(sqlDate);
String json = g.toJson(u, ClienteType);
String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/alterar";
http.sendPost(url, json, "PUT");
}
and then I have the set and get class:
public class Cliente2 {
public String cad_pes_nome;
public String cad_pes_apelido;
private String cad_pes_cpf;
public int cad_pes_id;
public Date cad_pes_data;
public String getcad_pes_nome() {
return cad_pes_nome;
}
public void setCad_pes_nome(String cad_pes_nome) {
this.cad_pes_nome = cad_pes_nome;
}
public String getCad_pes_apelido() {
return cad_pes_apelido;
}
public void setCad_pes_apelido(String cad_pes_apelido) {
this.cad_pes_apelido = cad_pes_apelido;
}
public String getCad_pes_cpf() {
return cad_pes_cpf;
}
public void setCad_pes_cpf(String cad_pes_cpf) {
this.cad_pes_cpf = cad_pes_cpf;
}
public int getcad_pes_id() {
return cad_pes_id;
}
public void setCad_pes_id(int cad_pes_id) {
this.cad_pes_id = cad_pes_id;
}
public Date getCad_pes_data() {
return cad_pes_data;
}
public void setCad_pes_data(Date cad_pes_data) {
this.cad_pes_data = cad_pes_data;
}
}
Because I'm using Classname X = new Classname();, when I try to print my u.getcad_pes_nome or any other get, It's empty, There's a way to call Cliente2 without using Cliente2 u = new Cliente2(); or what I have to change in my classes?
Related
[
{
"id":"1",
"created_at":"2019-08-19 02:54:36",
"updated_at":"2019-09-04 15:00:05"
},
{
"id":"2",
"created_at":"2019-08-27 08:59:18",
"updated_at":"2019-09-04 14:59:14"
},
{
"id":"4",
"created_at":"2019-08-29 20:19:54",
"updated_at":"2019-09-04 14:58:53"
}
]
how do i sort json data according to "created_at" (2019-08-30,2019-08-29) data in descending order and set value to textview in android.
please try this
public static JSONArray sortJsonArray(JSONArray array) {
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = lhs.getString("created_at");
String rid = rhs.getString("created_at");
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}
A solution using gson library:
public static void setSortedDate (String json, TextView tv) {
Type t = new TypeToken<List<DateModel>>(){}.getType();
Gson gson = new Gson();
List<DateModel> list = gson.fromJson(json, t);
Collections.sort(list, new Comparator<DateModel>(){
#Override
public int compare (DateModel p1, DateModel p2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date d1 = df.parse(p1.created_at);
Date d2 = df.parse(p2.created_at);
return d2.compareTo(d1);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
});
int i = list.size();
for(DateModel d: list){
tv.append(d.created_at);
if(--i > 0) tv.append(", ");
}
}
Model class
public class DateModel {
String id;
String created_at;
String updated_at;
}
Usage
private static final String JSON = "[ { \"id\": \"1\", \"created_at\": \"2019-08-19 02:54:36\", \"updated_at\": \"2019-09-04 15:00:05\" }, { \"id\": \"2\", \"created_at\": \"2019-08-27 08:59:18\", \"updated_at\": \"2019-09-04 14:59:14\" }, { \"id\": \"4\", \"created_at\": \"2019-08-29 20:19:54\", \"updated_at\": \"2019-09-04 14:58:53\" }, { \"id\": \"5\", \"created_at\": \"2019-08-30 09:31:42\", \"updated_at\": \"2019-09-04 14:58:40\" } ]";
setSortedDate(JSON, tv);
Output
2019-08-30 09:31:42, 2019-08-29 20:19:54, 2019-08-27 08:59:18, 2019-08-19 02:54:36
Update
Here is the replacement of gson with standard java implementation
public static void setSortedDate (String json, TextView tv) {
List<DateModel> list = getListFromJson(json);
Collections.sort(list, new DateModelComparator());
int i = list.size();
for(DateModel d: list){
tv.append(d.created_at);
if(--i > 0) tv.append(", ");
}
}
private static List<DateModel> getListFromJson (String json) {
List<DateModel> list = new LinkedList<>();
try {
JSONArray array = new JSONArray(json);
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
DateModel dm = new DateModel();
dm.id = obj.getString("id");
dm.created_at = obj.getString("created_at");
dm.updated_at = obj.getString("updated_at");
list.add(dm);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
DateComparator class
public class DateModelComparator implements Comparator<DateModel> {
#Override
public int compare (DateModel p1, DateModel p2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date d1 = df.parse(p1.created_at);
Date d2 = df.parse(p2.created_at);
return d2.compareTo(d1);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}
I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.
I am trying to save the state of my app to shared prefrences. The information that I want to save is an arraylist of custom objects where each object (PatientInfo) contains a few string and 2 more custom arraylist (SkinPhotoInfo, TreatmentsInfo). I was able to save and load an array list of custom objects, but I was'nt able to save the arraylist that has arraylists in it.
Anyone got an idea of what is the easiest way to do it? The object itself is allready parcable if it helps in any way.
P. S. When is the best time to save to shared prefrences - onPause or onDelete?
Thank you for your help!!
PatientInfo:
public class PatientInfo implements Parcelable {
String name;
String skinType;
String notes;
String image;
ArrayList<SkinPhotoInfo> skinPhotos;
ArrayList<TreatmentsInfo> treatments;
Boolean showDeleteButton;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(skinType);
dest.writeString(notes);
dest.writeValue(image);
dest.writeValue(skinPhotos);
dest.writeValue(treatments);
}
public static final Creator<PatientInfo> CREATOR = new Creator<PatientInfo>()
{
#Override
public PatientInfo createFromParcel(Parcel source) {
PatientInfo ret = new PatientInfo();
ret.name = source.readString();
ret.skinType = source.readString();
ret.notes = source.readString();
ret.image = (String)source.readString();
ret.skinPhotos = source.readArrayList(null);
ret.treatments = source.readArrayList(null);
return ret;
}
#Override
public PatientInfo[] newArray(int size) {
return new PatientInfo[size];
}
};
public PatientInfo() {
this.name = "";
this.skinType = "";
this.image = "";
this.skinPhotos = new ArrayList<SkinPhotoInfo>();
this.showDeleteButton = false;
this.treatments = new ArrayList<TreatmentsInfo>();
}}
SkinPhotoInfo:
public class SkinPhotoInfo implements Parcelable {
String photoDate;
Boolean showDeleteButton;
Uri imageUri;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(photoDate);
dest.writeByte((byte)(showDeleteButton ? 1 : 0)); // If showDeleteButton == true, byte == 1
dest.writeValue(imageUri);
}
public static final Creator<SkinPhotoInfo> CREATOR = new Creator<SkinPhotoInfo>()
{
#Override
public SkinPhotoInfo createFromParcel(Parcel source) {
SkinPhotoInfo ret = new SkinPhotoInfo();
ret.skinImageThumnail = (Bitmap)source.readValue(Bitmap.class.getClassLoader());
ret.photoDate = source.readString();
ret.showDeleteButton = source.readByte() != 1;
ret.imageUri = (Uri) source.readValue(Uri.class.getClassLoader());
return ret;
}
#Override
public SkinPhotoInfo[] newArray(int size) {
return new SkinPhotoInfo[size];
}
};
public SkinPhotoInfo(Uri imageUri, String photoDate) {
this.imageUri = imageUri;
this.photoDate = photoDate;
showDeleteButton = false;
}}
TreatmentsInfo:
public class TreatmentsInfo implements Parcelable {
String treatmentDate;
String treatmentName;
String pattern = "MM-dd-yy";
Boolean showDeleteButton;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(treatmentDate);
dest.writeString(treatmentName);
dest.writeString(pattern);
dest.writeByte((byte)(showDeleteButton ? 1 : 0)); // If showDeleteButton == true, byte == 1
}
public static final Creator<TreatmentsInfo> CREATOR = new Creator<TreatmentsInfo>()
{
#Override
public TreatmentsInfo createFromParcel(Parcel source) {
TreatmentsInfo ret = new TreatmentsInfo();
ret.treatmentDate = source.readString();
ret.treatmentName = source.readString();
ret.pattern = source.readString();
ret.showDeleteButton = source.readByte() != 1;
return ret;
}
#Override
public TreatmentsInfo[] newArray(int size) {
return new TreatmentsInfo[size];
}
};
public TreatmentsInfo(){
this.treatmentDate = "";
this.treatmentName = "";
this.showDeleteButton = false;
this.pattern = "";
}
public TreatmentsInfo(String treatmentDate, String treatmentName) {
this.treatmentDate = treatmentDate;
this.treatmentName = treatmentName;
this.showDeleteButton = false;
}}
Use Gson library and save the arraylist as string.
Snippet below is save as file but you can use it in sharedpreference as well:
public static void saveGroupChatFile(File file, List<GCRoom> list) throws IOException {
String data = new Gson().toJson(list);
FileOutputStream fout = new FileOutputStream(file, false);
OutputStreamWriter osw = new OutputStreamWriter(fout);
osw.write(data);
osw.close();
}
public static List<GCRoom> readGroupChatFile(File file) throws IOException {
Type listType = new TypeToken<List<GCRoom>>() {
}.getType();
JsonReader reader = new JsonReader(new FileReader(file));
return new Gson().fromJson(reader, listType);
}
As for the library:
implementation 'com.google.code.gson:gson:2.8.5'
You can do something like:
String json = new Gson().toJson(YourObject);
To save in the Shared Preferences.
To retrieve the json and transform it to YourObejct, just do:
String json = myPrefsObject.getString(TAG, "");
return new Gson().fromJson(json, YourObject.class);
As for the PS question, the answer is onPause.
Let me know if you need something else
GSON provides method to convert objects to string and vice versa.
Use toJson() to convert object to string
PatientInfo patientInfo = new PatientInfo();
Gson gson = new Gson();
String objectAsString = gson.toJson(patientInfo);
Use fromJson() to convert string to object
Gson gson = new Gson();
PatientInfo patientinfo = gson.fromJson(data, PatientInfo.class);
//data is object that that you saved in shared preference after converting to string
Convert response to gson and use it as list and thus simply convert list setvalue and use putArray() to that set
public class staticpref{
private static SharedPreferences prefs;
private static SharedPreferences.Editor editor;
public static void putArray(String key, Set<String> arrayList){
editor.putStringSet(key, arrayList);
editor.commit();
}
public static Set getArray(String key,Set<String> defvalue){
return prefs.getStringSet(key,defvalue);
}
}
or you can make static class for getting and array you have to convert gson to arraylist and like this
String strResponse = anyjsonResponse;
Modelclass model= new Gson().fromJson(strResponse, Modelclass .class);
List<String> datalist= model.anyvalue();
Putandgetarray.addArrayList(datalist);
static methods for achieving this
public class Putandgetarray{
public static void addArrayList(List<data> dataList){
String strputdata = new Gson().toJson(dataList, new TypeToken<List<MutedChat>>() {}.getType());
SharedPreferenceUtils.putString("key", strputdata);
}
public static List<data> getArrayList(){
Type type = new TypeToken<List<data>>(){}.getType();
String strreturndata=SharedPreferenceUtils.getString("key","");
return new Gson().fromJson(strreturndata, type);
}
}
In sharedPreferece you can put only putStringSet(String key, #Nullable Set values); in sharedpreference
I have not seen an (answered) example on the web which discusses this kind of nested-json-array.
JSON to be parsed:
{
"Field": {
"ObjectsList": [
{
"type": "Num",
"priority": "Low",
"size": 3.43
},
{
"type": "Str",
"priority": "Med",
"size": 2.61
}
]
}
}
I created a class for each 'level' of nested json block. I want to be able to parse the contents of the "ObjectList" array.
Can anyone help me to parse this JSON using Gson in Java?
Any hints or code-snippets would be greatly appreciated.
My approach is the following:
public static void main (String... args) throws Exception
{
URL jsonUrl = new URL("http://jsonUrl.com") // cannot share the url
try (InputStream input = jsonUrl.openStream();
BufferedReader buffReader = new BufferedReader (new InputStreamReader (input, "UTF-8")))
{
Gson gson = new GsonBuilder().create();
ClassA classA = gson.fromJson(buffReader, ClassA.class);
System.out.println(classA);
}
}
}
class ClassA
{
private String field;
// getter & setter //
}
class ClassB
{
private List<ClassC> objList;
// getter & setter //
}
clas ClassC
{
private String type;
private String priority;
private double size;
// getters & setters //
public String printStr()
{
return String.format(type, priority, size);
}
}
The following snippet and source file would help you:
https://github.com/matpalm/common-crawl-quick-hacks/blob/master/links_in_metadata/src/com/matpalm/MetaDataToTldLinks.java#L17
private static ParseResult NO_LINKS = new ParseResult(new HashSet<String>(), 0);
private JsonParser parser;
public static void main(String[] s) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(s[0]));
MetaDataToTldLinks metaDataToTldLinks = new MetaDataToTldLinks();
while (reader.ready()) {
String[] fields = reader.readLine().split("\t");
ParseResult outboundLinks = metaDataToTldLinks.outboundLinks(fields[1]);
System.out.println(tldOf(fields[0]) + " " + outboundLinks.links);
}
}
public MetaDataToTldLinks() {
this.parser = new JsonParser();
}
public ParseResult outboundLinks(String jsonMetaData) {
JsonObject metaData = parser.parse(jsonMetaData.toString()).getAsJsonObject();
if (!"SUCCESS".equals(metaData.get("disposition").getAsString()))
return NO_LINKS;
JsonElement content = metaData.get("content");
if (content == null)
return NO_LINKS;
JsonArray links = content.getAsJsonObject().getAsJsonArray("links");
if (links == null)
return NO_LINKS;
Set<String> outboundLinks = new HashSet<String>();
int numNull = 0;
for (JsonElement linke : links) {
JsonObject link = linke.getAsJsonObject();
if ("a".equals(link.get("type").getAsString())) { // anchor
String tld = tldOf(link.get("href").getAsString());
if (tld == null)
++numNull;
else
outboundLinks.add(tld);
}
}
return new ParseResult(outboundLinks, numNull);
}
public static String tldOf(String url) {
try {
String tld = new URI(url).getHost();
if (tld==null)
return null;
if (tld.startsWith("www."))
tld = tld.substring(4);
tld = tld.trim();
return tld.length()==0 ? null : tld;
}
catch (URISyntaxException e) {
return null;
}
}
public static class ParseResult {
public final Set<String> links;
public final int numNull;
public ParseResult(Set<String> links, int numNull) {
this.links = links;
this.numNull = numNull;
}
}
How about this snippet?:
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
List<Object> out = Lists.newArrayListWithCapacity(array.size());
for (JsonElement item : array) {
out.add(toRawTypes(item));
}
}
My goal: save one ArrayList to a .dat file, after read this file and in the end print this array.
To save the ArrayList, "equipas" is one ArrayList< Equipa>, I use this function:
saveMyFile("Equipas.dat", (Object) equipas);
To read:
public static ArrayList<Equipa> readMyFile(String s){
ArrayList<Equipa> novo = new ArrayList<Equipa>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(s));
novo = (ArrayList<Equipa>) ois.readObject();
ois.close();
}
catch(IOException er) { System.out.println(er.getMessage()); }
catch(ClassNotFoundException er) { System.out.println(er.getMessage()); }
return novo;}
In this read function, I have one Compilation Warning: "…uses unchecked or unsafe operations. Recompile with - Xlint:unchecked for details."
To save:
public static void saveMyFile(String s, Object o)
{
try {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(s));
oos.writeObject(o);
oos.flush();
oos.close();
}
catch(IOException e) { System.out.println(e.getMessage()); }
}
Finally, I want to print the ArrayList's info:
ArrayList<Equipa> cena = new ArrayList<Equipa>();
cena=(ArrayList<Equipa>) readMyFile("Equipas.dat");
for(Equipa e:cena)
e.toString();
Error when I try to run:
" writing aborted; java.io.NotSerializableException: Equipa"
Equipa havs the Serializable:
import java.util.*;
import java.io.*;
public class Equipa implements Serializable
{
private String nome;
private Carro carro;
private ArrayList<Piloto> pilotos;
private double tempoDecorrido;
private int pontos;
private boolean desistiu;
private int voltaDesistencia;
private Piloto piloto;
/**
* Constructor for objects of class Equipa
*/
public Equipa()
{
this.nome = "NA";
this.carro = null;
this.pilotos = new ArrayList<Piloto>();
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
this.piloto = null;
}
public Equipa(String nome, Carro carro, ArrayList<Piloto> pilotos)
{
this.nome = nome;
this.carro = carro;
//this.pilotos = new ArrayList<Piloto>(pilotos);
this.pilotos = pilotos;
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
//this.piloto = pilotos.get(0);
}
public Equipa (Equipa e)
{
this.nome = e.getNome();
this.carro = e.getCarro();
this.pilotos = e.getPilotos();
this.tempoDecorrido = e.getTempoDecorrido();
this.pontos = e.getPontos();
this.desistiu = e.getDesistiu();
this.voltaDesistencia = e.getVoltaDesistencia();
//this.piloto = e.getPiloto();
}
/** Getters */
public String getNome()
{
return this.nome;
}
public Carro getCarro()
{
return this.carro;
}
public ArrayList<Piloto> getPilotos()
{
return new ArrayList<Piloto>(this.pilotos);
}
public double getTempoDecorrido()
{
return this.tempoDecorrido;
}
public int getPontos()
{
return this.pontos;
}
public boolean getDesistiu()
{
return this.desistiu;
}
public int getVoltaDesistencia()
{
return this.voltaDesistencia;
}
public Piloto getPiloto()
{
return this.piloto;
}
/** Setters */
public void setNome(String nome)
{
this.nome = nome;
}
public void setCarro(Carro carro)
{
this.carro = carro;
}
public void setPilotos(ArrayList<Piloto> pilotos)
{
this.pilotos = new ArrayList<Piloto>(pilotos);
}
public void setTempoDecorrido(double tempoDecorrido)
{
this.tempoDecorrido = tempoDecorrido;
}
public void setPontos(int pontos)
{
this.pontos = pontos;
}
public void setDesistiu(boolean desistiu)
{
this.desistiu = desistiu;
}
public void setVoltaDesistencia(int voltaDesistencia)
{
this.voltaDesistencia = voltaDesistencia;
}
public void setPiloto(Piloto piloto)
{
this.piloto = piloto;
}
/** Outros Métodos */
public Equipa clone()
{
return new Equipa(this);
}
public boolean equals(Equipa e)
{
if(this.nome == e.getNome())
return true;
else
return false;
}
public String getStringPilotos()
{
String s = new String();
for(Piloto p: this.pilotos)
s = (s + ", " + p.getNome());
return s;
}
public String toString()
{
return new String("Nome da equipa: " + nome + "; Categoria do carro: " + carro.getClass().getName() + "; Marca e modelo: " + carro.getMarca() + " " + carro.getModelo() + "; Pilotos: " + getStringPilotos())+"\n";
}
Implementing Serializable means that serialization is permitted, but not necessarily that it is possible. For it to work, everything referenced by Equipa must also be either primitive or Serializable (and so on, recursively). Is this the case?
Warning in the read function is the result of generics in java. You won't be able to suppress it, unless you use #SuppressWarnings("unchecked") to ignore it.
If you are sure you are reading an ArrayList<Equipa>, you can ignore it without any problem.
With the Equipa code, I can try to point to the Serializable problem: make sure that Carro and Piloto classes are also Serializables. You can add the code of theses classes if you are not sure.
The only type-safer way would be do a custom serialization, using writeObject(OutputStream) and readObjectInputStream say on a class ArrayListOfEquipa maybe using Equipa[] (ArrayList.toArray()).
Not really attractive, if the warning would be the only reason.