ParseServer: not saving user info? - java

Basically, if a user is located near a certain event, I want to update an attribute called "pending" to "yes". I'm using a for loop to iterate through all the users (this code is just for a demo purposes, there aren't that many users), and check their distance to the specified event. If they are <= 7000 away, then I want to update "pending" to "yes." However, none of the attributes are actually saving?
I have attached my whole code but the relevant snippet occurs after this comment:// ****** NOTIFICATIONS FOR USERS WHO LIVE IN THE NEIGHBOURHOOD ***********
THINGS I KNOW:
the first log statement I put "numUsers" returns how many users are in the query, for me to validate that all of the users are actually queried. It returns 7, which is true! So that works.
IN the for loop, it's successfully printing each users user name at each iteration, so I know it's properly iterating through the users.
lastly, at u.SaveInBackground(....) it's successfully printing out each users name, and "yes" if they are within the distance I specified, or "null" if not.
but when I check the server none of this information is actually stored?
And outside of this method if I try to get any user's "pending" attribute, it will tell me it's null.
I've been stuck on this for hours now!
public void onButtonClickDecision(final View view) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("IncidentReports");
query.whereEqualTo("reference", intent.getStringExtra("reference"));
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size()>0) {
//if we clicked, decline -> update status to decline
if (view.getId() == R.id.decline) {
objects.get(0).put("status", "declined");
}
// if we clicked approve -> update status to approve
else if (view.getId() == R.id.approve) {
// update status
objects.get(0).put("status", "approved");
// ****** NOTIFICATIONS FOR USERS WHO LIVE IN THE NEIGHBOURHOOD ***********
ParseQuery<ParseUser> query3 = ParseUser.getQuery();
query3.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
Log.i("numUsers", Integer.toString(users.size()));
if ( e== null && users.size()>0) {
// COMPARE EACH USERS ADDRESS
for (final ParseUser u : users) {
Log.i("user name", u.getUsername());
String address = u.getString("address");
try {
// sets up users home as a Location
List<Address> list = geocoder.getFromLocationName(address, 1);
Address add = list.get(0);
Location home = new Location(LocationManager.GPS_PROVIDER);
home.setLatitude(add.getLatitude());
home.setLongitude(add.getLongitude());
// check if user is located in incident neighbourhood
if (home.distanceTo(incidentLoc) <= 7000) {
u.put("pending", "yes");
}
} catch (IOException ex) {
Log.i("ApprovedCheckingUsers", "failed");
System.out.println(ex.getMessage());
}
u.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.i("Updated:", u.getUsername() + "," + u.getString("pending"));
}
});
}
}
}
});
}
// NOTIFY USER WHO POSTED
objects.get(0).put("notified", "false");
objects.get(0).put("reviewedby", ParseUser.getCurrentUser().getString("username"));
objects.get(0).saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
System.out.println("Saving status updates");
currentStatus.setText(objects.get(0).getString("status"));
Toast.makeText(ViewIndividualReport.this, "Status successfuly changed", Toast.LENGTH_SHORT).show();
} else {
System.out.println("Failed to save");
Toast.makeText(ViewIndividualReport.this, "Could not update status at this time. Try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
});
}

Related

Printing a message that element is not present in catch block, selenium

This is my Feature file:
#Done #ProdSmoke #KioskSmoke
Scenario Outline: Add Items to the Cart and click Cancel
Given Open the application on Tablet device
When Click on the KeyInItem button
Then Enter Item Number "<upc>"
And Click Cancel
And Item "not added" in the cart
Examples:
| upctype | upc|
| upca | 8 |
This is my stepdef file:
#And("^Item \"([^\"]*)\" in the cart$")
public void itemAddedInTheCart(String action) throws Exception {
addItem.verify_itemadded(action);
}
And this is my function verify_itemadded(action):
public void verify_itemadded(String action) throws Exception {
try {
if (action.equals("added") && element("ItemVerify").isDisplayed()) {
Assert.assertTrue(element("ItemVerify").isDisplayed());
logger.info("Item Added");
}
}
catch (Exception ex)
{
if(action.equals("not added") && !element("ItemVerify").isDisplayed())
logger.info("Item not added");
}
}
Even though the test is passing, I am unable to get the message "item not added".
Any ideas?
You need to update the code as below. Let me know if you face any issue.
try
{
boolean isItemVerified = element("ItemVerify").isDisplayed());
if (action.equals("added") && isItemVerified )
{
logger.info("Item Added");
}
Assert.assertTrue(isItemVerified);
}
catch(AssertionError ae)
{
logger.info("Item not added");
}

