Parse query always returns an empty list - mongodb

I have the following problem:
I have two Android apps: In one app I add data to Mongo DB via Parse and in the other app I want to retrieve the information added from the first app.
The problem is that in the second app everytime I try to query the DB, I get an empty list. I`ve checked with the API KEY, with the keys from the Mongo DB, and everything seems ok in my app.
Here is the code for the second app to retrieve information in a RecyclerView
public class ParseDb extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId(API_KEY)
.server("http://injuriesandsuspensions.herokuapp.com/parse/")
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
public class MainActivity extends Activity {
private List<AboutTeams> aboutTeamsList = new ArrayList<AboutTeams>();
private RecyclerView recyclerView;
private GamesAdapter gamesAdapter;
public void retrieveGamesFromDatabase(){
ParseQuery<ParseObject> query = ParseQuery.getQuery("InjuriesAndSuspensions");
query.whereEqualTo("score", "none");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> gamesList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + gamesList.size() + " scores");
for(int i = 0; i < gamesList.size(); i++){
AboutTeams aboutTeams = new AboutTeams();
aboutTeams.setId(String.valueOf(gamesList.get(i).getObjectId()));
aboutTeams.setScore(String.valueOf(gamesList.get(i).get("score")));
aboutTeams.setHomeTeam(String.valueOf(gamesList.get(i).get("homeTeam")));
aboutTeams.setHomeTeamMissing(String.valueOf(gamesList.get(i).get("homeTeamMissingPlayers")));
aboutTeams.setAwayTeam(String.valueOf(gamesList.get(i).get("awayTeam")));
aboutTeams.setAwayTeamMissing(String.valueOf(gamesList.get(i).get("awayTeamMissingPlayers")));
aboutTeams.setDate(String.valueOf(gamesList.get(i).get("gameDate")));
Log.d("About Teams " , aboutTeams.toString());
aboutTeamsList.add(aboutTeams);
gamesAdapter.notifyDataSetChanged();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_listview);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
gamesAdapter = new GamesAdapter(aboutTeamsList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(gamesAdapter);
retrieveGamesFromDatabase();
}
Please help as I`ve been struggling with this thing for almost 3 days.

