Intent not working with if operator Android - java

I try when it displays a message when I press a button to redirect me to a page, but it doesn't work. When successful, the message is displayed but does not forward me.
private void registerUser() {
try {
Account account = new Account();
account.setpAddress(edt_adress.getText().toString());
account.setpBloodGroup(edt_blood.getSelectedItem().toString());
account.setpFirstName(edt_first.getText().toString());
account.setpMidName(edt_mid.getText().toString());
account.setpFamilyName(edt_fam.getText().toString());
account.setpGender(edt_gender.getSelectedItem().toString());
account.setpPhone(edt_phone.getText().toString());
account.setpEgn(edt_egn.getText().toString());
account.setuPassword(edt_password.getText().toString());
account.setuUsername(edt_username.getText().toString());
INodeJS accountservice = RetrofitClient.getInstance().create(INodeJS.class);
Call call = accountservice.create(account);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
Account result = (Account) response.body();
Toast.makeText(getApplicationContext(), result.getNotes(), Toast.LENGTH_LONG).show();
if (result.getNotes().equals("Success")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
// startActivity(intent);
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(), getString(R.string.createfield), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

looks like result.getNotes().equals("Success") isnt true, are you shure it should be? equals is case-sensitive so "success" doesn't equal "Success" and also " Success " - note whitespaces
maybe you can try with this statement:
result.getNotes().toLowerCase(Locale.getDefault()).trim().equals("success")
toLowerCase will make all your letters small caps and trim will remove all whitespaces at beggining and end of String
also there is equalsIgnoreCase method so it may also looks like below:
result.getNotes().trim().equalsIgnoreCase("success")

Related

Why negativeButton is "invisible"?

I'm trying to build an app with biometric authentication (Fingerprint) and I'm having some troubles with the negative button.
The button works, but for some reason is completely invisible.
This is how the app shows
And this is how it sees when you prees the button. As you can see, it exist, but i don't know how to make it visible
I'm using BiometricPrompt and BiometricManager in Java.
Edit: It seems that the button shows normally in any other phone that isn't mine
I'm using a Xiaomi Redmi Note 8.
However this is the code that I'm using:
private void initViews()
{
biometricManager = BiometricManager.from(this);
passwordEditText=findViewById(R.id.passwordText);
loginButton=findViewById(R.id.loginButton);
switch (biometricManager.canAuthenticate()) {
case BiometricManager.BIOMETRIC_SUCCESS:
Log.d("MY_APP_TAG", "App can authenticate using biometrics.");
break;
case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
Log.e("MY_APP_TAG", "No biometric features available on this device.");
break;
case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
Log.e("MY_APP_TAG", "Biometric features are currently unavailable.");
break;
case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
Log.e("MY_APP_TAG", "The user hasn't associated " +
"any biometric credentials with their account.");
break;
}
executor = ContextCompat.getMainExecutor(this);
biometricPrompt = new BiometricPrompt(EnterYourPassActivity.this,
executor, new BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode,
#NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
if(errString.equals("Use account password"))
{
passwordEditText.setVisibility(View.VISIBLE);
}
else
{
Log.d("MY_APP_TAG",""+errString);
Toast.makeText(getApplicationContext(),
"Authentication error: " + errString, Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onAuthenticationSucceeded(
#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Toast.makeText(getApplicationContext(),
"Authentication succeeded!", Toast.LENGTH_SHORT).show();
Intent seeingFiles = new Intent(EnterYourPassActivity.this, SeeingFilesActivity.class);
startActivity(seeingFiles);
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
Toast.makeText(getApplicationContext(), "Authentication failed",
Toast.LENGTH_SHORT)
.show();
}
});
promptInfo = new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login for my app")
.setSubtitle("Log in using your biometric credential")
.setNegativeButtonText("Use account password")
.build();
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
biometricPrompt.authenticate(promptInfo);
}
});
}
Try to change negativeButton text in this way:
Important - put string into resources:
<string name="negative_button_text"><![CDATA[<font color=\'#48a134\'>Your text at given color</font>]]></string>
As you can see, you can set text color in hex.
Now put negativeText into BiometricPrompt as follows:
val negativeButtonText = getString(R.string.negative_button_text)
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("title")
.setDescription("description")
.setNegativeButtonText(fromHtml(negativeButtonText))
.build()
fun fromHtml(html: String): Spanned {
return HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)
}
In given example negativeText is green and prompt looks like THIS.

Correctly check if user is logged in. Android

I have my login setup like this, I use retrofit to authenticate from the server and I'm using a token api authentication:
In the MainActivity.java method onCreate
apiInterface = ApiClient.getClient().create(ApiInterface.class);
User user = SharedPreferencesHelper.getUser(MainActivity.this);
if (user.getToken() == null) {
Intent login = new Intent(MainActivity.this, LoginActivity.class);
startActivity(login);
} else {
setContentView(R.layout.activity_main);
buildMain();
}
In the LoginActivity.java method on create (I'll summarize, the code is quite long)
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get login ingo
Login login = new Login(scardI, passwordI, device_name);
Call<User> call = apiInterface.LoginUser(login);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
User user = response.body();
//save user info into SharedPreferences
SharedPreferencesHelper.setUser(LoginActivity.this, user);
//check if user saved correctly by getting the user token
if (SharedPreferencesHelper.getUserToken(LoginActivity.this) != null) {
finish();
}
} else {
//show error message
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
//show error message
}
});
}
});
I'm having an issue, after the user logs in a blank page is displayed instead of the activity_main.xml however when I close the app and reopen it it takes me straight to the activity_main.xml as expected. Is there a reason that after the login it doesn't take me to the activity_main like expected.
An intent to MainActivity.java is missing on success. A blank screen is displayed because finish() is called.
if (response.isSuccessful()) {
User user = response.body();
SharedPreferencesHelper.setUser(LoginActivity.this, user);
if (SharedPreferencesHelper.getUserToken(LoginActivity.this) != null){
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(i);
}
}

