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.
Related
I'm trying to get the values of listString and save them to the list of objects listFeed and return listFeed. So far I used a Scanner to add date from feedsFile to my ArrayList listString but I don't know how to store those values in an ArrayList of Objects.
Here's the code snippet
public List<Feed> loadSubscribedFeeds(File feedsFile) throws FileNotFoundException {
Scanner s = new Scanner(feedsFile);
List<String> listString = new ArrayList<>();
List<Feed> listFeed = new ArrayList<>();
while (s.hasNextLine()) {
listString.add(s.nextLine());
}
for(int i = 0; i < listString.size(); i++) {
for(int j = 0; j < listFeed.size(); j++) {
}
}
return listFeed;
}
Here's 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());
}
}
The simplest way is to change your loop.
for(int i = 0; i < listString.size(); i++) {
listFeed.add( new Feed( listString.get(i) );
}
That way you're adding a new Feed object to the listFeed.
Another way you could do it is to use the stream api.
List<Feed> feeds = listString.stream().map( Feed::new ).collect( Collectors.toList() );
Your original technique with a loop is fine though.
A minor note, you do not need to call super() explicitly it will be called automatically if you don't use a different version of super.
I'm unfamiliar with getters and setters (and basically just Java) but I have to use them for this assignment, so if I did anything wrong with those please tell me.
The more important issue is the error that I am getting on my method. The word for word instructions from my assignment for the particular method I'm working on are:
Your processData() method should take all the record data from your ArrayList and add the data into each of your instance fields via your setters.
But I keep getting an error that says:
Type mismatch: cannot convert from element type String[] to List
On the line that says "for (List<String> rowData: content)" on the word content.
Thank you very much for any help you can give me.
My code so far:
public abstract class Client {
String file = "bank-Detail.csv";
ArrayList<String[]> bank = new ArrayList<>();
static Client o[] = new Client[12];
public Client(String file) {
this.file = file;
}
private String ID;
private String Age;
private String Sex;
private String Region;
private String Income;
private String Married;
private String Children;
private String Car;
private String Save_Act;
private String Current_Act;
private String Mortgage;
private String Pep;
public List<String[]> readData() throws IOException {
//initialize variable
int count = 0;
//name file
String file = "bank-Detail.txt";
//make array list
List<String[]> content = new ArrayList<>();
//trycatch for exceptions
try {
//file reader
BufferedReader br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
processData(content);
return content;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
this.Age = age;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getRegion() {
return Region;
}
public void setRegion(String region) {
Region = region;
}
public String getIncome() {
return Income;
}
public void setIncome(String income) {
Income = income;
}
public String getMarried() {
return Married;
}
public void setMarried(String married) {
Married = married;
}
public String getChildren() {
return Children;
}
public void setChildren(String children) {
Children = children;
}
public String getCar() {
return Car;
}
public void setCar(String car) {
Car = car;
}
public String getSave_Act() {
return Save_Act;
}
public void setSave_Act(String save_Act) {
Save_Act = save_Act;
}
public String getCurrent_Act() {
return Current_Act;
}
public void setCurrent_Act(String current_Act) {
this.Current_Act = current_Act;
}
public String getMortgage() {
return Mortgage;
}
public void setMortgage(String mortgage) {
this.Mortgage = mortgage;
}
public String getPep() {
return Pep;
}
public void setPep(String pep) {
Pep = pep;
}
public String toString() {
return "[ID = " + ", age=";
/// ect....
}
public void processData(List<String[]> content) {
int index = 0;
for (List<String> rowData : content) {
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData.get(0));
o[index].setAge(rowData.get(1));
o[index].setRegion(rowData.get(3));
o[index].setSex(rowData.get(2));
o[index].setIncome(rowData.get(4));
o[index].setMarried(rowData.get(5));
o[index].setChildren(rowData.get(6));
o[index].setCar(rowData.get(7));
o[index].setSave_Act(rowData.get(8));
o[index].setCurrent_Act(rowData.get(9));
o[index].setMortgage(rowData.get(10));
o[index].setPep(rowData.get(11));
System.out.println(rowData);
index++;
}
}
public void printData() {
}
}
The problem is in the processData method. The type of content is List<String[]>. So when you try to loop this list, each element is a String array, not List. Also, since each element in your list is a String array, you can access the elements of each of the String Array elements of the list by using the normal array square brackets, instead of get method of List. Try the following fix:
public void processData(List<String[]> content) {
int index=0;
for (String[] rowData: content){
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData[0]);
o[index].setAge(rowData[1]);
o[index].setRegion(rowData[3]);
o[index].setSex(rowData[2]);
o[index].setIncome(rowData[4]);
o[index].setMarried(rowData[5]);
o[index].setChildren(rowData[6]);
o[index].setCar(rowData[7]);
o[index].setSave_Act(rowData[8]);
o[index].setCurrent_Act(rowData[9]);
o[index].setMortgage(rowData[10]);
o[index].setPep(rowData[11]);
System.out.println(rowData);
index++;
}
}
As your error hints at... content is a List<String[]>, so it contains String[] elements, not List<String> elements.
If your end goal is a list of Client objects, just make the method List<Client> readData() instead.
List<Client> clients = new ArrayList<Client>();
BufferedReader br = null;
try {
//file reader
br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
Client c = null;
while ((line = br.readLine()) != null) {
c = new Client();
String[] rowData = line.split(",");
c.setID(rowData.get(0));
...
clients.add(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {}
}
return clients;
I need help to generate a graph's link connection in json format which are index numbers. I can manage to generate the 1st part of nodes index numbers but can't do the 2nd part of links index numbers. Nodes index number should be plotted links index no. Anyone please help.
Input file:
Abdelaziz Bouteflika,Bush,1
Albert II of Belgium,Bush,1
Albert Wehrer,Bush,1
Berlusconi,Bush,1
Bernard-Montgomery,Bush,1
Bush,Fidel-Castro,1
Bernard-Montgomery,Albert Wehrer,5
Expected Output file:
{
"nodes":[
{"name":"Bush","Id":0},
{"name":"Abdelaziz Bouteflika","Id":1},
{"name":"Albert II of Belgium","Id":2},
{"name":"Albert Wehrer","Id":3},
{"name":"Berlusconi","Id":4},
{"name":"Bernard-Montgomery","Id":5},
{"name":"Fidel-Castro","Id":6}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":0},
{"source":4,"target":0},
{"source":5,"target":0},
{"source":6,"target":0},
{"source":5,"target":3}
]
}
My code:
public class Link_Of_Index {
List<String> linklist1 = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
public void getIndexNo() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("E:/Workspace/Entity_Graph_Creation/WebContent/Graph_nodes_1.csv"));
FileWriter fw = new FileWriter(new File("E:/workspace/Entity_Graph_Creation/Input/links.json"));
try{
String line = null;
int index=0;
while (( line = reader.readLine()) != null)
{
String[] splits = line.split(",");
linklist1.add(splits[0]);
linklist1.add(splits[1]);
linklist1.add(splits[2]);
}
for (String s: linklist1) {
if (!finalList.contains(s)) {
finalList.add(s);
JSONObject obj = new JSONObject();
obj.put("Id", index);
obj.put("name", s);
fw.write(obj.toString()+ ","+ "\n");
index ++;
}
fw.flush();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Link_Of_Index inx = new Link_Of_Index();
inx.getIndexNo();
}
}
EDIT: I rewrote the entire answer to reflect your new requirements. For the next time, you should mention that in first place, or make 2 seperate questions of it.
public class GraphFileIO {
private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() {
#Override
public int compare(Node node1, Node node2) {
return node1.compareTo(node2);
}
};
private Map<Node, List<Edge>> graph;
private final File sourceFile;
public GraphFileIO(final File pSource) throws IOException {
if (pSource.exists()) {
sourceFile = pSource;
} else {
throw new IOException();
}
}
public void readGraph() throws IOException {
int index = 1;
graph = new TreeMap<>(NODE_COMPARATOR);
for (String line : Files.readAllLines(sourceFile.toPath(), Charset.defaultCharset())) {
if (line.trim().isEmpty()) {
continue; // skip blank lines
}
// csv columns:
// node 1, node 2, weight, event
String[] splits = line.split(",");
Node n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
Edge edge = new Edge(splits[3]);
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
Node node = entry.getKey();
if (node.getName().equals(splits[0])) {
edge.setSource(node.getId());
entry.getValue().add(edge);
} else if (node.getName().equals(splits[1])) {
edge.setTarget(node.getId());
// if edges are bi-directional, uncomment the next line of
// code
/* entry.getValue().add(edge); */
}
}
}
}
public void writeGraphToFile(final File targetFile) throws IOException {
JSONObject obj = new JSONObject();
JSONArray nodeList = new JSONArray();
JSONArray edgeList = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
JSONObject jsonNode = new JSONObject();
jsonNode.put("name", entry.getKey().getName());
jsonNode.put("Id", entry.getKey().getId());
jsonNode.put("event", entry.getValue());
nodeList.add(jsonNode);
for (Edge link : entry.getValue()) {
JSONObject link = new JSONObject();
link.put("source", link.getSourceID());
link.put("target", link.getTargetID());
edgeList.add(link);
}
}
obj.put("nodes", nodeList);
obj.put("links", edgeList);
FileWriter fw = new FileWriter(targetFile);
fw.write(obj.toJSONString());
fw.flush();
fw.close();
}
public static void main(final String[] args) {
File source = new File("C:\\Sandbox\\src\\foo\\test.csv");
File target = new File("C:\\Sandbox\\src\\foo\\testresult.csv");
GraphFileIO g;
try {
g = new GraphFileIO(source);
g.readGraph();
g.writeGraphToFile(target);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Node implements Comparable<Node> {
private final Integer id;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
private final String name;
private final Collection<String> events;
public Node(Integer id, String name) {
super();
this.id = id;
this.name = name;
this.events = new HashSet<>();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public Collection<String> getEvents() {
return events;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Node other = (Node) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
#Override
public int compareTo(Node o) {
return id.compareTo(o.id);
}
}
public class Edge {
private final String event;
private Integer sourceID;
private Integer targetID;
public Edge(String string) {
event = string;
}
public void setSource(Integer id) {
sourceID = id;
}
public void setTarget(Integer id) {
targetID = id;
}
#Override
public String toString() {
return event;
}
public Integer getSourceID() {
return sourceID;
}
public Integer getTargetID() {
return targetID;
}
public String getEvent() {
return event;
}
}
I'm trying to save a serialize/deserialize a List of POJOS with Gson. While normally this isn't such a special task, I'm getting an exception that I've never seen before:
01-11 14:17:22.556: E/AndroidRuntime(15941): java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.timkranen.playpalproject/com.timkranen.playpalproject.HomeActivity}:
java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.util.concurrent.locks.Lock.
Register an InstanceCreator with Gson for this type may fix this problem.
I'm suspecting that it has something to with the fact that the List items are being loaded in an AsyncTask. Anyone have experience with this problem?
I've tried putting the logic that I execute within onSaveInstanceState (for saving) in a synchronized method, but that didn't help.
Edit
Here's some of my code to try and make it more clear. I've got a List that is called friendsList. The List is filled in this AsyncTask and is executed in onCreateView()
private class RetrieveFriends extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... params) {
// get friends
if (friendProfiles == null || friendProfiles.size() == 0) {
friendProfiles = new ArrayList<Profile>();
if (currentProfile.getFriendUids() != null
&& currentProfile.getFriendUids().size() > 0)
for (String fUid : currentProfile.getFriendUids()) {
Profile friend = ProfileDataManager
.getProfileFromId(fUid);
friendProfiles.add(friend);
}
if (friendProfiles.size() == 0) {
return "null";
}
}
return "notnull";
}
#Override
protected void onPostExecute(String result) {
if (!result.equals("null")) {
loadingFriendsBar.setVisibility(View.INVISIBLE);
friendsList.setVisibility(View.VISIBLE);
FriendListAdapter adapter = new FriendListAdapter(
containedActivity, R.layout.friendslist_row,
friendProfiles);
friendsList.setAdapter(adapter);
} else {
loadingFriendsBar.setVisibility(View.INVISIBLE);
friendMsg.setVisibility(View.VISIBLE);
}
}
}
Now in the onSaveInstanceState I serialize that List to JSON like this:
private synchronized void saveToState(Bundle state) {
Gson gson = new Gson();
Type listOfProfiles = new TypeToken<List<Profile>>() {
}.getType();
String json = gson.toJson(friendProfiles, listOfProfiles);
state.putString("json_friendProfiles", json);
}
That method is called directly in onSaveInstanceState(). Retrieving it is the same:
private synchronized void retrieveFromState(String json) {
Type listOfProfiles = new TypeToken<List<Profile>>() {
}.getType();
Gson gson = new Gson();
friendProfiles = (List<Profile>) gson.fromJson(json,
listOfProfiles);
}
The weird thing is, the state is correctly saved when navigating to a different Fragment. The error only occurs when I change the orientation.
Edit: On request here's the Profile class
public class Profile {
private String mEmail;
private String mPassword;
private String uid;
// optional properties
private String name;
private String location;
private String about;
private ParseFile image; // not certain of data type
private List<String> friendUids;
public String getName() {
if (name == null || name.equals("")) {
return "Name unknown";
}
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
if (location == null || location.equals("")) {
return "Location unknown";
}
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getAbout() {
if (about == null || about.equals("")) {
return "About unknown";
}
return about;
}
public void setAbout(String about) {
this.about = about;
}
public void setUid(String Uid) {
this.uid = Uid;
}
public String getUid() {
return this.uid;
}
public String getPassword() {
return mPassword;
}
public String getEmail() {
return mEmail;
}
public Profile(String email, String password) {
this.mEmail = email;
this.mPassword = password;
}
/*
* Saves a Profile and returns the profiles UID This is ONLY APPLICABLE for
* NEW profiles use the update method to update existing profile data
*/
public void saveToParse(SaveCallback saveCallBack) {
if (ProfileDataManager.IsRegistered(this) != true) {
ParseObject pObject = new ParseObject("Profiles");
pObject.put("email", this.mEmail);
pObject.put("password", this.mPassword);
pObject.saveInBackground(saveCallBack);
} else {
saveCallBack.done(new ParseException(ErrorCodes.ALREADY_REGISTERED,
"AlreadyRegistered"));
}
}
public void update() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Profiles");
query.getInBackground(this.uid, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
// update the object
object.put("email", Profile.this.mEmail);
object.put("password", Profile.this.mPassword);
if (Profile.this.name != null) {
object.put("name", Profile.this.name);
}
if (Profile.this.location != null) {
object.put("location", Profile.this.location);
}
if (Profile.this.about != null) {
object.put("about", Profile.this.about);
}
if (Profile.this.image != null) {
object.put("profileImage", Profile.this.image);
}
if (Profile.this.friendUids != null
&& Profile.this.friendUids.size() != 0) {
object.put("friends", Profile.this.friendUids);
}
object.saveInBackground();
}
}
});
}
/*
* Use updateWithCallBack when you want to update an object but want to show
* the updated data immediatly using a callback, when calling this method
* make sure that currentProfile in HomeActivity is set to the new Profile!
*/
public void updateWithCallBack(final SaveCallback callBack) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Profiles");
query.getInBackground(this.uid, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
// update the object
object.put("email", Profile.this.mEmail);
object.put("password", Profile.this.mPassword);
if (Profile.this.name != null) {
object.put("name", Profile.this.name);
}
if (Profile.this.location != null) {
object.put("location", Profile.this.location);
}
if (Profile.this.about != null) {
object.put("about", Profile.this.about);
}
if (Profile.this.image != null) {
object.put("profileImage", Profile.this.image);
}
if (Profile.this.friendUids != null
&& Profile.this.friendUids.size() != 0) {
object.put("friends", Profile.this.friendUids);
}
object.saveInBackground(callBack);
}
}
});
}
// retrieves the image, when done calls callback
public void retrieveProfileImage(GetDataCallback callBack) {
this.image.getDataInBackground(callBack);
}
public ParseFile getProfileImage() {
return this.image;
}
public void setProfileImage(ParseFile image) {
this.image = image;
}
public void saveProfileImage(Bitmap image) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byteArray = stream.toByteArray();
String imgid = this.getUid() + "_profile_image.jpeg";
String fileNameForImage = this.getUid() + "_profile_image.jpeg";
this.image = new ParseFile(fileNameForImage, byteArray);
}
public List<String> getFriendUids() {
return this.friendUids;
}
public void addFriend(String uid) {
if (this.friendUids != null) {
friendUids.add(uid);
} else {
friendUids = new ArrayList<String>();
friendUids.add(uid);
}
}
public void setFriends(Object friends) {
ArrayList<String> f = (ArrayList<String>) friends;
this.friendUids = f;
}
}
Gson object
private Gson gson = new GsonBuilder().
setExclusionStrategies(new ParseExclusion()).
create();
Exclusion Class
private class ParseExclusion implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
return (f.getDeclaredClass() == Lock.class);
}
}
Finally:
Type type = new TypeToken<List<Profile>>() {}.getType();
List<Profile>) friendProfiles = new ArrayList<Profile>();
friendProfiles = gson.fromJson(json,type);
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.