When I was adding info to the Collection DB,the ParseObject I was using didn`t have this line added where I was initializing Parse in my application:
defaultACL.setPublicReadAccess(true);
Complete code on how to initialize Parse:
public class AddToDB extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId(API_KEY)
.server(SERVER_URL)
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
**defaultACL.setPublicReadAccess(true);**
ParseACL.setDefaultACL(defaultACL, true);
}
}

Related

Pushing data from one user to another in Vaadin web app

I get the fact that it might take more than 10 lines of code (hopefully not more than 50), but I was wondering if you could help me anyway.
I'm trying to update one user's UI thread at runtime, based on another user's input. I've created a basic project which implements three predefined users (jim, tom and threeskin). I'd like to send a message from jim to tom and have it appear as a new Label object in tom's UI, without threeskin ever knowing about it, even though they're all logged in. Oh, and jim shouldn't have to refresh his page. The label should just spawn on screen out of it's own accord.
To say that I'd appreciate some help would be the understatement of the decade.
public class User {
public String nume;
public User(String nume) {
super();
this.nume = nume;
}
}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
public class Engine implements ServletContextListener {
public static ArrayList<User>userbase;
public void contextDestroyed(ServletContextEvent arg0) { }
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("This code is running at startup");
userbase =new ArrayList<User>();
userbase.add(new User("jim"));userbase.add(new User("tom"));userbase.add(new User("threeskin"));
}
}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
public class InfigeUI extends UI {
User us3r;
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = InfigeUI.class)
public static class Servlet extends VaadinServlet {}
protected void init(VaadinRequest request) {
VerticalLayout everything=new VerticalLayout();
setContent(everything);
if (us3r==null){everything.addComponent(auth());}else{everything.addComponent(main());}
}
ComponentContainer auth(){
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
TextField userField=new TextField();
Button login = new Button("Log in");
login.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
us3r=login(userField.getValue());
if (us3r!=null){
saveValue(InfigeUI.this, us3r);
layout.removeAllComponents();
layout.addComponent(main());
}else{Notification.show("I only know jim, tom and threeskin. Which one are you?");}}
});
layout.addComponent(userField);
layout.addComponent(login);
return layout;
}
User login(String nume){
for (int i=0;i<Engine.userbase.size();i++){
if (nume.equals(Engine.userbase.get(i).nume)){return Engine.userbase.get(i);}
}
return null;
}
static void saveValue(InfigeUI ui,User value){
ui.us3r=value;
ui.getSession().setAttribute("something", value);
VaadinService.getCurrentRequest().getWrappedSession().setAttribute("something", value);
}
ComponentContainer main(){
VerticalLayout vl=new VerticalLayout();
Label label=new Label("This is the post-login screen");
String name=new String(us3r.nume);
Label eticheta=new Label(name);
TextField to=new TextField("Send to");
TextField message=new TextField("Message");
Button sendNow=new Button("Send now!");
vl.addComponent(eticheta);
vl.addComponent(label);
vl.addComponent(eticheta);
vl.addComponent(to);
vl.addComponent(message);
vl.addComponent(sendNow);
return vl ;
}
}
Basically you want three things
UI updates for a user which does no action himself, or in other words a message sent from the server to the browser. To enable this, you need to annotate the UI class using #Push. Otherwise, the update will only be shown when the user does something which causes a server visit, e.g. clicks a button
Some way of sending messages between UI instances (there is one UI instance per user). You can use some message bus implementation for this (CDI, Spring, ...) or you can make a simple on using a static field (static fields are shared between all users). See e.g. https://github.com/Artur-/SimpleChat for one way of doing it. It's also a good idea here to avoid all *.getCurrent methods as they in many cases will refer to another UI than you think (e.g. sender when you are in the receiver code), and you will do something else than you intend.
Safely update a UI when a message arrives. This is done using UI.access, also visible in the chat example.
First of all you need to enable the server push on your project help
based on Vaadin Documentation.
However, below code example will give what you want:
Create an Broadcast Listener Interface:
public interface BroadcastListener {
public void receiveBroadcast(final String message);
}
The Broadcaster Class:
public class Broadcaster {
private static final List<BroadcastListener> listeners = new CopyOnWriteArrayList<BroadcastListener>();
public static void register(BroadcastListener listener) {
listeners.add(listener);
}
public static void unregister(BroadcastListener listener) {
listeners.remove(listener);
}
public static void broadcast(final String message) {
for (BroadcastListener listener : listeners) {
listener.receiveBroadcast(message);
}
}
}
Your UI with Push Enalbed (via Annotation):
#Push
public class BroadcasterUI extends UI implements BroadcastListener {
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
final TextArea message = new TextArea("",
"The system is going down for maintenance in 10 minutes");
layout.addComponent(message);
final Button button = new Button("Broadcast");
layout.addComponent(button);
button.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
Broadcaster.broadcast(message.getValue());
}
});
// Register broadcast listener
Broadcaster.register(this);
}
#Override
public void detach() {
Broadcaster.unregister(this);
super.detach();
}
#Override
public void receiveBroadcast(final String message) {
access(new Runnable() {
#Override
public void run() {
Notification n = new Notification("Message received",
message, Type.TRAY_NOTIFICATION);
n.show(getPage());
}
});
}
you can find the full link here.

Update ListView via AsyncTask or IntentService

I am trying to Update my Custom ListView which is fed by two String Arrays:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getStringArray(ARG_PARAM1);
mParam2 = getArguments().getStringArray(ARG_PARAM2);
}
setupListView();
}
private void setupListView() {
listItemList = new ArrayList();
if (mParam1 != null && mParam2 != null && mParam1.length == mParam2.length) {
for (int i = 0; i < mParam1.length; i++) {
listItemList.add(new MyListItem(mParam1[i], (mParam2[i]).substring(0, 75) + "..."));
}
} else {
listItemList.add(new MyListItem("Loading...", "Swipe Down for Update"));
}
mAdapter = new MyListAdapter(getActivity(), listItemList);
}
mParam1 and mParam2 are Values which are fetched by an XML parser (IntentService) class in the MainActivity which i can show if needed.
Now, if i am to fast, and the mPara1 and mPara2 is empty there won´t be any ListView shown. Now i want to solve this by some AsyncTask or IntentService whatever is useful. I tried AsyncTask, which didn´t work at all. I tried notifyDataSetChanged() which didn´t work too...
Now, how could i solve this....
Using AsyncTask i have the problem that i don´t know how to passt the two Arrays to publishProgress() correctly
THis is how my AsyncTask looks like:
class UpdateListView extends AsyncTask<Void, String, Void> {
private MyListAdapter adapter;
private ArrayList listItemList;
#Override
protected void onPreExecute() {
adapter = (MyListAdapter) mListView.getAdapter();
}
#Override
protected Void doInBackground(Void... params) {
for (String item1 : mParam1) {
publishProgress(item1);
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
adapter.add(new MyListItem(values[0], values[1]));
}
#Override
protected void onPostExecute(Void result) {
Log.d("onPostExecute", "Added successfully");
}
}
Okay solved it...My Fragments are running in same Activity where the Data is loaded in, so i just created getter and setter in MainActivity and access them in the needed Fragment via
String[] titles =(MainActivity) getActivity()).getTitlesArray();
String[] text=(MainActivity) getActivity()).getTextArray();
Whatever i do trying setting Bundle with
bundle.putStringArray(TITLES,titles);
doesn´t work. Should work using parceable/serializable class but didn´t try...

Netbeans lookup not getting executed first time when the application is started

I have an application in which lookup provider is in explorer window and it is a jcomboBox. Its selected value is provided as lookup to other top components and displayed one in editor and one in output window area. The value of the jcombobox is saved at the time of closing the application and initialized into the jcombobox when the application is started.
When I clean and build the application and start the application, the initial value displayed in the jcombobox is not updated in the lookup and listner windows display uninitialized values. Once the new value is selected in the jcombobox it gets displayed in the other windows.
If I close the application without changing the value of the jcombobox and start the application, the lookup is not updated.
If I change the selection in the combobox, close the application and start again, the lookup gets updated.
I expect anytime when the application is started, the other windows will get the value of the lookup. Any help in this regards will be appreciated. Thanks in advance.
The code for the explorer window which provides the lookup is as follows:
public final class ProviderTopComponent extends TopComponent {
public ProviderTopComponent() {
initComponents();
setName(Bundle.CTL_ProviderTopComponent());
setToolTipText(Bundle.HINT_ProviderTopComponent());
associateLookup(new AbstractLookup(content));
}
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
str = (String) jComboBox1.getSelectedItem();
content.set(Collections.singleton(str), null);
}
private final InstanceContent content = new InstanceContent();
String str;
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
p.setProperty("val", (String) jComboBox1.getSelectedItem());
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
String v = p.getProperty("val");
if(v != null) {
jComboBox1.setSelectedItem(v);
}
}
}
The code for the lookup listener window is as follows:
public final class Listner_1TopComponent extends TopComponent implements LookupListener{
public Listner_1TopComponent() {
initComponents();
setName(Bundle.CTL_editorTopComponent());
setToolTipText(Bundle.HINT_editorTopComponent());
}
...
private void initComponents() {
...
jLabel1 = new javax.swing.JLabel();
...
Collection<? extends String> str_collection;
private Lookup.Result<String> result = null;
String str;
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
#Override
public void componentOpened() {
result = org.openide.util.Utilities.actionsGlobalContext().lookupResult(String.class);
result.addLookupListener(this);
}
#Override
public void componentClosed() {
result.removeLookupListener(this);
}
#Override
public void resultChanged(LookupEvent le) {
str_collection = result.allInstances();
if (str_collection.isEmpty()) {
} else {
str = str_collection.iterator().next();
}
jLabel1.setText(str);
jLabel1.repaint();
}
}

Loader for SimpleComboBox - GXT

I want to create a Dynamic ComboBox i.e it fetches data from DB
On pressing some buttons(on other Panels) I want to reload the ComboBox.
ComboBox Store Datatype : List
I created an RPC call(RPCProxy) which fetches List
However I cannot create a Loader to map it to my ComboBox Store, as Loader is mapped only to a Store that Extends BeanModel instance.
So I can fetch data only once while loading, but I cant refetch data, as I cant use a loader.
Here is some part of Code:
SimpleComboBox myCombo = new SimpleComboBox();
List myStore = new ArrayList();
XX.getService().getMyDD(userData.getId(), weekOffset, new AsyncCallback<List<String>>() {
public void onFailure(
Throwable caught) {
MessageBox.alert(UIConstants.ERROR,caught.getMessage(),
null);
}
public void onSuccess(List<String> result) {
for(String str: result)
{
myStore.add(str);
}
myCombo.removeAll();
myCombo.add(myStore);
myCombo.setSimpleValue(UIConstants.ALL);
}
});
RpcProxy<List<String>> userTypeProxy = new RpcProxy<List<String>>() {
#Override
protected void load(Object loadConfig,
AsyncCallback<List<String>> callback) {
try {
System.out.println("In Loader: my: "+my);
XX.getService().getMyDD(userData.getId(), weekOffset,
callback);
} catch (Exception e) {
MessageBox.alert(UIConstants.ERROR,
UIConstants.ERROR_USER_RETRIEVED, null);
}
}
};
Please let me know if I can implement any type of loader for my ComboBox, like ListLoader etc.
I highly appreciate your help in advance.

GWT new EntityProxy in #OneToOne with another EntityProxy from server

I am just creating a new Proxy:
LayoutExampleRequest r = requestFactory.employeeRequest();
DepartmentProxy d = r.create(DepartmentProxy.class);
r.save(d);
departmentEditor.editProxy(d, r);
Then pass the Proxy and the Request(LayoutExampleRequest ) to my editor
driver.edit(proxy, request);
Until here ! everything works as espected. I can save Department objects with null EmployeeProxy. Now iam getting with a suggest box Proxys of EmployeeProxy from the server.
search = new SuggestBox(new SuggestOracle() {
#Override
public void requestSuggestions(final Request request,final Callback callback) {
System.out.println(request.getQuery());
//ignore less than 3
if(request.getQuery().length() > 3){
requestFactory.employeeRequest().search(request.getQuery()).fire(new Receiver<List<EmployeeProxy>>(){
#Override
public void onSuccess(List<EmployeeProxy> response) {
List<MySuggestion<EmployeeProxy>> suggestions = new ArrayList<MySuggestion<EmployeeProxy>>();
for(EmployeeProxy e:response){
MySuggestion<EmployeeProxy> suggestion = new MySuggestion<EmployeeProxy>();
suggestion.setModel(e,e.getFirstName(),e.getFirstName()+" "+e.getLastName());
suggestions.add(suggestion);
}
callback.onSuggestionsReady(request, new Response(suggestions));
}
});
}
}
});
MySuggestion is a wrapper class to handle the EmployeeProxy.
Now i want to add this EmployeeProxy to my DeparmentProxy since i have a #OneToOne on JPA.
search.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
MySuggestion<EmployeeProxy> s = (MySuggestion<EmployeeProxy>)event.getSelectedItem();
proxy.setSupervisor(s.getModel());
}
});
proxy is the EntityProxy for Department (I sent to my editor) driver.edit(proxy, request);
then i fire the driver:
departmentEditor.getDriver().flush().fire(new Receiver<Void>() {
#Override
public void onSuccess(Void response) {
Window.alert("Success");
// refresh the datagrid
Range range = dataGrid.getVisibleRange();
dataGrid.setVisibleRangeAndClearData(range, true); //1st way
// create a new DepartmentProxy to bind to the Editor.
createProxy();
// change button text
updateButton.setText("Save");
}
#Override
public void onConstraintViolation(Set<ConstraintViolation<?>> violations) {
for(ConstraintViolation v :violations){
Window.alert(v.getMessage()+" "+v.getPropertyPath());
}
}
#Override
public void onFailure(ServerFailure error) {
Window.alert(error.getMessage());
}
});
The problem is iam getting ConstraintViolations from the EmployeeProxy, is like the driver atach the EmployeeProxy but with null values.
(Iam validating my Entityes with JSR-330 )
Dont know how to make a relationship with a new Proxy with other taked from the server. in a #OneToOne relationship
Any help would be nice!
Thank you
/* UPDATE */
Something like this but with editor
final LayoutExampleRequest r = requestFactory.employeeRequest();
final DepartmentProxy d = r.create(DepartmentProxy.class);
d.setName("Name");
d.setService(Service.CONTRACT_MANAGMENT);
// get some random employee
requestFactory.employeeRequest().findById(1).fire(new Receiver<EmployeeProxy>() {
#Override
public void onSuccess(EmployeeProxy response) {
d.setSupervisor(response);
r.save(d).fire(new Receiver<DepartmentProxy>() {
#Override
public void onSuccess(DepartmentProxy response) {
Window.alert("Kidding me! why editor cant get it work =p?");
}
});
}
});
The problem was i put on my editor properties of the EmployeeProxy so when a user select the employeproxy would see information about it, so i delete them and then do the same and now works.
Is like GWT when detects properties from another proxy on the editor thinks you will fill it. And the line:
proxy.setSupervisor(s.getModel());
doesn't works.