Paytm Integration in my application

I create sandbox account in paytm.I am using github code and pass merchant id and all parameter to paytm.please check my below code
public void onStartTransaction(View view) {
PaytmPGService Service = PaytmPGService.getStagingService();
Map<String, String> paramMap = new HashMap<String, String>();
// these are mandatory parameters
paramMap.put("ORDER_ID", ((EditText) findViewById(R.id.order_id)).getText().toString());
paramMap.put("MID", ((EditText) findViewById(R.id.merchant_id)).getText().toString());
paramMap.put("CUST_ID", ((EditText) findViewById(R.id.customer_id)).getText().toString());
paramMap.put("CHANNEL_ID", ((EditText) findViewById(R.id.channel_id)).getText().toString());
paramMap.put("INDUSTRY_TYPE_ID", ((EditText) findViewById(R.id.industry_type_id)).getText().toString());
paramMap.put("WEBSITE", ((EditText) findViewById(R.id.website)).getText().toString());
paramMap.put("TXN_AMOUNT", ((EditText) findViewById(R.id.transaction_amount)).getText().toString());
paramMap.put("THEME", ((EditText) findViewById(R.id.theme)).getText().toString());
paramMap.put("EMAIL", ((EditText) findViewById(R.id.cust_email_id)).getText().toString());
paramMap.put("MOBILE_NO", ((EditText) findViewById(R.id.cust_mobile_no)).getText().toString());
PaytmOrder Order = new PaytmOrder(paramMap);
PaytmMerchant Merchant = new PaytmMerchant(
"https://pguat.paytm.com/paytmchecksum/paytmCheckSumGenerator.jsp",
"https://pguat.paytm.com/paytmchecksum/paytmCheckSumVerify.jsp");
Service.initialize(Order, Merchant, null);
Service.startPaymentTransaction(this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
Toast.makeText(getApplicationContext(), "Ui/Webview error occured.", Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionSuccess(Bundle inResponse) {
Log.d("LOG", "Payment Transaction is successful " + inResponse);
Toast.makeText(getApplicationContext(), "Payment Transaction is successful ", Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionFailure(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed " + inErrorMessage);
Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
recreate();
}
#Override
public void networkNotAvailable() {
Toast.makeText(getBaseContext(), "No Internet connection.", Toast.LENGTH_LONG).show();
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
Toast.makeText(getBaseContext(), "Client Authentication Failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
});
}
below attachment I pass parameter to PaytmPGService.please check attachment
after click on confirm order I got this screen please check attachment
so please check and help me...
there is also some server side implementation, make sure your chechksum is generated from server.
Several things to take care:
Confirm you supply all required arguments for checksum generation to your server.
Make sure when paytm hits your server url, it generates same checksum as it was returned back to your app.
Your credentials are configured in their staging server while testing on staging, and same on their production server.
Make sure from their side if they have enabled all required options like cc/dc etc.

Why Retrofit can't resolve No connection - Check internet connection on Android?

Hello guys I have one specific problem. I'm using retrofit library for all of my network calls. And I have one method to send points to another user and if any error occurs, the server will return me code 400 and string alongside it that I will have to show to user. This thing is working I created it like this ( NetworkSDK is sending a body with params and expect to recieve an error status string if it occurs) so logically I am processing my errors in onResponse method (if Networksdk recieve an object with error string) and if onFailure occurs there is no error. But now I have a bigger problem. If there is no connection at all, if user turns off internet in that fragment it will again go to onFailure and show message that points are sent. Ordinary I would do that via status code if status code is 200 than it's okey but for some reasons I can't get any status code via response.code() command. Here is the code :
#Override
public void onClick(View v) {
try {
final String cardNo;
String amountstring = bodovi.getText().toString();
final Integer amount = Integer.valueOf(amountstring);
cardNo = brojkartice.getText().toString();
Log.d("Broj bodova:", amount.toString());
Log.d("Broj kartice:", cardNo);
final SendPoints Posiljka = new SendPoints();
Posiljka.setAmount(amount);
Posiljka.setCardNumber(cardNo);
NetworkSDK.getInstance().SendPoints(Posiljka, new Callback<SendPointsResponse>() {
#Override
public void onResponse(Call<SendPointsResponse> call, Response<SendPointsResponse> response) {
Log.d("Response code:", "" + response.code());
Log.d("Kartica", Posiljka.getCardNumber());
Log.d("Broj bodova", Posiljka.getAmount().toString());
try {
SendPointsResponse error = (new Gson()).fromJson(response.errorBody().string(), SendPointsResponse.class);
if (error.getCode().equals("-1"))
Toast.makeText(getActivity(), "Neuspješno slanje bodoava. Neispravni ulazni podaci.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-2"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnički podaci nisu popunjeni.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-3"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ima rezervisanu nagradu.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-4"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. U toku jednog mjeseca bodove je moguće poslati maksimalno dva puta.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-5"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Bodove nije moguće poslati samom sebi.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-6"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ne može primiti bodove.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-100"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Greška nepoznata.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<SendPointsResponse> call, Throwable t) {
Toast.makeText(getActivity(), "Uspješno slanje bodova.", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e) {
Toast.makeText(getActivity(), "Podaci nisu ispravni, provjerite podatke !", Toast.LENGTH_SHORT).show();
} }
});
}
I basicly need some idea in OnFailure method to detect if user is turned off internet and to display proper message.
You can check this link where is explained in detail if internet connection status is available usgin the ConnectivityManager through the Connectivity Service.
Notice that your app will need permissions for obtaining the network status:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Getting a Malformed access token "t ​ype":"OAuthException","code":190

I am writing an android application to get the Facebook user albums and photos and display in my Android application.
I have created a Facebook App with APP_ID 281846961912565.
While creating the Facebook instance, I am passing this id as follows
facebook = new Facebook(APP_ID);
Using this instance, I am able to login to my FB account post on messages on facebook wall programatically.
After logging in, I get an access_token.
I'm using the access token to get the album ids using facebook.request("https://graph.facebook.com/me/albums?access_token="+facebook.getAccessToken());
Now I get {"error":{"message":"Malformed access token ACCESSTOKENACCESSTOKEN?access_token=ACCESSTOKENACCESSTOKEN","t‌​ype":"OAuthException","code":190}}
Can any of you please help me resolve this issue and point out what i am doing wrong.
My code is as follows:
private static final String[] PERMISSIONS = new String[] { "publish_stream","user_photos" };
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY,
Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext()
.getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.facebook_dialog);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null) {
facebookMessage = "Test wall post";
}
messageToPost = facebookMessage;
}
R.layout.facebook_dialog is the dialog which pops up asking if a message should be shared on facebook or not. If yes the following method is called.
public void share(View button) {
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new LoginDialogListener());
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null) {
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
getImagesFromUserAlbum();
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
Later when I do a `private void getImagesFromUserAlbum() {
facebook.getAccessToken();
JSONArray albumss = null;
String response = null;
try {
response = facebook.request("me/albums");
// `
I get the error
{"error":{"message":"Malformed access token ACCESSTOKEN?access_token=ACCESSTOKEN","type":"OAuthException","code":190}}
Thanks for your help.
The code above is now the working copy. Thanks to Bartek.
If you look at the Errors page in the documentation you will see that when you get error 190 you should authorise/reauthorise the user.
I suspect that this happened to you because you first logged in, then added the permissions to access the albums to your application BUT did not log out and log back in. Hence, you need to obtain a new access token which will grant the new permissions to your application.
Please check is there &expires in your access token if yes then remove it because it is not part of access_token and try after that.

Categories