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()
{
}
Related
I am threading a time consuming for-loop and executing them inside N number of threads. A continue statement is throwing error
Getting the error "Continue cannot be used outside of a loop"
for (final Message m : messagelistholder.getMessage()) {
Callable<Void> tasksToExecute = new Callable<Void>() {
public Void call() {
if (guidanceonly1 == true && !QuoteUtil.isECPQuote(list.get(0))) {
String msg = "Message From " + m.getSource() + " when retrieving Guidance values: "
+ m.getDescription();
String lcladdStatusMessages = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_MSG_FRM_WHN_RETRVNG_GUIDNCE_VAL",
new String[]{m.getSource(), m.getDescription()}, msg);
list.get(0).addStatusMessages("Info", lcladdStatusMessages);
} else if ("Error".equalsIgnoreCase(m.getSeverity())) {
if (m.getCode().indexOf("_NF") > 0) {
continue; // price not found due to private sku
}
if ("Eclipse".equalsIgnoreCase(m.getSource())) {
String msg1 = "Please check Sold To customer data. ";
String lcladdStatusMessages1 = CommonUtil
.getLoclizedMsg("PRCE_LNE_ITM_PLS_CHK_SLDTO_CUST_DTA", null, msg1);
String msg2 = "Discount information may not be returned from Optimus due to "
+ m.getSeverity() + " From " + m.getSource() + " " + m.getDescription();
String lcladdStatusMessages2 = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_DSCNT_INFO_MNT_RTRND_FRM_OPTMS_DUETO_FRM",
new String[]{m.getSeverity(), m.getSource(), m.getDescription()}, msg2);
list.get(0).addStatusMessages(m.getSeverity(),
(m.getDescription().contains("MDCP") ? lcladdStatusMessages1 : "")
+ lcladdStatusMessages2);
} else {
if (response1.getItems() == null) {
String lcladdStatusMessages = CommonUtil.getLoclizedMsg("PRCE_LNE_ITM_OPTMS_ERR",
new String[]{m.getSource(), m.getDescription()}, m.getDescription());
list.get(0).addStatusMessages("Error", lcladdStatusMessages);
list.get(0).setOptimusError(true);
} else {
if (!QuoteUtil.isECPQuote(list.get(0))) {
String lcladdStatusMessages = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_MSG_FRM_WHN_RETRVNG_GUIDNCE_VAL",
new String[]{m.getSource(), m.getDescription()},
"Message From " + m.getSource() + " " + m.getDescription());
list.get(0).addStatusMessages("Info", lcladdStatusMessages);
list.get(0).setOptimusError(true);
}
}
}
}
if (list.get(0).getFlags().get(QtFlagType.ESCALATIONFORPARTNER) != null) {
list.get(0).getFlags().get(QtFlagType.ESCALATIONFORPARTNER).setFlgVl(null);
}
if (m.getCode() != null) {
String pricingServiceMsgCode = m.getCode();
String pricingServiceSeverity = m.getSeverity();
Map<Integer, AutoEscalationScenario> categoryMap;
if (StringUtils.equals("ERROR", pricingServiceSeverity)) {
categoryMap = getScenario("SEVERITY", globalAccount1, null, true, null);
if (categoryMap.size() != 0) {
finalCategorylist.get(0).putAll(categoryMap);
}
}
if (partnerExclusivityAutoEscalation1) {
categoryMap = getScenario(pricingServiceMsgCode, globalAccount1, null, true, null);
if (categoryMap != null && categoryMap.size() != 0) {
finalCategorylist.get(0).putAll(categoryMap);
}
}
}
return null;
}
};
runnableTasks.add(tasksToExecute);
}
Can someone help me to skip the particular loop for the speicified condition but without using continue statement since it throws error.
What's happening is that you are actually calling continue outside of a loop because the call() function itself does not have a for loop, so it doesn't matter if are only calling call() from a loop.
What can you do to fix this is making the call function to return a boolean and replacing the continues with return true and return false if no return true has been reached.
Then replace the:
call()
on the loop(s) for
if(call()) continue
So the I'm not saying I fully understand you code, but it appears that you are using continue to break out of that thread. On a normal multi-threaded application, it looks like you are launching multiple threads from one one loop. The continue call is inside the new thread, not the loop. As soon as you start writing the call() method, you leave the loop to run it. Looking at the code, I would try replacing continue with return. Normally I would try running it myself before I suggest it, but without the rest of the code I cannot verify that it works.
I have issue with searching trough ParseQuery Array.
I need case insensitive search, so i need to convert my array to lowercase.
I tried query.whereMatches and query.whereContains without success.
My guess is to make new method that would convert all data from ParseQuery to lowercaseString Array.
Am i right with this one?
Here's the example code for setting search result list:
private void setList(boolean hardRefresh) {
// stop any ongoing progress dialog
cancelProgressDialog();
reloadTags();
reloadContents();
ParseQuery<Note> query = Note.getQuery()
.fromLocalDatastore()
.orderByDescending("date");
String searchStr = searchText.getText().toString().toLowerCase();
if (!searchStr.isEmpty()) {
query.whereMatches(Note.FIELD_DETAIL, searchStr);
}
try {
mNotes = query.find();
if (adapter == null) {
adapter = new ListAdapter();
notesGridView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
} catch (ParseException e) {
e.printStackTrace();
}
For case insensitive search try like this :
if (!searchStr.isEmpty()) {
query.whereMatches(Note.FIELD_DETAIL, searchStr,"i");
}
I am getting an array from parse.com. I am using an array, to retrieve an array:
fightList.whereContainedIn("objectId", itemListCard);
fightList.findInBackground(new FindCallback<ParseObject>() ....
My first array; itemListCard is in a specific order. After I findInBackground, my array from online, (objectId), is completely out of order. This is because I am getting it from Parse.com, so it is added to the array as it is retrieved. I need to:
1. Re-order array objectId to match itemListCard or
2. Retrieve objectId in order of itemListCard
Java code:
HomeItemList = new ArrayList<HomeItem>();
fightList.whereContainedIn("objectId", itemListCard);
fightList.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objectId, ParseException e) {
if (e == null) {
for (int i = 0; i < objectId.size(); i = i + 2) {
HomeItem homeItem = new HomeItem();
homeItem.setHomeItemID(k);
k++;
//set Red Array
homeItem.setHomeItemRedName(objectId.get(i).getString("Name"));
homeItem.setHomeItemRedAge(objectId.get(i).getString("Age"));
homeItem.setHomeItemRedRecord(objectId.get(i).getString("Record"));
homeItem.setHomeItemRedHeight(objectId.get(i).getString("Height"));
homeItem.setHomeItemRedWeight(objectId.get(i).getString("Weight"));
homeItem.setHomeItemRedCity(objectId.get(i).getString("Location"));
homeItem.setHomeItemRedExp(objectId.get(i).getString("Experience"));
//set blue Array
homeItem.setHomeItemBlueName(objectId.get(i+1).getString("Name"));
homeItem.setHomeItemBlueAge(objectId.get(i+1).getString("Age"));
homeItem.setHomeItemBlueRecord(objectId.get(i+1).getString("Record"));
homeItem.setHomeItemBlueHeight(objectId.get(i+1).getString("Height"));
homeItem.setHomeItemBlueWeight(objectId.get(i+1).getString("Weight"));
homeItem.setHomeItemBlueCity(objectId.get(i+1).getString("Location"));
homeItem.setHomeItemBlueExp(objectId.get(i+1).getString("Experience"));
HomeItemList.add(homeItem);
}
HomeListAdapter = new HomeListAdapter(getApplicationContext(), 0, HomeItemList);
adapter.addSection(" Fight Card ", HomeListAdapter);
} else {
progressDialog.dismiss();
Log.d("Display Card", "Error parsing Card");
Log.d("Card Error:", e.getMessage());
Toast.makeText(databaseFightCard.this, "Could not retrieve parse info. Try again later", Toast.LENGTH_LONG).show();
}
listView.setAdapter(adapter);
progressDialog.dismiss();
}
});
Note
The for loop is counting by 2 because this is the structure I am going for:
objectId[0] vs objectId[1]
objectId[2] vs objectId[3]
objectId[4] vs objectId[5]
objectId[6] vs objectId[7]
....and so on
Hence the need for a specific order.
You can control the order in which the items are returned using orderByAscending() and orderByDescending().
In your case:
fightList.whereContainedIn("objectId", itemListCard);
fightList.orderByAscending("objectId");
fightList.findInBackground(new FindCallback<ParseObject>() ....
See Query Constraints section of the the Parse Android Guide.
I have a project as follows: Several photos are taken from a mobile, the photos are saved in a web system, which in turn displays the photos on google earth that is inside it. I've read many articles but all of them were using fetchKml, one good article that i've read was using php, but using fetchKml. I dont know if its possible using parseKml instead. Anyway, I'm not sure how to do this with the kml, so it looks tike this:
My Class KMLGenerator()
public static String getKMLFromObra (List<Obra> obraFotos) {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version='1.0' encoding='UTF-8'?>");
sb.append("<kml xmlns='http://www.opengis.net/kml/2.2' " +
"xmlns:gx='http://www.google.com/kml/ext/2.2' " +
"xmlns:kml='http://www.opengis.net/kml/2.2' " +
"xmlns:atom='http://www.w3.org/2005/Atom'> ");
if (obraFotos != null && obraFotos.size() > 0) {
for (Obra o : obraFotos) {
for (Local local : o.getLocais()) {
sb.append("<Document>");
sb.append("<name>" + local.getName() + "</name>");
sb.append("<Style id='defaultStyles'>");
sb.append("<IconStyle>");
sb.append("<scale>1.1</scale>");
sb.append("<Icon>");
sb.append("<href>" + "http://localhost:8080/ConstruMobilFoto/lib/img/fotoIcon.png" + "</href>");
sb.append("</Icon>");
sb.append("</IconStyle>");
sb.append("</Style>");
sb.append("<Placemark>");
sb.append("<name>" + "Foto" + "</name>");
sb.append("<styleUrl>" + "#defaultStyles"+ "</styleUrl>");
sb.append("<altitudeMode>" + "relativeToGround" + "</altitudeMode>");
sb.append("<Point>");
sb.append("<altitudeMode>relativeToGround</altitudeMode>");
sb.append("<coordinates>" + local.getLongitude() + "," + local.getLatitude() + "," + 50</coordinates>");
sb.append("</Point>");
sb.append("<Link>");
sb.append("<href>" + local.getFotos() + "</href>");
sb.append("</Link>");
sb.append("</Placemark>");
sb.append("</Document>");
sb.append("</kml>");
return sb.toString();
}
}
}
return null;
}
I have a dwr function in my jsp that invokes this method, got its String results and make the parse like this:
Class PainelEarth()
#SuppressWarnings("static-access")
public String geraFotosObra (int idObra) throws Exception {
try {
List<Obra> obraFotos = obraBusiness.getObraLatLong(new Obra(idObra));
return new KMLGenerator().getKMLFromObra(obraFotos);
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
return null;
}
}
and in my jsp page
function initCB(instance) {
// other codes
showPics(ge);
}
function showPics(ge) {
PainelEarthAjax.geraFotosObra({
callback : function(kmlString) {
var kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
}
});
return null;
}
Any help will be welcome!!
In your code if you look at the signature of the method geraFotosObra you can see it takes a single int parameter idObra.
public String geraFotosObra (int idObra) throws Exception { ...
Yet when you call the method in your jsp you are passing an an object literal containing a callback function.
PainelEarthAjax.geraFotosObra({
callback : function(kmlString) { ...
As it is I don't see how the kml is generated, unless perhaps geraFotosObra is an overloaded method? Also even if it was generated, as is, I don't see how the callback function that you pass in place of an id is ever called - why for example would kmlString be the result of the call to geraFotosObra?
// How is this called, what sets kmlString!?
callback : function(kmlString) {
var kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
}
All in all the code you posted is a wee bit confusing, so sorry if I have missed something...I think you have possibly copy and pasted some code from a fetchKml example and the asynchronous callbacks used with that method have confused you slightly.
Anyhow, based on what you have posted, you should be passing an int id to the geraFotosObra method, getting the string result and then parsing it in the plug-in.
Something like the following makes sense. Replace the showPics function with the following.
function showPics(ge) {
var kmlString = PainelEarthAjax.geraFotosObra(1); // or something?
var kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
}
Hope your problem is resolved, but my problem is still there
and I thought that you can help me to get out of this problem.
actually I had multiple events to publish one by one as per user
selection for eg: user select Season, Service, DateFrom and
DateTo and then clicks on the refresh button.
When the refresh button is clicked I had used the above logic to
get all the datas using the below mentioned code
public void onClick$ref(Event event){
if(lbox_service.getSelectedIndex() != 0 || lbox_season.getSelectedIndex() != 0)
{
if(lbox_service.getSelectedIndex() == 0)
{
setService_id("0");
}
else
{
setService_id(lbox_service.getSelectedItem().getValue().toString());
}
if(lbox_season.getSelectedIndex() == 0)
{
setSeason_id("0");
}
else
{
setSeason_id(lbox_season.getSelectedItem().getValue().toString());
}
System.out.println("Service Index 11 : "+ lbox_service.getSelectedIndex());
System.out.println("Season Index 11 : "+ lbox_season.getSelectedIndex());
EventQueue evtQ = EventQueues.lookup("myEventQueue", EventQueues.APPLICATION, true);
//evtQ.publish(new Event("service_id", self, lbox_service.getSelectedItem().getValue().toString()));
//evtQ.publish(new Event("season_id", self, lbox_season.getSelectedItem().getValue().toString()));
evtQ.publish(new Event("service_id", self, getService_id()));
evtQ.publish(new Event("season_id", self, getSeason_id()));
//evtQ.publish(new Event("onClickRef", null, lbox_service.getSelectedItem().getValue().toString()));
//evtQ.publish(new Event("onClickRef", null, lbox_season.getSelectedItem().getValue().toString()));
/*.publish(new Event("onClickRef", null, lbox_service.getSelectedItem().getValue().toString()));
EventQueues.lookup("myEventQu", EventQueues.DESKTOP, true).publish(new Event(
"onClickRef", null, lbox_season.getSelectedItem().getValue().toString()));*/
}
else
{
setService_id("0");
setSeason_id("0");
EventQueue evtQ = EventQueues.lookup("myEventQueue", EventQueues.APPLICATION, true);
evtQ.publish(new Event("service_id", self, getService_id()));
evtQ.publish(new Event("season_id", self, getSeason_id()));
System.out.println("Service Index : "+ lbox_service.getSelectedIndex());
System.out.println("Season Index : "+ lbox_season.getSelectedIndex());
}
}
now i had publish all my value and after that my new Controller
run that will subscribe those published values. using the
below code
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
EventQueues.lookup("myEventQueue", EventQueues.APPLICATION, true).subscribe(new EventListener() {
public void onEvent(Event event) throws Exception {
/*String service = (String) event.getData();
logger.info("Servive $$$$$$$$$ " + service);
//String season = (String) event.getData();
//logger.info("Season $$$$$$$$$ " + season); */
if("service_id".equals(event.getName())) {
setService_id((String) event.getData());
baseController.setFilter_bar(true);
System.out.println("Service Id :" +event.getData());
}
else if("season_id".equals(event.getName())) {
setSeason_id((String) event.getData());
baseController.setFilter_bar(true);
System.out.println("Season Id :" +event.getData());
}
/*setService_id((String) event.getData());
setSeason_id((String) event.getData());*/
/*if("season_id".equals(event.getName())){
setSeason_id((String) event.getData());
}else
{
setSeason_id("0");
}*/
System.out.println("Filter bar :" +baseController.isFilter_bar());
if(baseController.isFilter_bar() == true)
{
String dateFrom = "";
String dateTo = "";
String order = "2";
List TDRetailers = verificationStoreHibernateDao.getTraditionalRetailers(
getService_id(), getSeason_id(), dateFrom, dateTo, order);
//VerificationStoreHibernateDao storeHibernateDao = new VerificationStoreHibernateDao();
//List TDRetailers = this.verificationStoreHibernateDao.getTraditionalRetailers(service_id);
//ListModel listModel = this.retailers.getModel();
ListModelList listModelList = (ListModelList) retailer.getModel();
listModelList.clear();
listModelList.addAll(TDRetailers);
baseController.setFilter_bar(true);
}
}
});
}
but actully my problem is with running the query and with
getting those published values. Based on them I will be able to
run my Traditional getTraditionalRetailers queries.
My problem is
how to publish multiple events values. Is it the right way
that I had done.
as I had done separate publish, everytime
I publish new value The query runs, the result is that i had
mutiple time query execution. for example If i will publish two
values the queries run's for the two times and if I publish
three values the query executes for three time.
I don't know what is their problem. Help me to solve my error.
The event object passed through EventQueue is where you put your payload there. You can just define an aggregate Event class and collect information and publish them in a whole.
If you can publish all information in a whole(using an aggregate Event), this is solved automatically.