String.equals() always returns false? - android

I am trying to make a sign in page for an android app. My team leader has decided to make this with a webservice.
Whenever a uses logs in, a request is sent, with 3 possible responses:
0: Wrong Password
20: Wrong username
otherwise: a UUID
I am trying to validate the results given back by the webservice like this:
String resultString = result.toString();
if (resultString.equals("20")) {
Toast.makeText(getBaseContext(), "Het ingevulde emailadres klopt niet!", Toast.LENGTH_LONG).show();
return;
} else if (resultString.equals("0")) {
Toast.makeText(getBaseContext(), "Het ingevulde wachtwoord klopt niet!", Toast.LENGTH_LONG).show();
return;
} else {
Toast.makeText(getBaseContext(), "Debug, klopt", Toast.LENGTH_LONG).show();
return;
}
Seems like basic code to me. However, this code always shows the bottom statement, so it lets the first 2 pass as false.
For debugging purposes, am also returning the resultString to my console. (removed that line in the sample). There I can very obviously see that the result given back is in fact 20.
How can it be that such simple code does not do what I want it to do?
Thanks.

The code seems to be ok... Maybe a white space in the result?
Try trimming the resultString.
which es 20, result or resultString?
As an advice, it is usually better do "".equals(object) because otherwise, if the object is null it will throw NullpointerExceptcion
Regards

Response is not exactly the string you are comparing which are "0" and "20". but the response is
0: Wrong Password
20: Wrong username
otherwise: a UUID
if you want to compare the string then it should be
Options : 1
String resultString = result.toString();
if (resultString.equals("20: Wrong username")) {
// code
} else if (resultString.equals("0: Wrong Password")) {
// code
} else {
// code
}
Option : 2
Instead of eqauls you should use contains
String resultString = result.toString();
if (resultString.contains("20")) {
// code
} else if (resultString.contains("0")) {
// code
} else {
// code
}

I agree with all of the above - the code does look good.
Try using String.compareTo and look at the int returned value to check for hidden differences.
Also, try printing String.toCharArray + String.length to identify extra characters.

If you are taking the complete string returned from web service without extracting the code (0 or 20) then you need to replace 'equals' with 'contains'.

Related

Accessing a custom column in Parse.com user table returning me null

I am trying to retrieve a new column called "address" I created in Parse User in my android app. But it returns me nullPointerException error and returns me nothing although I filled the address in the table.
This link only shows the way to store your custom field in the user table but I need to retrieve what I stored there.
This is my code:
ParseUser pUser = ParseUser.getCurrentUser();
userAddress.setText(pUser.getString("address").toString());
I tried get("address") as well but still it returns me nothing. Is there something I'm missing here?
Alright, I found the answer on my own. It turns out that Parse caches the ParseUser.getCurrentUser() object locally and the reason I wasn't able to get the data from server was because I changed the data on server and the client cache wasn't updated.
I was able to fix this by fetching the ParseUser object from the server:
ParseUser.getCurrentUser().fetchInBackground();
and then after the object is retrieved from the server I was able to get the address field on my client.
You need to call it using a Query, then display it in a textView/editText. Try the following:
final ParseQuery<ParseObject> address = ParseQuery.getQuery("//Class Name");
address.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject reqAdd, ParseException e) {
if (address != null) {
Log.d("quizOne", "Got it");
//Retrieve Age
String //CreateNewString = reqAdd.getString("//Column name");
TextView //textView Name = (TextView) findViewById(R.id.//textView ID);
//textViewName.setText(//StringName);
Toast.makeText(getApplicationContext(),
"Successfully Recieved Address",
Toast.LENGTH_LONG).show();
} else {
Log.d("//EnterName", "//Enter Error Message");
Toast.makeText(getApplicationContext(),
"Can't receive address", Toast.LENGTH_LONG)
.show();
}
}
});
Short answer: that user probably just doesn't have an address set.
Long answer: your code snippet will throw exceptions often, and you should expect and handle those, or use tests to avoid throwing them.
Read this page: http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException
Key example/excerpt:
Object obj = null;
obj.toString(); // This statement will throw a NullPointerExcept
So pUser.getString("address") appears correct. But calling .toString() on the result requires you to be try/catching the exception. Maybe do
ParseUser pUser = ParseUser.getCurrentUser();
if (pUser.getString("address") != null) {
userAddress.setText(pUser.getString("address"));
}
BTW, I believe the error is "nullPointerException" fyi! :)

