What is going in in this IF-ELSE statement? - java

I'm really stuck here and it simply doesn't make any sense to me. Here's what's going on: I have an AsyncTask sending data to a server and retrieving a String response back. The String response can be two things: it can be a message telling the user that he/she is logged in if the credentials entered are correct or it can be a "FALSE" string which I use to display a notification toast to the user and take him/her back to the main activity to retry logging in.
Here is the code snippet:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String cr = "Placeholder";
Credential cred = new Credential();
try { cr = cred.execute().get(); }
catch (InterruptedException e) { e.printStackTrace(); }
catch (ExecutionException e) { e.printStackTrace(); }
//tv.setText(cr);
if (cr == "FALSE") {
Log.d("Checking in false", cr);
Toast.makeText(Credentials.this, "Cannot log in: wrong username or password", Toast.LENGTH_LONG).show();
startActivity(new Intent(Credentials.this, MainActivity.class));
} else if (cr != "FALSE") {
Log.d("Checking in true", cr);
Intent intent = new Intent(Credentials.this, ProfileActivity.class);
intent.putExtra(INTENT_DATA, cr);
startActivity(intent);
}
}
});
By using the Log.d() static method and looking at the LogCat, I'm sure that the returned value is indeed FALSE if the credentials are wrong (again, it's not a boolean value, just String in all Caps). The funny thing is that the code that gets executed is the "else if" part of the snippet I have posted but it actually logs that the returned string value is FALSE! Which means (at least to me) that it should have executed the first "if" condition (that is, if (cr == "FALSE") { } ). But no, it keeps executing the "else if" part.
Any ideas?

Use equals for string comparisons.
I.E:
WRONG:
if (cr == "FALSE") {
CORRECT:
if (cr.equals("FALSE")) {

Use
if (cr.contentEquals("false") {
//your code
} else {
//your code
}

Related

unable to use utility method to check if multiple edittext are empty with custom correct edittext id in output toast

Thanks for reading this
I am having difficulty a utility method meant to read all 20 edittexts and check if they are empty and return custom toast messages for instances of each editText being empty
The utility method is called inside my onclicklistener as seen below. Its called checkEmpty
btnRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checkEmpty(etPickupLocation, getActivity())) return;
}
});
see checkempty below
public static boolean checkEmpty(EditText myEditText, Context context) {
String editTextIdInt= String.valueOf(myEditText.getId());
Log.d(TAG, "checkEmpty: editTextIdInt>> "+ myEditText.getId());
String editTextIdStr = context.getString(Integer.parseInt(editTextIdInt));
Log.d(TAG, "checkEmpty: editTextIdStr >>"+ editTextIdStr);
if (myEditText.getText().toString().trim().length() == 0) {
Toast.makeText(context, editTextIdStr+" is missing.", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
The issue is : I want to return the id of the editTextResource (etPickupLocation) as the second log output but instead i keep getting false
log output
2020-09-20 10:33:21.556 11445-11445/com.packagename.clasname D/UTILITYLOG: checkEmpty: editTextIdInt>> 2131230927
2020-09-20 10:33:21.556 11445-11445/com.packagename.clasname D/UTILITYLOG: checkEmpty: editTextIdStr >>false
All I want is to get the id of the editext bein passed into the method so i can return the right toast method
or is there a better approach to doing this?
Help me out guys
Thanks so much to Mike Ms clarification
I decided to use this approach instead since I cannot use an EditText's ID to retrieve a string resource.
public static boolean checkEmpty(EditText myEditText, Context context) {
Log.d(TAG, "checkEmpty: Obj" + myEditText.toString());
String myObj = myEditText.toString();
String OutputText="";
if (myObj.contains("etPickupLocation")) {
OutputText = "Sender Address";
}else if (myObj.contains("etWhereTo")) {
OutputText = "Recipient Address";
} else {
Log.d(TAG, "checkEmpty: >> DOING NOTHING");
OutputText = "Something";
}
if (myEditText.getText().toString().trim().length() == 0) {
Toast.makeText(context, "Enter "+OutputText+"." , Toast.LENGTH_SHORT).show();
return true;
}
return false;
}

Checking for in-app purchases

Following instructions from: https://developer.android.com/training/in-app-billing/purchase-iab-products.html under Query Purchased Items, I am checking for purchased items.
My code looks like this:
private void lookForPurchases() {
IabHelper.QueryInventoryFinishedListener lookForPurchasesListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
Log.e(TAG, "Error checking for purchases:" + result.toString());
}
else {
Log.d(TAG, "Processing purchases." + inventory.toString());
if(inventory.hasPurchase(SKU_LEXCOINS_100)){
Purchase purchase = inventory.getPurchase(SKU_LEXCOINS_100);
consumeCoinPurchase(purchase);
}
if(inventory.hasPurchase(SKU_LEXCOINS_550)){
Purchase purchase = inventory.getPurchase(SKU_LEXCOINS_550);
consumeCoinPurchase(purchase);
}
if(inventory.hasPurchase(SKU_LEXCOINS_1200)){
Purchase purchase = inventory.getPurchase(SKU_LEXCOINS_1200);
consumeCoinPurchase(purchase);
}
}
}
};
Log.i(TAG, "Looking for purchases");
if(inAppBillingHelper == null) {
Log.e(TAG, "Null preventing query inventory");
} else {
try {
inAppBillingHelper.queryInventoryAsync(lookForPurchasesListener);
} catch (IabHelper.IabAsyncInProgressException ex) {
Log.e(TAG, "Error retrieving purchases.", ex);
}
}
}
In the log, though, the last thing I get is "Looking for purchases" with nothing following. It looks like I should get something on any branch, so, does anyone see what I'm doing wrong?
No errors or anything, it just never seems to come back.
The problem was on the line handler.post deep in IabHelper (Google Code) where it was executing my callback I was passing in. The handler.post was getting called, buy my callback never was. I'm not sure how that happened.
I replaced the handler.post with a AsyncTask and posted the call of my callback in the onPostExecute method to get it run on the UI thread. This appears to have solved my problem.

