Parse query does not work - android

The problem just like the title, I tried to count the user (I defined) who have the same name, I used countinbackground or findinbackground, no matter what I did, the count is always 0. Does anyone can help me, I don't know why. Thanks a lot. Below is my code:
public boolean checknameunique(String n) {
boolean notexist = true;
ParseQuery<Userdata> query = ParseQuery.getQuery(Userdata.class);
query.whereEqualTo("name", n);
/*query.countInBackground(new CountCallback() {
public void done(int count, ParseException e) {
if (e == null) {
name_count = count;
}
}
});*/
query.findInBackground(new FindCallback<Userdata>() {
#Override
public void done(List<Userdata> objects, ParseException e) {
if(e==null) {
int size = objects.size();
name_count = size;
}
}
});
if(name_count>0) {
notexist = false;
Toast.makeText(this,
"Username already exist",
Toast.LENGTH_LONG).show();
}
return notexist;
}

I guess you are not aware that findInBackground method is asynchronous, that is why you have that callback inside. You probably want to learn a bit more about threads and async tasks in Android and Parse.
Here is the correct code you would want to have:
public void checknameunique(String n) {
ParseQuery<Userdata> query = ParseQuery.getQuery(Userdata.class);
query.whereEqualTo("name", n);
query.findInBackground(new FindCallback<Userdata>() {
#Override
public void done(List<Userdata> res, ParseException e) {
if(e == null) {
int size = res.size();
if(res.size() > 0) {
showMessage("Username already exist");
} else {
proceed();
}
} else {
showMessage(e.getMessage());
}
}
});
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private void proceed() {
//TODO:
}

Related

Sendbird group channel

Currently i have 2 users:
Tester1 and AnotherTester
I've been trying to create a public group channel using my Tester1
but whenever i try to create one.
It's not showing in my list using AnotherTester
Here is my code in creating public group channel
GroupChannelParams params = new GroupChannelParams()
.setPublic(true)
.setDiscoverable(true)
.setEphemeral(false)
// .addUserIds(users)
.setDistinct(false)
.setName(channelName);
GroupChannel.createChannel(params, new GroupChannel.GroupChannelCreateHandler() {
#Override
public void onResult(GroupChannel groupChannel, SendBirdException e) {
if (e != null) { // Error.
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
Logs.logError(e.getMessage());
retrySendConnection(context, String.valueOf(e.getCode()), e.getMessage());
return;
} else {
// inviteUser(groupChannel);
Logs.logData(groupChannel.getUrl());
Intent i = new Intent(MainActivity.this, channelChatActivity.class);
i.putExtra("channelUrl", groupChannel.getUrl());
startActivity(i);
}
}
});
So Tester1 is the one that created a public group channel
but when i switch to AnotherTester, it doesn't show the public group channel.
Here is my code in retrieving AnotherTester channels
GroupChannelListQuery channelListQuery1 = GroupChannel.createMyGroupChannelListQuery();
channelListQuery1.setIncludeEmpty(true);
channelListQuery1.next(new GroupChannelListQuery.GroupChannelListQueryResultHandler() {
#Override
public void onResult(List<GroupChannel> list, SendBirdException e) {
if (e != null) {
Logs.logError(e.getMessage());// Error.
return;
} else {
groupChannelList.addAll(list);
groupChannelAdapter = new groupChannelAdapter(context, groupChannelList);
initializeRecyclerView(channelAdapter);
}
}
});
i hope you can help me.
You need to do atleast one message in that , then it will show to another user. Please try once to send one message.
Please try this code :-
private void createGroupChannel(List<String> userIds, boolean distinct, final String toID) {
GroupChannel.createChannelWithUserIds(userIds, distinct, "tsg-chat-" + SessionUtils.getCurrentMemberId(this) + "-" + toID, "", "", new GroupChannel.GroupChannelCreateHandler() {
#Override
public void onResult(GroupChannel groupChannel, SendBirdException e) {
if (e != null) {
// Error!
return;
}
}
});
}

Why is my ContentResolver batch operation only putting in 7 out of 21 entries?

I have three fragments in a FragmentPagerAdapter, and each of them would fetch a list of frames/data from a server using Volley. This data would later be used to update the Fragment's RecyclerView Adapter as a Cursor.
VolleyRestClientUtils.get(getString(R.string.PATH_SHOP), LOG_TAG, params, true, false, new JsonHttpResponseHandler() {
public void onSuccess(JSONObject response) {
Log.d(LOG_TAG, "request Response : " + response.toString());
try {
String status = response.getString("status");
if (RestClientUtils.STATUS_OK.equals(status)) {
final JSONArray frames = response.getJSONArray("items");
Log.d(LOG_TAG, "request Response : " + frames.length());
if (frames != null && frames.length() > 0) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
List<ContentValues> listShopFrame = ShopFrame.fromJSONArray(frames, sort);
if (listShopFrame.size() > 0 && isActivityActive()) {
ContentResolver cr = getActivity().getContentResolver();
if (!isRequestMore) {
cr.delete(ShopFrame.CONTENT_URI, ShopFrame.COLUMN_CATEGORY + "=?",
new String[]{sort});
paramSkip = frames.length();
} else {
paramSkip += frames.length();
}
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
String log = listShopFrame.size()+" ";
for (int i = 0; i < listShopFrame.size(); i++) {
operations.add(ContentProviderOperation
.newInsert(ShopFrame.CONTENT_URI)
.withValues(listShopFrame.get(i))
.build());
log += listShopFrame.get(i).toString()+"\n";
}
Log.i("loader_callback_"+sort, log);
//cr.applyBatch(ShopFrame.CONTENT_AUTHORITY, operations);
ContentValues[] opsAsArray = new ContentValues[listShopFrame.size()];
listShopFrame.toArray(opsAsArray);
cr.bulkInsert(ShopFrame.CONTENT_URI, opsAsArray);
//return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
dataRefreshed = true;
Log.i("loader_callback_"+sort, "response post execute");
if (result) {
loadSucceed();
PicMixApp.getInstance().setRefreshed(ShopFrameFragment.this.getClass().getName());
} else {
loadFailed(null);
}
}
}.execute();
} else {
//TODO
//Handle error
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} else if (VolleyRestClientUtils.STATUS_RESOURCE_NOT_FOUND.equals(status)) {
hasMore = false;
loadSucceed();
} else {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception:" + e.getMessage());
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
}
#Override
public void onJSONError(String responseString) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
#Override
public void onFailure(String errMessage, int statusCode, Map<String, String> headers, byte[] responseBytes) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
});
Whereas loadSucceed() has this following code:
if (this.recyclerView != null) {
final RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null) {
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onChanged");
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onItemRangeRemoved:" + positionStart + ", itemcount:" + itemCount);
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
});
if (adapter instanceof CursorRecyclerAdapter && loadMoreView != null) {
((CursorRecyclerAdapter) adapter).removeFooter(loadMoreView);
}
}
}
I've put the code to initialize the loader in the onResume() method of each fragment:
int id = 100+Integer.valueOf(sort);
Loader l = getLoaderManager().getLoader(id);
Log.i("loader_callback_"+sort, "success loading volley "+l);
if(l == null) {
getLoaderManager().restartLoader(id, null, this);
}
My problem is that there seems to be some sort of race condition happening, that the currently viewed fragment's adapter seem to be updated twice, and sometimes thrice. The initial cursor fetched by the Fragment's Loader has 10 rows, sure, but after the update, most of the time it only has 7 of the 21 rows expected to be put in.
I thought all the ContentResolvers' operations are synchronous (can only be done one after another, not simultaneously). What's going on here?
EDIT: Should I just put the loader init code in the loadSuccess() callback?
EDIT2: I should note that these Fragments extend android.support.v4.app.Fragment, and I'm using the version 27.1.1 of the Support Library.

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.

