Android: Storing ArrayList<T> in SharedPreferences? - java

I need to store an ArrayList of type "Comment" in my SharedPreferences. This is my model class:
public class Comment {
public String getPID() {
return PID;
}
public void setPID(String pID) {
PID = pID;
}
public String PID;
public String Comment;
public String Commenter;
public String Date;
public String getComment() {
return Comment;
}
public void setComment(String comment) {
Comment = comment;
}
public String getCommenter() {
return Commenter;
}
public void setCommenter(String commenter) {
Commenter = commenter;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
}
So my ArrayList contains 2 Comments that need to be stored in SharedPreferences. I tried HashSet but it requires String values:
ArrayList<Comment_FB> fb = getFeedback(); //my Comments List
SharedPreferences pref = getApplicationContext().getSharedPreferences("CurrentProduct", 0);
Editor editor = pref.edit();
Set<String> set = new HashSet<String>();
set.addAll(fb);
editor.putStringSet("key", set);
editor.commit();
How do I get this done folks? :)

I think you need to store it as a file.
public static boolean save(String key, Serializable obj) {
try {
FileOutputStream outStream = new FileOutputStream(instance.getCacheDir() + "/" + key);
ObjectOutputStream objOutStream;
objOutStream = new ObjectOutputStream(outStream);
objOutStream.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static Object getObject(String key) {
Object obj = null;
if (!new File(instance.getCacheDir() + "/" + key).exists())
return obj;
FileInputStream inputStream;
try {
inputStream = new FileInputStream(instance.getCacheDir() + "/" + key);
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
obj = objInputStream.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
Your "Comment" class should implements Serializable.

Related

How to save and load Objects to and from a file

I'm gonna be honest I am panicking. I am doing an exam in a Java course and I have been stuck for some time now.
I have to implement a RSS Feader and I am currently doing methods to save and load subscribed feeds. I thought I got the saveSubscribedFeeds method right because it passes the JUnit Test but I am starting to think I have some kind of error in there so that the loadSubscribeFeeds method cannot work properly.
Here is the saveSubscribedFeeds method:
public void saveSubscribedFeeds(List<Feed> feeds, File feedsFile) {
FileWriter writer = null;
try {
writer = new FileWriter(feedsFile);
for(Feed f: feeds) {
writer.write(f + System.lineSeparator());
}
writer.close();
} catch (IOException e) {
e.getMessage();
}
}
For the loadSubscribedFeed method I already tried a Scanner, BufferedReader and FileInputStream and ObjectInputStream but nothing works. This is my current method:
public List<Feed> loadSubscribedFeeds(File feedsFile) {
Scanner s = null;
try {
s = new Scanner(feedsFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<String> listString = new ArrayList<>();
List<Feed> listFeed = new ArrayList<>();
while (s.hasNextLine()) {
listString.add(s.nextLine());
}
for(String f : listString) {
listFeed.add(new Feed(f));
}
return listFeed;
}
here is also the Feed class:
public class Feed implements Serializable, Comparable<Feed> {
private static final long serialVersionUID = 1L;
private String url;
private String title;
private String description;
private String publishedDateString;
private List<Entry> entries;
public Feed(String url) {
super();
this.url = url;
this.entries = new ArrayList<Entry>();
this.title = "";
this.description = "";
this.publishedDateString = "";
}
/**
* Creates an instance of a Feed and transfers the feed
* data form a SyndFeed object to the new instance.
* #param url The URL string of this feed
* #param sourceFeed The SyndFeed object holding the data for this feed instance
*/
public Feed(String url, SyndFeed sourceFeed) {
this(url);
setTitle(sourceFeed.getTitle());
setDescription(sourceFeed.getDescription());
if (sourceFeed.getPublishedDate() != null)
setPublishedDateString(FeaderUtils.DATE_FORMAT.format(sourceFeed.getPublishedDate()));
for (SyndEntry entryTemp : sourceFeed.getEntries()) {
Entry entry = new Entry(entryTemp.getTitle());
entry.setContent(entryTemp.getDescription().getValue());
entry.setLinkUrl(entryTemp.getLink());
entry.setParentFeedTitle(getTitle());
if (entryTemp.getPublishedDate() != null) {
entry.setPublishedDateString(FeaderUtils.DATE_FORMAT.format(entryTemp.getPublishedDate()));
}
addEntry(entry);
}
}
public String getUrl() {
return url;
}
public void setTitle(String title) {
this.title = title != null ? title : "";
}
public String getTitle() {
return title;
}
public void setDescription(String description) {
this.description = description != null ? description : "";
}
public String getDescription() {
return description;
}
public void setPublishedDateString(String publishedDateString) {
this.publishedDateString = publishedDateString != null ? publishedDateString : "";
}
public String getPublishedDateString() {
return publishedDateString;
}
/**
* Returns a short string containing a combination of meta data for this feed
* #return info string
*/
public String getShortFeedInfo() {
return getTitle() + " [" +
getEntriesCount() + " entries]: " +
getDescription() +
(getPublishedDateString() != null && getPublishedDateString().length() > 0
? " (updated " + getPublishedDateString() + ")"
: "");
}
public void addEntry(Entry entry) {
if (entry != null) entries.add(entry);
}
public List<Entry> getEntries() {
return entries;
}
public int getEntriesCount() {
return entries.size();
}
#Override
public boolean equals(Object obj) {
return (obj instanceof Feed)
&& ((Feed)obj).getUrl().equals(url);
}
#Override
public int hashCode() {
return url.hashCode();
}
#Override
public String toString() {
return getTitle();
}
#Override
public int compareTo(Feed o) {
return getPublishedDateString().compareTo(o.getPublishedDateString());
}
}
Maybe someone out there will be able to help me or guide me in the correct direction.
Thanks already in advance.

JSON mapping to Java returning null value

I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.

How to read an ArrayList from a File into another ArrayList?

I trying to read an arraylist from a file into another arraylist but I keep getting errors. The file is called eventos.dat and the arraylist is from the type Evento. I want to create a new ArrayList<Evento> with the objects from the array on the file. Here is the method i'm using:
public class ListaEventos implements Serializable{
private ArrayList<Evento> eventos = new ArrayList();
public String adicionarEvento(Evento novo){
for (Evento evento : eventos) {
if(novo.equals(evento)){
return "Evento já existe";
}
}
eventos.add(novo);
return "ADICIONEI";
}
public ArrayList<Evento> getEventos() {
return eventos;
}
public Evento procuraEvento(String tituloEvento){
for (Evento evento : eventos){
if(tituloEvento.equals(evento.getTitulo())){
return evento;
}
}
return null;
}
public String editaEvento(Evento antigo, Evento novo){
for (int i=0;i<eventos.size();i++){
if(antigo.equals(eventos.get(i))){
eventos.get(i).setTitulo(novo.getTitulo());
eventos.get(i).setData(novo.getData());
eventos.get(i).setDescricao(novo.getDescricao());
eventos.get(i).setLocal(novo.getLocal());
eventos.get(i).setPrivado(novo.getPrivado());
return "Editei evento";
}
}
return "Evento não existe";
}
public String removeEvento(String removeTitulo){
Evento aux= procuraEvento(removeTitulo);
if(aux != null){
eventos.remove(aux);
return "Evento removido!";
}
return "Evento não existe";
}
public void gravaFicheiro(){
try{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Eventos.dat"));
out.writeObject(eventos);
out.close();
}
catch(IOException ex){
System.out.println("Não conseguiu gravar");
}
}
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException{
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
}
here is the Evento class:
public class Evento implements Serializable {
private String titulo = "Nao preenchido";
private String data = "Nao preenchido";
private String local = "Nao preenchido";
private String descricao = "Nao preenchido";
private String privado = "Nao preenchido";
private ArrayList<Contacto> convidados = new ArrayList();
public Evento() {
}
public Evento(String titulo, String data, String local, String descricao, String privado) {
this.titulo = titulo;
this.data = data;
this.local = local;
this.descricao = descricao;
this.privado = privado;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setData(String data) {
this.data = data;
}
public void setLocal(String local) {
this.local = local;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setPrivado(String privado) {
this.privado = privado;
}
public String getTitulo() {
return titulo;
}
public String getData() {
return data;
}
public String getLocal() {
return local;
}
public String getDescricao() {
return descricao;
}
public String getPrivado() {
return privado;
}
public ArrayList<Contacto> getConvidados() {
return convidados;
}
public void setConvidados(ArrayList<Contacto> convidados) {
this.convidados = convidados;
}
public String adicionaConvidado(String nomeConvidado){
Contacto novo = new Contacto();
for (Contacto contacto : this.convidados) {
if(nomeConvidado.equals(contacto.getNome())){
return "Contacto já foi convidado";
}
}
novo.setNome(nomeConvidado);
novo.setEmail("");
novo.setTelefone("");
convidados.add(novo);
return "ADICIONEI CONVIDADO";
}
public Evento(String titulo, String local) {
this.titulo = titulo;
this.local = local;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Evento other = (Evento) obj;
if (!Objects.equals(this.titulo, other.titulo)) {
return false;
}
if (!Objects.equals(this.data, other.data)) {
return false;
}
if (!Objects.equals(this.local, other.local)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Evento{" + "titulo=" + titulo + ", data=" + data + ", local=" + local + ", descricao=" + descricao + ", privado=" + privado + ", convidados=" + convidados + '}';
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
Changed the method CarregaEvento to:
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException {
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
No errors but still doesn't work.
eventos=(ArrayList<Evento>) in.readObject();
This will not create a new type of an ArrayList<Evento>.
although you can create a new instance of an Evento with the String that is provided when you read the text file. you can use the split(String par1) method in the String class to create a new instance of Evento and add it to an arraylist.
refer to the JavaDocs for more info on splitting.

java.lang.NullPointerException while reading value from json to java object

Here I am reading json value from youtube to java.
I am getting values properly except the thumbnail data while getting thumbnail object value i am getting java.lang.NullPointerException
public class JsonVideoDetais {
public static void main(String... args) {
BufferedReader reader = null;
StringBuilder buffer = null;
try {
String link = "https://gdata.youtube.com/feeds/api/videos/" + "aa_wFClyiVE" + "?v=2&alt=jsonc";
URL url = new URL(link);
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
buffer = new StringBuilder();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
} catch (Exception e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(JsonVideoDetais.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
videoDetails data;
data = new Gson().fromJson(buffer.toString(), videoDetails.class);
System.out.println(data.getData().getTitle());
System.out.println(data.getData().getTn().getHqDefault());
System.out.println(data.getData().getTn().getSqDefault());
}
}
class videoDetails {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String toString() {
return String.format("data:%s", data);
}
}
class Data {
private String id;
private String title;
private String description;
private int duration;
private Thumbnail tn;
public Thumbnail getTn() {
return tn;
}
public void setTn(Thumbnail tn) {
this.tn = tn;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return String.format("title:%s,id:%s,description:%s,tn:%s,duration:%d", title, id, description, tn, duration);
}
}
class Thumbnail {
private String sqDefault;
private String hqDefault;
public String getSqDefault() {
return sqDefault;
}
public void setSqDefault(String sqDefault) {
this.sqDefault = sqDefault;
}
public String getHqDefault() {
return hqDefault;
}
public void setHqDefault(String hqDefault) {
this.hqDefault = hqDefault;
}
public String toString() {
return String.format("sqDefault:%s,hqDefault:%s", hqDefault, sqDefault);
}
}
I am getting following exception
Exception in thread "main" java.lang.NullPointerException
at utility.JsonVideoDetais.main(JsonVideoDetais.java:52)
while calling
System.out.println(data.getData().getTn().getHqDefault());
System.out.println(data.getData().getTn().getSqDefault());
If you wll see this link. It is having value for sqDefault and hqDefault
I would like to fetch the value of sqDefault and hqDefault.
How to do this.
In your Data class, i created an object like this. I guess the Thumbnail object is getting set to thumbnail, tn is not working on my side too.
private Thumbnail thumbnail;// instead of tn
and the resultant output is : -
Blood Glucose Hindi - Dr. Anup, MD Teaches Series
https://i1.ytimg.com/vi/aa_wFClyiVE/hqdefault.jpg
https://i1.ytimg.com/vi/aa_wFClyiVE/default.jpg
Using debugger to find out which object is null is fastest way to solve your problem.
OR
Find the null return value with the following code:
System.out.println(data);
System.out.println(data.getData());
System.out.println(data.getData().getTn());
--The following text are newly added-----------------
Well, I have run your program on my laptop, and it seem that the json response of https://gdata.youtube.com/feeds/api/videos/aa_wFClyiVE?v=2&alt=jsonc#data/thumbnail/hqDefault contains no tn field at all. That's why you always got null value.

Built a class "TimetableData" using simpleframework that saves fine as xml, but when I try reading it in code, it throws PersistenceException

04-21 20:09:17.590: W/System.err(23059): org.simpleframework.xml.core.PersistenceException: Constructor not matched for class com.example.simplexml.DayData
my main class where I am saving the data in the xml File which seems to work fine
Serializer serializer = new Persister();
TimetableData timetableData = new TimetableData();
SubjectData programming = new SubjectData("Programming","ECG 12",1200, 1400);
SubjectData electronics = new SubjectData("Electronics","ECG 13", 1400, 1600);
timetableData.daysData.get(0).subjectsData.add(electronics);
timetableData.daysData.get(1).subjectsData.add(programming);
File result = new File(this.getFilesDir().getPath().toString() + "example.xml");
try {
serializer.write(timetableData, result);
}
at this moment, if I look at the xmlfile, I can see it, and it looks alright.. but when I read it, it throws the exception. This is how I am reading it.
TimetableData timetableData;
try {
timetableData = serializr.read(TimetableData.class, source);//this throws the exception
DayData myDay= timetableData.daysData.get(0);
SubjectData mySub = myDay.subjectsData.get(0);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
class daydata
public class DayData {
#Attribute(name="dayName")
private String dayName;
#ElementList(name="subjectsData", inline=true)
public List<SubjectData> subjectsData = new ArrayList<SubjectData>();
public DayData(String dayName)
{
this.dayName = dayName;
}
public String getDayName()
{
return dayName;
}
}
my Class TimetableData that makes a list of dayData
#Root
public class TimetableData {
#ElementList(name="daysData",inline=true)
public List<DayData> daysData;
public TimetableData()
{
daysData = new ArrayList<DayData>();
daysData.add(new DayData("monday"));
daysData.add(new DayData("tuesday"));
daysData.add(new DayData("wednesday"));
daysData.add(new DayData("thursday"));
daysData.add(new DayData("friday"));
}
}
my class subjectData
public class SubjectData{
#Element(name="classLoc")
private String classLoc;
#Element(name="startTime")
private int startTime;
#Element(name="endTime")
private int endTime;
#Attribute(name="subjectName")
private String subjectName;
public SubjectData() {
super();
}
public SubjectData(String subjectName, String classLoc, int startTime, int endTime) {
this.classLoc = classLoc;
this.subjectName = subjectName;
this.startTime = startTime;
this.endTime = endTime;
}
public String getClassLoc() {
return classLoc;
}
public int getStartTime()
{
return startTime;
}
public int getEndTime()
{
return endTime;
}
public String getDayName() {
return subjectName;
}
}
This is the xmlFile created
<timetableData>
<dayData dayName="monday">
<subjectData subjectName="Electronics">
<classLoc>ECG 13</classLoc>
<startTime>1400</startTime>
<endTime>1600</endTime>
</subjectData>
</dayData>
<dayData dayName="tuesday">
<subjectData subjectName="Programming">
<classLoc>ECG 12</classLoc>
<startTime>1200</startTime>
<endTime>1400</endTime>
</subjectData>
</dayData>
<dayData dayName="wednesday"/>
<dayData dayName="thursday"/>
<dayData dayName="friday"/>
</timetableData>
Try this:
public class DayData {
#Attribute(name="dayName")
private String dayName;
#ElementList(name="subjectsData", inline=true)
public List<SubjectData> subjectsData = new ArrayList<SubjectData>();
public DayData(#Attribute(name="dayName") String dayName)
{
this.dayName = dayName;
}
public String getDayName()
{
return dayName;
}
}

Categories