getting all the records from table -Parse.com - android

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());
}
}
});

Related

Get all objects back from parse in Android

So I am trying to review all objects back from Parse. I know parse has a limit of 1000, but I found some solutions that allows me to page through the results. However, I can not get those solutions to work. Wondering if someone has dealt with this before.
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());
callback method:
int limit = 1000;
int skip = 0;
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++) {}
}
The issue seems to be that "getallobjects" is not resolved and I can't get the errors to go away.

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;
}
}
}

How to run code sequentially with parse, in Android?

I am trying to get records from parse. My table in parse contains an array of pointers; I was facing difficulties to write parse query, so I first save array of pointers in an ArrayList, now I make a for loop to execute the query; for each loop iteration, I want to get records from parse and update local db then same as for next iterations. But this is creating some different problems. parse getInBackground is not working sequentially.... my outer for loop completely executes then parse method called due to which I am facing problems to save values in local db.
public void insertGroupsInDB(ArrayList<TempGroupClass> temp)
{
Log.d(TAG,"insertGroupsInDB: temp size:"+temp.size());
for(int i = 0;i<temp.size();i++) `//my target is to make inner query run till no of loop times and for each iterations inner parse query will run and then insert records in db against outer insertion group`
{
Groups grp = new Groups();
grp.setGroupTitle(temp.get(i).getGroupTitle());
grp.setGroupType(temp.get(i).getGroupType());
grp.setParseObjectId(temp.get(i).getParseObjectId());
long groupinsert = (YouinDatabase.getInstance(context)).addGroup(grp,context);
//}
/*try
{
final CountDownLatch latch = new CountDownLatch(1);*/
if(groupinsert != -1)
{
//now insert friends
//long friendInsertId = YouinDatabase.getInstance(context).addFriend();
//now get friends from members id
Log.d(TAG,"groups inserted successfully:"+groupinsert);
final ArrayList<Integer> list = new ArrayList<Integer>();
if(temp.get(i).getFriendObjectIdList().size() > 0)
{
for(int j =0;j<temp.get(i).getFriendObjectIdList().size();j++)
{
Log.d(TAG," >>>>>>>>>>>>>>>friend objectId>>>>>>>>>>>>>>:"+temp.get(i).getFriendObjectIdList().get(j));
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContainedIn("objectId",temp.get(i).getFriendObjectIdList());
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> arg0,
ParseException arg1) {
// TODO Auto-generated method stub
if(arg1 == null)
{
//Log.d(TAG,"arg0 size:"+arg0.size());
if(arg0.size() >0)
{
for(int i = 0;i<arg0.size();i++)
{
Log.d(TAG,"arg0.size():"+arg0.size());
Friend f = new Friend();
f.setUsername(arg0.get(0).getString("username"));
f.setParseObjectId(arg0.get(0).getObjectId());
f.setHasAdded(false);
boolean userAlreadyExist = YouinDatabase.getInstance(context).checkUserExistInFriendTable(arg0.get(0).getString("username"));
long friendInsertId = -1;
ArrayList<Integer> list = new ArrayList<Integer>();
int friendid;
if(!userAlreadyExist)
{
// Log.d(TAG,"friend Already not exist :"+userAlreadyExist);
friendInsertId = YouinDatabase.getInstance(context).addFriend(f);
list.add(YouinDatabase.getInstance(context).findFriendIdOfLatestRecord());
friendid = YouinDatabase.getInstance(context).findFriendIdOfLatestRecord();
}
else
{
//Log.d(TAG,"friend Already exist :"+userAlreadyExist);
//list.add(YouinDatabase.getInstance(context).getFriendIdFromFriendName(arg0.get(0).getString("username")));
friendid = YouinDatabase.getInstance(context).getFriendIdFromFriendName(arg0.get(0).getString("username"));
}
// Log.d(TAG,"list size 1 :"+list.size());
int latestGroupInsertId = YouinDatabase.getInstance(context).findGroupIdOfLatestRecord();
long id = YouinDatabase.getInstance(context).addFriendInConnection(friendid,latestGroupInsertId);
//now update user setHasAdded
long updateFriendTable = -1;
if(id != -1)
{
updateFriendTable = YouinDatabase.getInstance(context).updateFriendTable(friendid);
}
Log.d(TAG,">>>>updated friend id information:>>>>");
if(updateFriendTable != -1)
{
Friend friendDetails = YouinDatabase.getInstance(context).getFriendDetailsFromFriendId(friendid);
Log.d(TAG,"friend name:"+friendDetails.getUsername());
Log.d(TAG,"friend:"+friendDetails.getParseObjectId());
Log.d(TAG,"friend added :"+friendDetails.isHasAdded());
Log.d(TAG,"groupId:"+latestGroupInsertId);
}
//YouinDatabase.getInstance(context).get
}
Log.d(TAG,"list size 2"+list.size());
}
}
else
{
Log.d(TAG,"arg1 != null:"+arg1.getMessage());
}
}
});
}
// Log.d(TAG,"list size:"+list.size());
}
//latch.countDown();
}
/*latch.await();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
Right now, the problem is that my outer loop executes twice one after another and then after the loop ends, then my parse method brings data from parse ...due to which it's only updating record in db against last group id ...and it's not inserting records against first groupId
How to resolve this issue? I have used this technique because I failed to write query to get object result of array of pointers using parse.
You could use find() which should do a synchronous operation which might hold up your ui. I have not used parse yet so i dont know. Or you can set up something like below. Remove the outer and check conditions in your callback to determine when to launch the next query.
private int j = 0;
private int loopnumber = temp.size();
ArrayList<TempGroupClass> temp; //setup temp somewhere else
private void doQuery() {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContainedIn("objectId",temp.get(i).getFriendObjectIdList());
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> arg0,
ParseException arg1) {
// TODO Auto-generated method stub
if(arg1 == null)
{
...
...
else
{
Log.d(TAG,"arg1 != null:"+arg1.getMessage());
}
//at the end call the same method to start a query if the loop conditions have not been reached.
if(++i < loopnumber) {
doQuery();
}
}
});
}
}

Android - Parse.com Populating Array from ONE element

I am trying to populate an Array from a parse.com query and I am stock in the part of getting the element from query. basically i dont know where to get the current location for exercise_object.get(location) thanks.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Programs");
query.whereEqualTo("name", objname);
query.orderByAscending("name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
//success
String [] exercice = new String[3];
exercise_object = list;
Toast.makeText(Wko_Display.this, "Workouts", Toast.LENGTH_LONG).show();
ParseObject program_object = exercise_object.get(location);
exercice [0] = exercise_object.getString("wk0");
exercice [1] = exercise_object.getString("wk1");
exercice [2] = exercise_object.getString("wk2");
}
If I understand what you're trying to do correctly, then this should work:
#Override
public void done(List<ParseObject> list, ParseException e){
if (e == null){
for (ParseObject pObj : list){
String[] exercise = new String[3];
// assuming each ParseObject has a pointer to a Program object in the database
ParseObject programObject = pObj.getParseObject("location");
// do whatever you want with this programObject
// then do any further stuff with the current pObj in the list
exercise[0] = pObj.getString("wk0");
// ...
}
} else{
Log.e(TAG, e.getMessage());
}
}
This would be wrong if you're expecting only one object to be returned from the query though. Let me know.

Android: parse query in thread

I'm using the Parse library to query some records from DB that will be shown in a ListView with a custom adapter. I've a table with records and each record should I do a counting query from other table.
This is the thread for the counting query of each object retrieved:
getVisualizations = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < events.size(); i++) {
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseConstant.PT_VISUALIZ);
query.whereEqualTo(ParseConstant.PT_VISUALIZ_EVENTO, events.get(i));
events.get(i).setVisualizations(query.count());
}
}
});
events is an Object ArrayList
And this is the code in the main
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseConstant.PT_EVENT);
query.setLimit(30);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> resultList, ParseException e) {
if (e == null) {
events = new ArrayList<Event>();
for (int i = 0; i < resultList.size(); i++) {
Event event = (Event) resultList.get(i);
events.add(event);
}
if (!getVisualizations.isAlive()) {
getVisualizations.start();
}
if (adapter != null) {
adapter.notifyDataSetChanged();
} else {
adapter = new AdapterEvent(getActivity(), R.layout.list_event, events, list);
AnimationAdapter animAdapter = new SwingBottomInAnimationAdapter(adapter);
animAdapter.setAbsListView(list);
list.setAdapter(animAdapter);
}
loadingBar.setVisibility(View.INVISIBLE);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
The problem is that after the thread has started, I don't know how to block the main thread until the other thread finish. (Sorry for the english :/ )
perhaps you should use Thread.join() - if we are dealing with 2 threads, this will block one thread, while allowing the other to complete, then once it does complete, it will resume. Here is a tutorial on it

Categories

Resources