microsoft band - sensor update rate

I am currently writing an Android app in Android Studio for the Microsoft band that will record data from the GSR, HR, and Skin Temp.
I have the data for GSR and Skin Temp. currently reading on the application but the rate that it is updated is very slow, especially for the Skin Temp. I was wondering if there was a way to make these sensors send data more frequently because the data I have now has too long of intervals for the purpose I am using it for. Here is my MainPage.java file.
public class MainPage extends Activity {
private BandClient client = null;
TextView tvGSR;
TextView tvHeartRate;
TextView tvTemperature;
Button updateTest;
private BandGsrEventListener mGsrEventListener = new BandGsrEventListener() {
#Override
public void onBandGsrChanged(final BandGsrEvent event) {
if (event != null) {
appendGSRToUI(String.format("%d kΩ\n", event.getResistance()));
}
}
};
private BandSkinTemperatureEventListener tempEventListener = new BandSkinTemperatureEventListener() {
#Override
public void onBandSkinTemperatureChanged(final BandSkinTemperatureEvent event) {
if (event != null) {
appendTempToUI(String.format("%.2f ºF\n", event.getTemperature()*1.800 + 32.00));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
tvGSR = (TextView) findViewById(R.id.tvGSR);
tvTemperature = (TextView) findViewById(R.id.tvTemperature);
updateTest = (Button) findViewById(R.id.updateTest);
updateTest.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tvGSR.setText("");
tvTemperature.setText("");
new GsrSubscriptionTask().execute(); // Put first (runs connection)
new TempSubscriptionTask().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
tvGSR.setText("");
tvTemperature.setText("");
}
#Override
protected void onPause() {
super.onPause();
if (client != null) {
try {
client.getSensorManager().unregisterGsrEventListener(mGsrEventListener);
client.getSensorManager().unregisterSkinTemperatureEventListener(tempEventListener);
} catch (BandIOException e) {
appendGSRToUI(e.getMessage());
appendTempToUI(e.getMessage());
}
}
}
#Override
protected void onDestroy() {
if (client != null) {
try {
client.disconnect().await();
} catch (InterruptedException e) {
// Do nothing as this is happening during destroy
} catch (BandException e) {
// Do nothing as this is happening during destroy
}
}
super.onDestroy();
}
private class GsrSubscriptionTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
if (getConnectedBandClient()) {
int hardwareVersion = Integer.parseInt(client.getHardwareVersion().await());
if (hardwareVersion >= 20) {
appendGSRToUI("Band is connected.\n");
client.getSensorManager().registerGsrEventListener(mGsrEventListener);
} else {
appendGSRToUI("The Gsr sensor is not supported with your Band version. Microsoft Band 2 is required.\n");
}
} else {
appendGSRToUI("Band isn't connected. Check Bluetooth.\n");
}
} catch (BandException e) {
String exceptionMessage="";
switch (e.getErrorType()) {
case UNSUPPORTED_SDK_VERSION_ERROR:
exceptionMessage = "SDK Version Outdated.\n";
break;
case SERVICE_ERROR:
exceptionMessage = "GSR Not Supported\n";
break;
default:
exceptionMessage = "Unknown error occured: " + e.getMessage() + "\n";
break;
}
appendGSRToUI(exceptionMessage);
} catch (Exception e) {
appendGSRToUI(e.getMessage());
}
return null;
}
}
private class TempSubscriptionTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
if (true) {
int hardwareVersion = Integer.parseInt(client.getHardwareVersion().await());
if (hardwareVersion >= 20) {
appendTempToUI("Band is connected.\n");
client.getSensorManager().registerSkinTemperatureEventListener(tempEventListener);
} else {
appendTempToUI("Temperature Not Supported.\n");
}
} else {
appendTempToUI("Band isn't connected. Check Bluetooth\n");
}
} catch (BandException e) {
String exceptionMessage="";
switch (e.getErrorType()) {
case UNSUPPORTED_SDK_VERSION_ERROR:
exceptionMessage = "SDK Version Outdated\n";
break;
case SERVICE_ERROR:
exceptionMessage = "Microsoft Health App Error\n";
break;
default:
exceptionMessage = "Unknown error occured: " + e.getMessage() + "\n";
break;
}
appendTempToUI(exceptionMessage);
} catch (Exception e) {
appendTempToUI(e.getMessage());
}
return null;
}
}
private void appendGSRToUI(final String string) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
tvGSR.setText(string);
}
});
}
private void appendTempToUI(final String string) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
tvTemperature.setText(string);
}
});
}
private boolean getConnectedBandClient() throws InterruptedException, BandException {
if (client == null) {
BandInfo[] devices = BandClientManager.getInstance().getPairedBands();
if (devices.length == 0) {
appendGSRToUI("Band isn't paired with your phone.\n");
return false;
}
client = BandClientManager.getInstance().create(getBaseContext(), devices[0]);
} else if (ConnectionState.CONNECTED == client.getConnectionState()) {
return true;
}
appendGSRToUI("Band is connecting...\n");
return ConnectionState.CONNECTED == client.connect().await();
}
}
There is currently no way to get data at a faster rate than provided by the Microsoft Band SDK.
Also, depending on what you want the data for, the skin temperature data might not be useful for you. Looking at the sensors you want to subscribe to, it looks like your application might be health related. But the skin temperature data contains the raw values from one of several thermometers inside of the band. And the band itself will generate some heat internally, so the data is unlikely to represent the skin temperature of the wearer exactly.

Downloading files with progressbar horizontal using parse

I have 37 files to download and I wanted to show my progress bar complete in 100%. how can I set that my last file will equal to 100%.. sorry for my english. thanks in advance..
querySound.findInBackground(new FindCallback<ParseObject>() {
#SuppressWarnings("unused")
#Override
public void done(List<ParseObject> objects, ParseException e) {
Log.d("OBJECTS MP3", ""+objects.toString());
if (objects == null) {
Toast.makeText(ParseStarterProjectActivity.this,"Something is Wrong!", Toast.LENGTH_LONG).show();
} else {
final int adder = 100 / objects.size();
for(ParseObject po : objects){
ParseFile sounds = (ParseFile) po.get("remindersSpanish");
final String filenames = sounds.getName().substring(37, sounds.getName().length());
Log.d("OBJECTS NAME", filenames);
sounds.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data,ParseException e) {
Log.d("OBJECTS DATA", ""+data);
if (e == null) {
saveMp3(filenames, data);
counter = counter + adder;
} else {
e.printStackTrace();
}
prgBar.setProgress(counter);
counterPrg.setText(counter+"/"+prgBar.getMax());
}
});

Categories

Resources