How to Search a specfic value in parse.com? - android

Method checkMobileTableAccount uses to check a phone number in table Account, strMobile is phone number to search.
public boolean checkMobileTableAccount(final String strMobile) {
result = false;
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Account");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
for (ParseObject user : objects) {
String mobile = user.getString("phonenumber");
if (strMobile.equals(mobile)) {
result = true;
break;
}
}
}
});
return result;
}
How can I get result after for loop finished?

Just dont use method findInBackground(). Use find() which is not making your request in background.
public boolean checkMobileTableAccount(final String strMobile) {
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Account");
try {
List<ParseObject> objects = query.find();
for (ParseObject user : objects) {
String mobile = user.getString("phonenumber");
if (strMobile.equals(mobile)) {
return true;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}

Related

Parse Query objects.size always returns 0 Android

public void pictureQuery() {
friendsPic = new ArrayList<>();
for (int i = 0; i < friendsList.length(); i++) {
ParseQuery parseQuery = ParseQuery.getQuery("Data");
parseQuery.whereEqualTo("firstName", "John");
//parseQuery.whereEqualTo("userId",friendsID.get(i));
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
String link = objects.get(0).get("picUrl").toString();
Bitmap bitmap = null;
try {
bitmap = task.execute(link).get();
friendsPic.add(bitmap);
} catch (Exception e1) {
e1.printStackTrace();
}
Log.i("FDA, done", friendsPic.toString());
} else {
Log.i("FD", "0002");
}
} else {
e.printStackTrace();
}
}
});
}
}
Hi guys,
I am trying to retrieve picture URL from parse server (stored as a string), originally I was trying to make a query using the Id, but also tried to hard code it using:
parseQuery.whereEqualTo("firstName", "John");
It always seems to go to the else statement of object.size() > 0 i.e.
Log.i("FD", "0002");
I think i've checked everything including:
size of friendsList ( for the for loop )
spelling, made sure that "Data", "firstName" and "John" are the same on Parse Server
The value of friendsID.get(i)
Tried to use findFirstInBackground instead (same issue)
I have also compared it with my other code for different data ( that works ) :
ParseQuery parseQuery = ParseQuery.getQuery("SportData");
parseQuery.whereEqualTo("id", mApp.getId());
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
saveSportData(objects.get(0), false);
} else if (objects.size() < 1) {
saveSportData(null, true);
}
} else {
e.printStackTrace();
}
}
});
Any idea what am I doing wrong, or what may be causing it ?
Thanks a lot.

How to pin parse relation data in local data store?

Retrieved data and stored in local database but while trying to pull relation from the local database I get empty list which indicates that the relation data is not pinned to the local database.
public void retrieveThreadListStoreInDB()
{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Threads");
query.include("postedBy");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if(e == null)
{
// Query is successful now lets load data from parse
ParseObject.pinAllInBackground((List<ParseObject>) list, new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null)
{
if(!isFinishing())
{
// TODO : Notify to refresh data
}
}
else
{
Log.d("DEBUG","ERROR PINNING DATA WITH EXCEPTION : "+e);
}
}
});
}
}
});
So how should I pin "relation" data to the local database ???
What is the best way to read comments which is a relation. shall I store them in local datastore or pull data in the background ??
make sure you enableLocalDatastore store in application class Parse.enableLocalDatastore(getApplicationContext());
Parse local data store will not work with cache policy. We can access relational data like below
private void getParseData() {
if (parseObjectId != null) {
mApp.show_PDialog(context, "Loading..");
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("Profile");
parseQuery.getInBackground(parseObjectId, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
try {
newName = parseObject.getString("name");
newGender = parseObject.getString("gender");
newDOB.setTime(parseObject.getDate("dob"));
newTOB.setTime(parseObject.getDate("tob"));
newCurrentLocation = parseObject.getParseObject("currentLocation");
newPOB = parseObject.getParseObject("placeOfBirth");
if (newName != null) {
displayName.setText(newName);
}
if (newGender != null) {
gender.setText(newGender);
}
if (newDOB != null) {
DateFormat df = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault());
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String subdateStr = df.format(newDOB.getTime());
datePicker.setText(subdateStr);
}
if (newTOB != null) {
DateFormat df = new SimpleDateFormat("hh:mm a", Locale.getDefault());
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String subdateStr = df.format(newTOB.getTime());
timepicker.setText(subdateStr);
}
if (newPOB != null) {
placeOfBirth.setText(newPOB.fetchIfNeeded().getString("name")
+ ", " + newPOB.fetchIfNeeded().getParseObject("Parent").fetchIfNeeded().getString("name") + ", " + newPOB.getParseObject("Parent").fetchIfNeeded().getParseObject("Parent").fetchIfNeeded().getString("name"));
}
if (newCurrentLocation != null) {
currentLocation.setText(newCurrentLocation.fetchIfNeeded().getString("name")
+ ", " + newCurrentLocation.fetchIfNeeded().getParseObject("Parent").fetchIfNeeded().getString("name") + ", " + newCurrentLocation.fetchIfNeeded().getParseObject("Parent").fetchIfNeeded().getParseObject("Parent").fetchIfNeeded().getString("name"));
}
} catch (ParseException e1) {
e1.printStackTrace();
}
} else {
e.printStackTrace();
}
mApp.dialog.dismiss();
}
});
} else {
getActivity().finish();
}
}