why am i getting an error on .verifyCredentials()

I want to get the data using twitter's fabric api but whenever i tend to verify credentials and use a callback it shows an error , specifically ,"The arguments differ in length"
void getUserData() {
Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
#Override
public void failure(TwitterException e) {
}
#Override
public void success(Result<User> userResult) {
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.d("imageurl", user.profileImageUrl);
Log.d("name", user.name);
Log.d("email",user.email);
Log.d("des", user.description);
Log.d("followers ", String.valueOf(user.followersCount));
Log.d("createdAt", user.createdAt);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
If you check the fabric documentation, it shows two version of the method, however when I tried to open the source code in Android Studio but it had only the version without the callback.
You can solve the isssue as follows:
//Getting the account service of the user logged in
Call<User> call = Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false);
call.enqueue(new Callback<User>() {
#Override
public void failure(TwitterException e) {
//If any error occurs handle it here
}
#Override
public void success(Result<User> userResult) {
//If it succeeds creating a User object from userResult.data
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.d("imageurl", user.profileImageUrl);
Log.d("name", user.name);
Log.d("email",user.email);
Log.d("des", user.description);
Log.d("followers ", String.valueOf(user.followersCount));
Log.d("createdAt", user.createdAt);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Source
Documentation
Just change the twitter dependency in your Build.Gradle
from
compile('com.twitter.sdk.android:twitter:2.0.0#aar') {
transitive = true;
}
to
compile('com.twitter.sdk.android:twitter:1.11.0#aar') {
transitive = true;
}
The new version of the .verifyCredentials() method doesn't accept a callback hence your error.

Parse Anonymous Utils: How to only create one user?

I have a quick question. I'm trying to enable automatic user creation in my app, so that when you open it for the first time, one and only one user is created. I read the User docs thoroughly, and found that Parse persists the user session on disk, and that once you save an object to that user, that user is saved on the cloud. However, I've noticed two problems with this:
1) When I save an object and create a pointer to the Owner User, the user object does not exist on the cloud.
2) If I check whether the current user is linked using ParseAnonUtils.isLinked(), this sometimes returns true, as in the current user is linked, or false, as in the current user is not linked, for the same exact ParseUser that was cached on session.
Here is the method I'm using to create and determine the user:
private void getUser() {
if (!ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) {
Log.v("Miles", "new user");
ParseAnonymousUtils.logIn(new LogInCallback() {
#Override
public void done(final ParseUser user, ParseException e) {
if (e == null) {
user.setUsername(UUID.randomUUID().toString());
user.setPassword(UUID.randomUUID().toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.v("Miles", "user saved");
} else {
Log.v("Miles", "user not saved " + String.valueOf(e.getCode()));
}
}
});
} else {
Log.v("Miles", "signup fail " + String.valueOf(e.getCode()));
}
}
});
} else {
Log.v("Miles", "anon login fail " + String.valueOf(e.getCode()));
}
}
});
}
}
Help would be greatly appreciated.

Android parse.com delete object from array

You can see what i am talking about in this picture
I have an array called "statusLikers" under a class called "Status". I am trying to create a facebook/instagram like/unlike functionality on button click.
Now, before i move on from where i am, i am trying to figure out how to remove users from the array.
I know how to add to th array but i dont know how to delete from it.
The way i am going about it is like this
List<Object> likesPpl = status.getList("statusLikers");
JSONObject myObject = new JSONObject();
try {
myObject.put("statusLikers", currUser.getUsername());
} catch (JSONException e1) {
e1.printStackTrace();
}
likesPpl.removeAll(Arrays.asList(myObject));
but it does not seem to work, first i want to learn to remove items from the array before i create the if statements.
to remove data from an array of a Parse Tab
List<String> ary_users = new ArrayList<String>();
ParseQuery<ParseObject> queryPart1 = ParseQuery.getQuery("Channel");
queryPart1.whereEqualTo("objectId",channel_id);
queryPart1.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("usersArray")!=null) {
ary_users = p.getList("usersArray");
}
else
{
ary_users = null;
}
if (ary_users!=null) {
if (ary_users.contains(frnd_objid)) {
ary_users.remove(frnd_objid);
p.put("usersArray",ary_users);
p.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException arg0) {
Toast.makeText(activity,frnd_name+ "is successfully removed in the channel"+channel_name,Toast.LENGTH_LONG).show();
}
});
}
}
}
}
}
});
}
Here "usersArray" is an Array of table "Channel" .And I am removing "frnd_objid" from the "usersArray"

