Parse.com Search (Android) - Direct-Hit Search - java

What I've essentially built is an EditTextView that collects a String, which when input by the user attempts to communicate with the back-end in order to pull the user's "objectId", this being a column in my User database.
The showProfileActivity() function shown below simply works, and I've excluded it because it isn't relevant to the problem. It takes the user's "objectId" and shows the user's profile.
What I want is for "String userId", which is the User's "objectId" in the database to be generated dynamically. I know that the showProfileActivity() function works because I can literally just input a String with the hard-coded objectId and it brings me to that user's profile.
My question is, based on the String input by the user into the search field, how can I retrieve the value in the relevant "objectId" column?
findViewById(R.id.submitSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchUserTextField = (EditText) findViewById(R.id.searchUserTextField);
// Value input to search field
final String searchInput = searchUserTextField.getText().toString();
// System.out.println(searchInput);
// Initiate ParseQuery
final ParseQuery<ParseUser> query = ParseQuery.getQuery("username");
// Look for the username that was typed into the search field
query.whereEqualTo("username", searchInput);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
// The query was successful.
// This works but clearly always loads the exact same user profile. I need this string to be loaded dynamically as a function of the user's search query.
String userId = "dj16qsXPle";
// System.out.println(userId);
showProfileActivity(userId);
} else {
// Something went wrong.
}
}
});
// Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
});
}

I am not sure what showProfileActivity does, but since you are passing it a userId I am assuming it does another query? Why not do the following:
Assuming usernames are unique (in this case it seems you are also assuming that) Then the findInBackground method should return just a single user.
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
// The query was successful.
if(objects.size() > 0){
ParseUser user = objects.get(0);
showProfileActivity(user);
}
} else {
// Something went wrong.
}
}
});
And in showProfileActivity, use the user data do whatever showProfileActivity does.
Or, if you are using the objectId for something else, you can do this:
ParseUser user = objects.get(0);
showProfileActivity(user.getObjectId());
and this gives you the id you are looking for instead of the hardcoded one. Again, doing in showProfileActivity whatever it is you do with the objectId. This could mean retrieving from a separate table using objectId, etc..

Ultimately figured it out. I granted you the answer because you definitely provided the core of the correct solution. My error was in initiating my ParseQuery as such: final ParseQuery query = ParseQuery.getQuery("username");. It should have just been ParseQuery query = ParseUser.getQuery();
// Initiate ParseQuery
ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("username", searchInput);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
// The query was successful.
System.out.println(objects);
ParseUser user = objects.get(0);
String userId = user.getObjectId();
showProfileActivity(userId);
} else {
// Something went wrong. Look at the ParseException to see what's up.
}
}
});

Related

Replace element of ArrayList if object of same value already present in it

I'm using socket.io for my chat app. I have an ArrayList which contains last message, username, time. Whenever a new message arrives in JSON format then it should check if JSON contained username is present in ArrayList or not. If present, then updates the ArrayList otherwise add in ArrayList.
Here is my code:-
private Emitter.Listener handle1 = new Emitter.Listener() {
#Override
public void call(final Object... args) {
ChatLists.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject)args[0];
try {
String sendername = data.getString("sender");
String lastMessage = data.getString("message");
String profileImage = data.getString("Profile");
String token = data.getString("fb_token");
chat_list chat_list = new chat_list(sendername,
profileImage, lastMessage, "0", "", "dummy", token);
if (chat_lists.size()==0){
chat_lists.add(chat_list);
}else {
for (int i=0;i<chat_lists.size();i++){
if (chat_lists.get(i).getContactname().equals(sendername)){
chat_lists.set(i,chat_list);
}else {
chat_lists.add(chat_list)
}
}
}
contactlistAdapter = new ContactlistAdapter(chat_lists);
recyclerView.setAdapter(contactlistAdapter);
contactlistAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
};
Well, you can use contains() & set() methods of ArrayList in a logical way to solve your problem like below:-
if(chat_lists.contains(username))
chat_lists.set(indexOf(username), new_username);
else chat_lists.add(new_username);
Try it:
if(chat_lists.contains(chat_list)){
chat_lists.remove(chat_list);
chat_lists.add(chat_list);
} else {
chat_lists.add(chat_list);
}
Read about architecture patterns, for example, MVP.
You need to store your messages somethere (in Model) and update view relative to data.
Also read about RecyclerView, cause of ListView is a little bit deprecated
if (chat_lists.get(i).getContactname().equals(sendername)){
above statement has problem them. It's not getting under your if condition and following the chat_lists.add(chat_list) statement.
Instead equals use ignoreCasequals. If still wont it solve your problem please use debug mode or logs check chat_lists.get(i).getContactname()
and sendername same or not.

android parse query only gets newest data on the column

final String name = getIntent().getStringExtra("name");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Info");
query.whereEqualTo("user", name);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null){
ArrayList<String> barbers = new ArrayList<String>();
for (ParseObject object : objects){
barbers.add(String.valueOf(object.get("times")));
}
ArrayAdapter arrayAdaptar = new ArrayAdapter<String>(Barbers.this, android.R.layout.simple_list_item_1, barbers);
list.setAdapter(arrayAdaptar);
}
}
});
I am making a app where people put times and then other people can see all their times when they click their name. I have made this query to get all the times from that certain person that they clicked on but when the app runs it only gets me the newest time and if the person that you clicked is not the newest will not retrieve anything. Thank you, here are some screenshots of my Parse Server and of the query.

Parse.com How to return a value from a query in Android