onPartialResult is always one value, even after I change the keyword?

hypothesis.getHypstr() is always one value, even after I change the keyword!
I am using pocketsphinx to do speech recognition, and I let the user change what to listen for. This value is stored in my shared preferences. My problem is that hypothesis.getHypstr() is only called when the previous keyword is spoken.
For example:
If it is set to default keyword (oranges and rainbows), then the recognition works fine. But, if the user changes it to "hello computer" then the onPartialResult method still only gets called when the user says hello, and hypothesis.getHypstr() is still oranges and rainbows.
onCreate:
try {
Assets assets = new Assets(MyService.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
Log.v(TAG, "SET UP DIRECTORIES STARTING LISTENING!");
mSpeechRecognizer.startListening("usersKeyword");
} catch (IOException e) {
e.printStackTrace();
Log.v(TAG, e.toString());
}
setupRecognizer()
public void setupRecognizer(File sphinxDir) {
try {
mSpeechRecognizer = defaultSetup()
.setAcousticModel(new File(sphinxDir, "en-us-ptm"))
.setDictionary(new File(sphinxDir, "cmudict-en-us.dict"))
.setBoolean("-allphone_ci", true)
.setKeywordThreshold(1e-40f)
.getRecognizer();
} catch (IOException e) {
e.printStackTrace();
}
mSpeechRecognizer.addListener(this);
mSpeechRecognizer.addKeyphraseSearch("usersKeyword", keyword.getString("keyword", "oranges and rainbows"));
}
onPartialResult:
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null) { //no one spoke
return;
}
String text = hypothesis.getHypstr();
Log.v(TAG, "TEXT: " + text + "hypothesis.getHypstr: " + hypothesis.getHypstr());
if (text.equals(keyword.getString("keyword", "oranges and rainbows"))) { //Only happens when text is oranges and rainbows, even after changing preference value!!!
Log.v(TAG, "Heard user keyword!");
mSpeechRecognizer.cancel();
mSpeechRecognizer.startListening("usersKeyword");
}
}
Why is hypothesis.getHypstr() always only one value, even after I change the value of the addKeyphraseSearch?
Thanks,
Ruchir
EDIT:
I actually stop and start the service every time the user changes their input, and so onCreate() is called every time the user changes their data.
FULL CODE:
https://gist.github.com/anonymous/47efc9c1ca08d808e0be
You do not need to destroy the service, you create it once with onCreate.
You can set the command in onStartCommand:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
recognizer.cancel();
recognizer.addKeyphraseSearch("usersKeywords", intent.getStringExtra("keyword"););
recognizer.startListening("usersKeywords");
}
From the other class which is a user of the service you start service with intent:
Intent i = new Intent(this, MyService);
i.putExtra("keyword", "hello");
startService(i);
For more details read documentation
You need to call mSpeechRecognizer.addKeyphraseSearch() every time you want to change the key phrase.