Finding which phone contacts are users in Parse

In my application, each user signs in with a phone number. In other words, each username corresponds to a different number. I want to detect which phone contacts are using this application in a way. However, I could not determine how should I do this. At first, I think about querying for each contact and get users_in_contacts by using an OR query at the end. This method is given in this answer:
public void getFriends(List<String> numbers) {
List<ParseQuery<ParseUser>> queries = new ArrayList<ParseQuery<ParseUser>>();
for (String number : numbers) {
ParseQuery<ParseUser> parseQuery = ParseUser.getQuery();
parseQuery.whereEqualTo("username", number);
queries.add(parseQuery);
}
ParseQuery<ParseUser> userQuery = ParseQuery.or(queries);
userQuery.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> numberList, ParseException e) {
if (e == null) {
for (int i = 0; i < numberList.size(); i++) {
Log.v("" + i + ". user_contact", numberList.get(i).getUsername());
}
}
}
});
}
It is a working solution but I do not want to burst too many queries and exceed the limit of request per second. Thus, I want to know is there a better alternative or not.
In short, how can I achieve to find the users that are in contacts as fast and costless (with respect to request per second) as possible? I will be all ears to every advice and alternative ways comes from you. Thank you in advance.
There is a querying method named as .whereContainedIn() in Parse. By using this query, I can get users which are already in my contracts without using any other query. I put all of my contracts (which associated with a phone number) as parameter in this method and it worked. I wrote a AsyncTask to perform these operations and monitor the results in a ListView. If you give any advice to increase the performance of this task, I will appreciate it.
public class RetrieveContactedUsersTask extends AsyncTask<String, Void, String> {
private Activity activity;
HashMap<String, String> contactsMap = new HashMap<>();
String[] contactedUserNumbers;
ListView contactsView;
public RetrieveContactedUsersTask (Activity activity, ListView contactsView) {
this.activity = activity;
this.contactsView = contactsView;
}
#Override
protected String doInBackground(String... params) {
retrieveContactList();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
TreeMap<String, String> contactedUsersMap = new TreeMap<>();
for (int i = 0; i < contactedUserNumbers.length; i++) {
contactedUsersMap.put(contactsMap.get(contactedUserNumbers[i]), contactedUserNumbers[i]);
}
contactsView.setAdapter(new ContactAdapter(activity, contactedUsersMap));
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
public void retrieveContactList() {
Cursor phones = null;
try {
phones = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext())
{
String _number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("\\s+", "");
String _name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contactsMap.put(_number, _name);
}
phones.close();
} catch ( Exception e ) {}
finally {
if(phones != null){
phones.close();
}
}
try {
retrieveContactedUsers(contactsMap);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void retrieveContactedUsers(Map<String, String> numbers) throws ParseException {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContainedIn("username", numbers.keySet());
List<ParseUser> users= query.find();
contactedUserNumbers = new String[users.size()];
for (int i = 0; i < users.size(); i++) {
String value = users.get(i).getUsername();
contactedUserNumbers[i] = value;
}
}
}

No success with retrieving from parse

I'm trying to read from parseObject. I have a class over there and I'm trying to get the messages from there but I get only the last message that is sent from the device.
So if I send two messages only the last one is sent.
Can anyone help me?
This is my code:
ParseQuery<ParseObject> query = ParseQuery.getQuery("SmsTable");
query.whereEqualTo("deviceId", android_id);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, com.parse.ParseException e) {
if (e == null) {
for (ParseObject smsObject : objects) {
Date time = (Date) smsObject.get("date");
myMsg = (String) smsObject.get("message");
usrNum = (String) smsObject.get("phoneNumber");
//happend = (boolean) smsObject.get("happend");
result = time;
}
} else {
}
}
});
if (System.currentTimeMillis() >= result.getTime()&& happend == false) {
// count++;
sendMsg2(myMsg, usrNum);
happend = true;
}
Use this
for (ParseObject smsObject : objects) {
Date time = (Date) smsObject.get("date");
myMsg = (String) smsObject.get("message");
usrNum = (String) smsObject.get("phoneNumber");
//happend = (boolean) smsObject.get("happend");
result = time;
if (System.currentTimeMillis() >= result.getTime()&& happend == false) {
// count++;
sendMsg2(myMsg, usrNum);
happend = true;
}
}
I hope this will solve your problem
It seems that myMsg and usrNum are not an Array or a List.
You only call sendMsg2(myMsg, usrNum) once, after the loop has ended. That is why you only get the last message.
Move sendMsg2(myMsg, usrNum) into the loop.
The problem seems to be that you have located your sendMsg2() outside of both - the callback scope and the loop scope. If you want to have all of your messages being sent you have to put sendMsg2() inside of the loop.
ParseQuery<ParseObject> query = ParseQuery.getQuery("SmsTable");
query.whereEqualTo("deviceId", android_id);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, com.parse.ParseException e) {
if (e == null) {
for (ParseObject smsObject : objects) {
Date time = (Date) smsObject.get("date");
myMsg = (String) smsObject.get("message");
usrNum = (String) smsObject.get("phoneNumber");
//happend = (boolean) smsObject.get("happend");
result = time;
if (System.currentTimeMillis() >= result.getTime()&& happend == false) {
// count++;
sendMsg2(myMsg, usrNum);
happend = true;
}
}
} else {
}
}
});