I'm using the Parse API to query some data for an Android application and I would like to know how to return a value (for example a Boolean) from a Parse Query. For example I would like a function that returns true if some data exists and false otherwise like so :
public Boolean myFunction(){
ParseQuery<ParseObject> query = ParseQuery.getQuery();
query.findInBackground("someData",new GetCallback<ParseObject>() {
#Override
public void done(ParseObject lan, ParseException e) {
if(e==null){
return true;
} else {
return false;
}
});
}
I do know that this cannot be done this way because the query is processed in a background thread and I'm not very familiar with Callbacks.
I am aware that there is a similar question here Parse.com how to get return value of query but this is for JavaScript.
Do you have any idea on how to do that ?
You are almost there. When you get the Parse Object extract it with:
boolean myBoolean = myParseObject.getBoolean("myBooleanColumn");
Full example (finding an object via id, it can be adapted for other type of queries):
ParseQuery<ParseObject> query = ParseQuery.getQuery("YourClass");
query.getInBackground("id", new GetCallback<ParseObject>() {
public void done(ParseObject myParseObject, ParseException e) {
if (e == null) {
boolean myBoolean = myParseObject.getBoolean("myBooleanColumn");
} else {
// something went wrong
}
}
});
Update: if you only want to check if some data exists in a row you can do it with
query.whereEqualTo("columnToFind", "searchterm");
You can even find compare an array with the data in row with
query.whereContainsAll("columnToFind", arrayOfThingsToSearch);
After some research and thanks to #buckettt, the easiest way to accomplish that is to use Parse Cloud Code. Define your function in the main.js file inside parse-server folder :
Parse.Cloud.define("myFunction",function(req,res){
var userId = req.params.userId; //params passed in Client code
var myQuery = new Parse.Query(Parse.User);
myQuery.equalTo("userId", userId);
myQuery.find({
success: function(results) {
res.success(results.get("userName"));
}
error: function() {
res.error("Failed !");
}
}
});
And in your Client's code :
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userId",userId);
ParseCloud.callFunctionInBackground("myFunction", params, new FunctionCallback<String>() {
public void done(String res,ParseException e){
if (e == null) {
Log.i("Results :",res);
} else {
Log.i("Error",e.getMessage());
}
}
});
This way you return the desired value and the function is executed directly on your server. Hope this helps

Android ArrayList size set to zero after call

I'm currently working on a basic application that makes a query to parse (back4app) backend, the aim is to retrive ParseGeoPoint from every row in the class "Annuncio" and display them in the google map.
The query works fine, I have an ArrayList that is populated after the query:
ParseQuery<ParseObject> query = ParseQuery.getQuery(Keys.CLASS_NAME);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for(ParseObject object : objects){
createAnnuncio(object);
}
progressDialog.hide();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
the createAnnuncio method is this:
private void createAnnuncio(ParseObject object) {
Azienda azienda = new Azienda();
azienda.setWebSite(object.getString(Keys.SITO_WEB));
azienda.setEmail(object.getString(Keys.EMAIL));
azienda.setPhoneNumber(object.getString(Keys.TELEFONO));
azienda.setLocation(object.getParseGeoPoint(Keys.LOCATION));
azienda.setNomeAzienda(object.getString(Keys.NOME_AZIENDA));
azienda.setDescAzienda(object.getString(Keys.DESC_AZIENDA));
Annuncio annuncio = new Annuncio();
annuncio.setAzienda(azienda);
annuncio.setCompleteText(object.getString(Keys.TESTO_ANNUNCIO));
annuncio.setJobKind(object.getString(Keys.TIPO_LAVORO));
annuncio.setSettore(object.getString(Keys.SETTORE));
annuncio.setTitolo(object.getString(Keys.TITOLO_ANNUNCIO));
annuncio.setFineAnnuncio(object.getDate(Keys.FINE_ANNUNCIO));
mAnnunci.add(annuncio);
}
Basically mAnnunci is a global variable:
public List<Annuncio> mAnnunci = new ArrayList<>();
Even the debug works fine, i have just 2 rows and the mAnnunci.size() is 2 after the for cycle in the query, but then the debugger takes me to some native code of parse sdk and i don't know why but after the query mAnnunci is empty.
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
showSpinner();
getAllPostsFromParse(); // retrive all posts from parse backend
//inside getAllPostsFromParse the size is 2
setUpMarkers(); // here the size is 0 (the debug print is the first instruction, so I don't modify it)
}
And most of all sorry for my bad english!

How to query a user Pointer<_user> field using Parse.com with Android

Really struggling with this query, all I want to do is run a query through my Routines table selecting Routines that belong to a certain user. Running a normal query would require something query.whereEqualTo("routineIcon", "1") would bring up the the first and third row. However, the tricky bit is querying the user (Point<_user>) field, this is a reference to a user (objectId) from the User class. Initially I tried query.whereEqualTo("user", "RE1bvmzyPk"), but this came out blank so I looked into querying Pointers, I've trie d a few things but can't get it to work. Anyone got any tips?
private void retrieveRoutines() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Routine");
query.whereEqualTo("user", "RE1bvmzyPk");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> routines, ParseException e) {
if (e==null){
mRoutines = routines;
String[] routineNames = new String[mRoutines.size()];
int i = 0;
for (ParseObject routine : mRoutines) {
routineNames[i] = routine.getString("routineName");
Log.d("OK", routineNames[i]);
i++;
}
}
else {
//error
}
}
});
}
The Routine Class is in the format:
objectId (string) | routineIcon (string) | routinesName (string) | user (Pointer<_User>
You can create the user pointer by using the objectid of the user
ParseUser user=new ParseUser();
user.setObjectId("RE1bvmzyPk");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Routine");
query.whereEqualTo("user", user);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> routines, ParseException e) {
if (e==null){
}
else {
//error
}
}
});
if you want routines that point back to ( were created by a User )
Add the pointer field to Routines:
"createdBy" type=pointer
And then query for it using the User Obj.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Routine");
query.whereEqualTo("createdBy", $userObj);

Categories