Parse: Duplicate records for the a single saveInBackground Call

I have a single incident where a complete duplicate of a entry was made into the database (the same user comment appeared twice). They had different object IDs but were otherwise the exact same. It was slower than usual to finish the posting and only happened once out of dozens of comments, so I want to say it was a Parse issue during the saveInBackground call. Even so, I expect a service like Parse to be a little more robust. As my first time working with Android though, I also can't be sure nothing is wrong on my end. Any help? Also just any criticisms? This is the method called when the user hits a comment submission button:
private void submitComment() {
String text = commentText.getText().toString().trim();
Intent intent = getIntent();
String ID = intent.getStringExtra("imageID");
String parentID = intent.getStringExtra("parent");
// Set up a progress dialog
final ProgressDialog loadingDialog = new ProgressDialog(CommentSubmitActivity.this);
loadingDialog.setMessage(getString(R.string.publishing_comment));
loadingDialog.show();
Comment comment = new Comment();
comment.setText(text);
comment.setUser((ParseUser.getCurrentUser()));
if (ID.equals("#child")) {
comment.setParent(parentID);
comment.setImage("#child");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");
query.getInBackground(parentID, new GetCallback<ParseObject>() {
public void done(ParseObject parentComment, ParseException e) {
if (e == null) {
int numChild = parentComment.getInt("numChild");
parentComment.put("numChild", ++numChild);
parentComment.saveInBackground();
} else {
Log.d("numChild: ", "error");
}
}
});
} else {
comment.setImage(ID);
comment.put("numChild", 0);
ParseQuery<ParseObject> query = ParseQuery.getQuery("ImageUpload");
query.getInBackground(ID, new GetCallback<ParseObject>() {
public void done(ParseObject image, ParseException e) {
if (e == null) {
int numComments = image.getInt("numComments");
image.put("numComments", ++numComments);
image.saveInBackground();
} else {
Log.d("numComments: ", "error");
}
}
});
}
comment.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
loadingDialog.dismiss();
finish();
}
}
});
}
I encountered similar problem like yours.
I created an app where user can create account and add photo to it and list of objects (friends in my case).
Once when I was testing it user was created twice.
I went through my code and my my suspicions are connected with async calls.
I see that you use asynchronous parse api in you application so no fragment of code is waiting for response and blocking the rest of operations.
You cannot control when parse server will response.
What I did I just put all synchronous requests in my custom async code (AsyncTask in Android).
Hope that my answer somehow meeets your expectations.

Help with password validation

I created a login application. But when I input a wrong password, the app won't give me any notification that the password was incorrect and it's because I didn't even put any codes for it. I don't know what to put in order to achieve it. I'm a newbie here. Please help.
This is my code:
public void onClick(View v)
{
EditText passwordEditText = (EditText) findViewById(R.id.currentPass);
SharedPreferences prefs = this.getApplicationContext().getSharedPreferences("prefs_file",MODE_PRIVATE);
String password = prefs.getString("password","");
if("".equals(password))
{
Editor edit = prefs.edit();
edit.putString("password",passwordEditText.getText().toString());
edit.commit();
StartMain();
}
else
{
if(passwordEditText.getText().toString().equals(password))
{
StartMain();
}
}
}
You probably want an else condition on your inner if statement:
if(passwordEditText.getText().toString().equals(password)) //checking if they put the right password?
{
StartMain(); //I assume this is starting the application
}
else
{
//Tell them the password was wrong.
}
The simplest think would be to show a Toast notification. You could do that in the else branch of the second (nested) if in your code above.
Hello schadi:
i think you problem is this:EditText catch the click event as first as you click it that you should want to input some password.so,your code should always running at '"".equals(password)' statement.
you may can use TextWatcher or something else to do your work.
Chinese guy,English is poor,i hope you can understand what i am saying :)
I suggest using a toast to notify the user. Like this:
else
{
if(passwordEditText.getText().toString().equals(password))
{
StartMain();
}
} else {
Toast.makeText(v.getContext(), "Wrong password!", Toast.LENGTH_LONG).show();
}

Categories

Resources