Problem in updating database (jdbc)

I'm developing an application in which I dynamically create forms by reading data from a database. What I want is the user to be able to update or delete the database by using the corresponding button in the database(I am allowing user to connect to almost any database so I have no idea about the type of columns, or whether an update will be supported). I've successfully created code to insert data in any database but I am struggling to figure out a way to update and delete records. This is the code snippet for the class for updating/deleting :
/* tflist contains the list of text fields(I used setName() to set their names to
the column names in the table) which I created dynamically
for allowing the user to enter new values and they already hold the
current values,panel contains all the labels and generated gui which is basically
column name in a label and text field,
e.g. Roll no(label) : 9(in a text field),
tablename has the name of the table,
jtable is the table on which event occurred
(you click on a row of table, and a form appears that gives you the option to
update or delete something),and rowno contains the row number of jtable on which
the user clicked */
private void update_buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String querypart2=" WHERE ";
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
if(tf.getText()!=null&&!tf.getText().equals(""))
{
if(jtable.getValueAt(rowno, i)==null||jtable.getValueAt(rowno, i).equals(""))
{
querypart2=querypart2+"\""+tf.getName()+"\" IS NULL";
}
else
{
querypart2=querypart2+"\""+tf.getName()+"\"='"+jtable.getValueAt(rowno,i)+"'";
}
querypart2=querypart2+" AND ";
}
}
if(querypart2.equals(" WHERE "))
{
querypart2="";
}
else
{
querypart2=querypart2.substring(0, querypart2.length()-5);
}
try {
Statement statement = Aw_supersensible.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=statement.executeQuery("SELECT * FROM \""+tablename+"\""+querypart2);
rs.absolute(1);
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
rs.updateObject(tf.getName(), tf.getText());
}
Aw_supersensible.conn.commit();
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
jtable.setValueAt( tf.getText(),rowno,i);
rs.updateRow();
}
central_window.cw.setEnabled(true);
dispose();
}
catch(final Exception e)
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new errorWindow(new javax.swing.JFrame(),e.toString()).setVisible(true);
}
});
}
}
private void delete_buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String querypart2=" WHERE ";
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
if(tf.getText()!=null&&!tf.getText().equals(""))
{
if(jtable.getValueAt(rowno, i)==null||jtable.getValueAt(rowno, i).equals(""))
{
querypart2=querypart2+"\""+tf.getName()+"\" IS NULL";
}
else
{
querypart2=querypart2+"\""+tf.getName()+"\"='"+jtable.getValueAt(rowno,i)+"'";
}
querypart2=querypart2+" AND ";
}
}
if(querypart2.equals(" WHERE "))
{
querypart2="";
}
else
{
querypart2=querypart2.substring(0, querypart2.length()-5);
}
try {
Statement statement = Aw_supersensible.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=statement.executeQuery("SELECT * FROM \""+tablename+"\""+querypart2);
rs.absolute(1);
rs.deleteRow();
((DefaultTableModel)jtable.getModel()).removeRow(rowno);
Aw_supersensible.conn.commit();
central_window.cw.setEnabled(true);
dispose();
}
catch(final Exception e)
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new errorWindow(new javax.swing.JFrame(),e.toString()).setVisible(true);
}
});
}
}
This is some pseudo code for your delete operation, to show you what I think a 'modular' approach would look like.
I am not an experienced developer (in fact I am not a developer), so there may be better ways.
private void delete_buttonActionPerformed(java.awt.event.ActionEvent evt) {
String tableName;
List<String> whereProperties;
List<String> whereValues;
// get your table name
// get your properties and values from the GUI in such a way that the property in whereProperties.get(n) corresponds to the value in whereValues(n)
// have a function in some class (I've called it SQL) that can take the following parameters and performs the delete operation.
SQL.delete(tableName, whereProperties, whereValues);
}

Categories