I am having a problem to implement a ParseQuery in a HashMap. My code is as follows:
HashMap<String, Integer> portfoliodata;
public HashMap getPoints() {
try {
ParseQuery<RoyalPoints> pointsQuery = RoyalPoints.getQuery();
pointsQuery.whereEqualTo("user", ParseUser.getCurrentUser());
List<RoyalPoints> list = pointsQuery.find();
portfoliodata = new HashMap<>();
for (RoyalPoints obj : list) {
portfoliodata.put(obj.getString("business"), portfoliodata.get(obj.getString("business")) + obj.getInt("points"));
}
} catch (ParseException e) {
Log.d("Points retrieval", "Error: " + e.getMessage());
}
return portfoliodata;
}
Yet, my result is empty even though obj.getString("business") and obj.getInt("points") give results and no errors are generated. Any idea how I could solve this?
It looks like there should be errors.
On the first run through the loop, you execute:
portfoliodata.put(
obj.getString("business"),
portfoliodata.get(obj.getString("business")) + obj.getInt("points"));
where portfoliodata.get(obj.getString("business")) would give you a null (because the map is empty), and adding that to an int should throw a NullPointerException.
Related
I am having a hard time writing a couple of lines of code. All my current codes are in: https://github.com/anabeen/MeetingJava
The problem that I have is, finding a suitable way to go through the hashmap and get the meetings that have overlapping times and replace them.
Map<LocalDate, Set<Meeting>> meetings = new HashMap<LocalDate, Set<Meeting>>();
Let's say we have a HashMap of
[{2011-03-21=[objectMeeting1, objectMeeting2]}]
and we need to add objectMeeting3 to that hashMap. How do I select the key "2011-03-21" to look at the objects in that hashmap and compare the set of objects in there with a new objectMeeting3's time (part of the data from object) and then replace that object?
In GitHub, I am trying to pass the MeetingSchedulerTest (). This is where I am stuck at:
Meeting meeting = extractMeeting(employeeId, requestLines[i],
officeStartTime, officeFinishTime, meetingSlotRequest1);
if(meetings.containsKey(meetingDate)){
// if the order overlaps
for (Map.Entry<LocalDate, Set<Meeting>> meetingEntry : meetings.entrySet()) {
if (meetingDate == meetingEntry.getKey())
{
Set<Meeting> setOfMeeting = meetingEntry.getValue();
for (Meeting m : setOfMeeting) {
}
}
}
// if the order doesn't
if (meetings.get(meetingDate) != null)
//shouldNotHaveOverlappingMeetings
{
System.out.println("HERES?");
meetings.remove(meetingDate);
Set<Meeting> meetingsForDay = new HashSet<Meeting>();
meetingsForDay.add(meeting);
meetings.put(meetingDate, meetingsForDay);
} else
{
System.out.println("HERES2?");
meetings.get(meetingDate).add(meeting);
}
}else if (meeting != null){
// if meeting doens't have meetingDate then create a new HashMap with date & Meeting
System.out.println("HERES3?");
Set<Meeting> meetingsForDay = new HashSet<Meeting>();
meetingsForDay.add(meeting);
meetings.put(meetingDate, meetingsForDay);
}
}
I figured out the answer by using this:
for (Map.Entry<LocalDate, Set<Meeting>> meetingEntry : meetings.entrySet()) {
if (meetingDate.equals(meetingEntry.getKey()))
{
System.out.println("HERES1? ");
Set<Meeting> setOfMeeting = meetingEntry.getValue();
for (Meeting m : setOfMeeting) {
System.out.println("comparing time? " + m.getStartTime().getHourOfDay() + " TO "
+ meeting.getStartTime().getHourOfDay());
if (m.compareTo(meeting) == 0) {
continue;
} else {
setToPut.add(m);
}
}
}
}
I'm in the process of building a basic database using csv files, and i'm currently testing the select function out when i ran into something strange.
private ArrayList<Record> selectField(String selectTerm)
{
Log.log("Selection " + selectTerm,2,"DB_io");
ArrayList<Record> ret = new ArrayList<Record>();
if (titleRow.values.contains(selectTerm))
{
Log.log("Adding values to " + selectTerm);
int ordinal = titleRow.values.indexOf(selectTerm);
Log.log("Ordinal " + ordinal);
List<String> tempList = new ArrayList<String>();
for (Record r : data)
{
List<String> tempList = new ArrayList<String>();
tempList.add(r.values.get(ordinal));
Record s = new Record(tempList);
ret.add(s);
tempList.clear();
}
Log.log("Number of records in ret " + ret.size());
for (Record t : ret)
{
Log.log(t.toString());
}
}
else
{
Log.log("keyField does not contain that field");
return null;
}
Log.log("Values " + ret.toString());
return ret;
}
When i do this, the part where it logs t.ToString() shows the record to be empty, whereas if i log it before tempList.clear(), it shows the record to be containing data like it should.
If i move the tempList declaration into the Record r : data loop, then it works fine and the Record t : ret loop works outputs the contents of the record like it should
Why is this?
Edit : Record class
public class Record
{
List<String> values = new ArrayList<String>();
public Record(List<String> terms)
{
this.values = terms;
}
public Record(String[] s)
{
this.values = Arrays.asList(s);
}
public String toString()
{
return values.toString();
}
}
Your Record instance holds a reference to the ArrayList instance you passed to its constructor. Therefore, when you call tempList.clear(), you clear the same List that your Record instance is holding a reference to.
You shouldn't call tempList.clear(), since you are creating a new ArrayList in each iteration of your loop anyway.
you are referencing object from more than one place and clear method is cleaning object by setting its reference to null:
instead of ret.add(s); you can use ret.add(s.clone());
I want get the name of each object in this return list, but the output is an array of Object[], and this show entitys.Categoria[id=1] in my JComboBox control.
I not understand this. Please help me! This is my code:
public List<Categoria> consultarCategorias() {
try {
TypedQuery<Categoria> q =
em.createQuery("select c from Categoria c", Categoria.class);
List<Categoria> results = q.getResultList();
return results;
} catch (Exception e) {
return null;
}
}
Note: I use this
for (Categoria c : results) {
System.out.println(c.getName());
}
and not work, this show the result cannot convert to Categoria
This is the code to fill my JComboBox:
public void fillCmbCategorias() {
cmbCategoria.removeAllItems();
try {
Object[] listaCategorias = crud.consultarCategorias().toArray();
DefaultComboBoxModel dcb = new DefaultComboBoxModel(listaCategorias);
cmbCategoria.setModel(dcb);
} catch (Exception e) {
JOptionPane.showMessageDialog(null
,"No se pudo cargar la lista de categorias. " + e.getMessage());
}
}
Only reason i can imagine that you have declared the result as some super type list, like List<?> or List<Object>.
Assuming you can assing the return value of consultarCategorias() to it.
And of course you should not do it this way - you should correct the list generic type - but this might then work:
for (Object c : results) {
System.out.println(((Categoria)c).getName());
}
Update (after problem code added):
Your problem seems be this:
Object[] listaCategorias = crud.consultarCategorias().toArray();
as i suspected.
Try
Categoria[] listaCategorias =
crud.consultarCategorias().toArray(new Categoria[]{});
// toArray() needs some array instance to determine the type
About Lists and converting to Arrays see more here Convert list to array in Java
Can you try casting like this :
List<Categoria> results = (List<Categoria>)q.getResultList(); `
This is the Code I was made. It shouldn't get and enter to NoResultException, but it doesn't as expected. There is an unused data. I try to print out, here is the output : "[ ]"
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = tableDataRangka.getSelectedRow();
String idRangka = tableDataRangka.getValueAt(row, 0).toString();
System.out.println( relasiRumahkayuRangkaDAO.getRelasiByIdRangka(idRangka).toString() );
} catch (NoResultException nre) {
// Doing something..
} catch (Exception ex) {
Logger.getLogger(MasterDataProjectUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code of method "getRelasiByIdRangka" :
public List<RelasiRumahKayuRangka> getRelasiByIdRangka(String idRangka) throws Exception{
initEntityManager();
List<RelasiRumahKayuRangka> rrDrs = new ArrayList<>();
Query q = em.createNamedQuery("RelasiRumahKayuRangka.findByIdRangka");
q.setParameter("idRangka", idRangka);
rrDrs.addAll(q.getResultList());
closeEntityManager();
return rrDrs;
}
And this one is the JPA query, findByIdRangka :
#NamedQuery(name = "RelasiRumahKayuRangka.findByIdRangka", query = "SELECT r FROM RelasiRumahKayuRangka r WHERE r.relasiRumahKayuRangkaPK.idRangka = :idRangka"),
Do you guys know the solution, so the code can be catched by NoResultException ?
In your code. if the result set is empty then list will also be empty.
Make use of that situation and throw a desired exception.
In your getRelasiByIdRangka(String idRangka) add following changes.
public List<RelasiRumahKayuRangka>
getRelasiByIdRangka( String idRangka ) throws Exception {
initEntityManager();
// rest of the code here
// ...
// check if some results are found or not
if( rrDrs.isEmpty() ) { // or ( rrDrs.size() == 0 )
throw new NoResultException( "No results found" );
} // if empty
// this should be a filled in list
return rrDrs;
} // end of method
I'm new to Parse and was wondering if there is any way to store all the ParseFiles (in this case images) for a given ParseUser into something like an ArrayList?
Here's my code:
public ArrayList<ParseFile> getFiles() {
ArrayList<ParseFile> files = new ArrayList<ParseFile>();
//mUser is the current ParseUser
ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> fileList, ParseException e) {
if (e == null) {
Log.d("FILES", "Retrieved " + fileList.size() + " files");
for(ParseObject ch:fileList) {
image = ch.getParseFile("image");
files.add(image);
#Override
public void done(byte[] arg0, ParseException arg1) {
//nothing to do here
}
});
}
Log.i("TAG", ": " + files.size());
} else {
Log.d("FILES", "Error: " + e.getMessage());
}
}
});
Log.i("DONE", ": " + files.size());
return files;
}
When I'm inside done(), the 3 images I have for this particular user are added and I get an ArrayList of size 3 which is to be expected. When I'm outside of done(), the size of the ArrayList goes back to 0, which I'm assuming is because it's being referenced outside of the query. And sure enough it returns an empty ArrayList (not too shocking).
I feel like this should be an easy solution but I can't seem to figure it out. I've tried to make a static ArrayList variable but that doesn't seem to work either. Any idea on how to return the desired ArrayList?
I believe the problem is that the outside thread still continues before your background process is completed. In other words..
1. query.findInBackground(....);
2. Log.i("DONE" ....);
.. 2. is executed before 1. completes. The whole point of Parse "inBackground" is that it completes actions that your thread is not dependent on. If you need to do something with the List, you should do it in the same thread as the background thread or not do it "inBackground".
Try like this
ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername());
List<ParseObject>imageList=query.find();
try {
Arraylist<ParseFile> files = new Arraylist<ParseFile>files();
ParseFile image;
for(int i =0;i<imageList.size();i++)
{
image = imageList.get(i).getParseFile("image");
files.add(image);
}
}
catch()
{
}