getting all the records from table -Parse.com

i have around 13000 records on one table(HashTag -classname) . i want to retrieve all of them on a single query. but parse allows only 1000 per query. any other ways get the all the records..
ParseQuery<ParseObject> query = ParseQuery.getQuery("HashTag");
query.whereExists("Tag"); query.orderByAscending("Type"); query.setLimit(1000);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list,
ParseException e) {
// TODO Auto-generated method stub
if (e == null)
{
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
ParseObject p = list.get(i);
String tagid = p.getString("Tag");
String Type = p.getString("Type");
class2 c2 = new class2();
c2.type = "" + Type;
c2.tag = "" + tagid;
listClass2.add(c2);
}
}
Sure, you can run multiple queries on the same table, with query's skip property incremented by 1000 each time:
Get the total number of records via query.count(), and use it to set a 'skip' variable
Run a new query for each 1000 records, updating your skip property accordingly
Process records as normal when each query returns
Something like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("HashTag");
query.whereExists("Tag");
query.countInBackground(new CountCallback() {
public void done(int count, ParseException e) {
if (e == null) {
// The count request succeeded. Run the query multiple times using the query count
int numQueries = Math.ceil(count / 1000); //Gives you how many queries to run
for(int skipNum = 0; l < numQueries; l++){
ParseQuery<ParseObject> query = ParseQuery.getQuery("HashTag");
query.whereExists("Tag"); query.orderByAscending("Type");
query.setLimit(skipNum * 1000);
query.findInBackground(new FindCallback<ParseObject>() {
//Run your query as normal here
}
}
} else {
// The request failed
}
}
//Declare a global variable for storing the complete data
private static List<ParseObject>allObjects;
allObjects=new ArrayList<ParseObject>();
ParseQuery<ParseObject>query3=ParseQuery.getQuery("HashTag");
query3.whereExists("Tag");
query3.setLimit(1000);
query3.findInBackground(getallobjects());
int limit=1000;
int skip=0;
//callback method:
private FindCallback<ParseObject>getallobjects(){
return new FindCallback<ParseObject>(){
#Override
public void done(List<ParseObject>list,ParseException e){
allObjects.addAll(list);
if(list.size()==limit){
skip=skip+limit;
ParseQuery<ParseObject>query=ParseQuery.getQuery("HashTag");
query.setSkip(skip);
query.setLimit(limit);
query.findInBackground(getallobjects());
}else{
//you have full data in allobjects
for(int i=0;i<allObjects.size();i++){}
}
}}}
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("TestObject");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
for(ParseObject p : list){
Log.d("--", (String) p.get("foo")+p.getCreatedAt());
}
}
});

Categories

Resources