How to tell the if the City is incorrect in OpenWeatherMap api and in android

I am creating an app which will tell the weather condition of a city using the OpenWeatherMap.org api. In this app I let user to write a city name and the data will be fetched from the web. But what if the user entered wrong city.
For example if a user entered Lomdon instead of London.
What should I do in that case. The Api I am using is
"http://api.openweathermap.org/data/2.5/weather?q="+city name
Thanks in advance for the help, I am new to android development.
If the city is incorrect your API returns an error message. You can check it like this:
"http://api.openweathermap.org/data/2.5/weather?q=Lomdon"
try {
String msg = jsonObject.getString("message");
if (msg.equalsIgnoreCase("Error: Not found city")) {
Log.e("TAG", "City not found");
} else {
// Use the data
}
} catch (JSONException e) {
e.printStackTrace();
}
The reason I didn't use cod which looks like the return code, is that if the city is found cod is an int and if it's not found it's a string. Kind of misleading to design the JSON like that.

How to check if a incoming message in Android has the correctly Keyword

I am creating a op-out app. I am using Incomming SMS Broadcast Receiver, I need to check if the incoming message contains a specific keyword:
i.e
From: 656565451
msn: I want to op-out news
code .i.e - "this does not work"
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
//check if user message has this keywork
String keyWord_code = "op-out";
Pattern pattern = Pattern.compile("op-out");
if (pattern == keyWord_code ) {
//Do the op-out function here
}
else {
//Send message to user
}
I see that you are trying to use Regex?
Well, you can try something a little simpler first before going on to RegEx:
if( message.contains(keyWord_code) ){
// do something
}else{
// do something else
}
I don't know if you have problems with the receiver or what. If you just want to know if the msg body has the word "op-out" you just need the next code:
if(message.contains(keyWord_code) {
//...
} else {
//...
}

Android - Facebook API giving empty result for user cover photo

I'm trying to get the user's cover photo and show it at the top of a layout. I'm using AsyncTask to run the API call to Facebook. The code I'm using to get the Facebook data is
JSONObject json = null;
response = Utility.facebook.request("me?fields=cover");
json = Util.parseJson(response);
The exception that stops the thread comes from a json error on the next step because the returned json is empty, even though the request clears through. I can get a proper json using just "me" or "me/albums" or anything other than "me?fields=cover". When I comment out the last line, 'try' process finishes with no exceptions/errors.
Is there something wrong with the Facebook API or am I doing something wrong?
I personally prefer using FQL when dealing with User Profile. If you would like to give FQL a try, check the following piece of code. If you would like to stick to Graph API, see this answer: https://stackoverflow.com/a/12434640/450534
try {
String query = "SELECT pic_cover FROM user where uid = " + PUT_THE_USER_ID_HERE;
Bundle param = new Bundle();
param.putString("method", "fql.query");
param.putString("query", query);
String response = Utility.mFacebook.request(param);
JSONArray JAUser = new JSONArray(response);
for (int i = 0; i < JAUser.length(); i++) {
JSONObject JOUser = JAUser.getJSONObject(i);
// COVER PHOTO
if (JOUser.has("pic_cover")) {
String getCover = JOUser.getString("pic_cover");
if (getCover.equals("null")) {
String finalCover = null;
} else {
JSONObject JOCoverSource = JOUser.optJSONObject("pic_cover");
if (JOCoverSource.has("source")) {
String finalCover = JOCoverSource.getString("source");
} else {
String finalCover = null;
}
}
} else {
String finalCover = null;
}
}
} catch (Exception e) {
// TODO: handle exception
}
The above code already accounts for User's who do not have a Cover Photo set in their profiles and checks for its availability. With this code, you will have the URL to the Cover Photo and can then process it as you prefer.
NOTE: If you are fetching the logged in users cover photo, this piece of code SELECT pic_cover FROM user where uid = " + PUT_THE_USER_ID_HERE; can also be written as: SELECT pic_cover FROM user where uid = me()"; For the non-logged in user's cover photo, the above can be used as is.
Couple of things as a side note.
I use Fedor's Lazy Loading technique to load images in almost exclusively.
I recommend running the code block, mine or any other solution you choose, in an AsyncTask.
The reason for not getting any result can be found in the javadoc of request(String graphPath) method:
(...) this method blocks waiting for a network response, so do not
call it in a UI thread.
In your case, you should probably do the following synchronous call:
Bundle params = new Bundle();
params.putString("fields", "cover");
String result = Utility.facebook.request("me/", params);
Siddharth Lele is very correct in his answer, but I wanted to specify the actual reason for not getting any response in this case.
Note: Fetching Cover Photo using Facebook API and endpoint https://graph.facebook.com/me?fields=cover no longer works as on 20th Dec 2014.
It was supposed to give following response:
{
"cover": {
"cover_id": "10151008748223553",
"source": "http://sphotos-a.ak.fbcdn.net/hphotos-ak-ash4/s720x720/391237_10151008748223553_422785532_n.jpg",
"offset_y": 0
},
"id": "19292868552"
}
But now it just gives User's id:
{
"id": "19292868552"
}
Verified this using Graph Tool explorer v2.2 using me?fields=cover.

Ignore case for JSON-Keys in Android

i'm using in my android app native JSON-Library within Android OS. It works fine, but one thing makes me crazy.
If server interface changes and gives almost the same answer but the key notation will be a bit different (e.g. examplekeyofmyapp and exampleKeyOfMyApp) i have a problem.
Is there the way to ignore the case of the keys?
Or maybe anybody of you uses a workaround for these cases?
Thank you
if you had implemented your code like this
jsonobject.get(examplekeyofmyapp);
then modify your code. simply change the json String to lower case.
jsonString.toLowerCase(). thats it, all the upper case will get converted to lower case.
I faced the same problem and the best solution I found is to check if your key has an available value.
You still have to check all the possible cases you think you could have.
String TAG_URL_LOWER_CASE = "url";
String TAG_URL_UPPER_CASE = "URL";
String urlValue = "";
if (!obj.isNull(TAG_URL_LOWER_CASE)) {
urlValue = obj.getString(TAG_URL_LOWER_CASE);
} else if (!obj.isNull(TAG_URL_UPPER_CASE)) {
urlValue = obj.getString(TAG_URL_UPPER_CASE);
}
You will also avoid JsonException if your key has no value associated to you key.
Hope it helps
I know this is a few years old, but I thought my solution might help others:
String keyName = null;
for(Iterator<String> iter = jsonData.keys(); iter.hasNext();) {
String key = iter.next();
if (key.equalsIgnoreCase(jsonVar)) {
keyName = key;
break;
}
}
jsonData.get(keyName);
Obviously you can change the "get()" to other types of get methods
I have core methods that I use for each of the types that handles the error for you, e.g.
public static String getJSONString(JSONObject jsonData, String jsonVar) {
// start with a blank name
String keyName = null;
// loop through they keys to find the correct spelling
for(Iterator<String> iter = jsonData.keys(); iter.hasNext();) {
String key = iter.next();
if (key.equalsIgnoreCase(jsonVar)) {
keyName = key;
break;
}
}
// if the key isn't found, return a null
if (keyName == null) {
return keyName;
}
// need a try/catch around JSON stuff as the variable could be the wrong type or not exist
try {
return jsonData.getString(keyName);
}
catch (Exception e) {
// log the variable & the error
Log.w("getJSONString", "failed to getJSONstring "+jsonVar+" - "+e.toString());
// return an empty string because the "get" failed
return "";
}
}
Once you have all of the types made, it makes it easier to handle blank or missing values
I hope this helps somebody :)

Categories

Resources