Android if statement is NEVER exectued - android

Please help this is now driving me crazy.
I have an if, else if and else statement inside a try block.
if (loginSuccess.equalsIgnoreCase("true")) {
emailAddressEditText.setText("");
passwordEditText.setText("");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("redirectURL", redirectUrl);
editor.apply();
Intent intent = new Intent(LoginActivity.this, WebviewActivity.class);
intent.putExtra("url", redirectUrl);
startActivity(intent);
} else if (loginSuccess.equalsIgnoreCase("false")) {
Intent intent = new Intent(LoginActivity.this, ErrorActivity.class);
intent.putExtra("errormessage", "loginerror");
startActivity(intent);
} else if (loginSuccess.equalsIgnoreCase("")){
Intent intent = new Intent(LoginActivity.this, ErrorActivity.class);
intent.putExtra("errormessage", "servererror");
startActivity(intent);
}
the first "if" statement never gets executed.
I even tried to create a new String with "true" in it but no success.
Even the log says that the loginSuccess String IS TRUE!
I/System.out: true
What is wrong?

First you have to check for null,
if(loginSuccess != null)
{
if(loginSuccess.toString().contains("true"))
{
// its true
// do your code here as required
}
else{
// not contains true
}
}else
{
// loginSuccess is null
}

Try using
loginSuccess.trim().equalsIgnoreCase("true")

Related

Why I can NOT receive extra parameters from Intent in onStartCommand? [duplicate]

Is there any way to check if an extra has been passed when starting an Activity?
I would like to do something like (on the onCreate() in the Activity):
Bundle extras = getIntent().getExtras();
String extraStr = extras.getString("extra");
if (extraStr == null) {
extraStr = "extra not set";
}
But this is throwing a java.lang.NullPointerException.
Thank you.
Use the Intent.hasExtra(String name) to check if an extra with name was passed in the intent.
Example:
Intent intent = getIntent();
if (intent.hasExtra("bookUrl")) {
bookUrl = b.getString("bookUrl");
} else {
// Do something else
}
Also, use Intent.getStringExtra(String name) directly on the intent to handle the NullPointerException if no extras were passed.
Well, I had similiar problem. in my case the null point exception was happen when I checked if my bundle.getString() was equall to null.
here is how IN MY CASE I solved it:
Intent intent = getIntent();
if(intent.hasExtra("nomeUsuario")){
bd = getIntent().getExtras();
if(!bd.getString("nomeUsuario").equals(null)){
nomeUsuario = bd.getString("nomeUsuario");
}
}
if (this.getIntent().getExtras() != null && this.getIntent().getExtras().containsKey("yourKey")) {
// intent is not null and your key is not null
}
I think you need to check when extras != null
Bundle extras = getIntent().getExtras();
if (extras != null) {
String extraStr = extras.getString("extra");
}else {
extraStr = "extra not set";
}
I would use this solution in your case.
String extraStr;
try {
extraStr = getIntent().getExtras().getString("extra");
} catch (NullPointerException e ) {
extraStr = "something_else";
}
Working Code
If you want to check first Intent have no extra
Intent intent = getIntent();
if (intent.getExtras() == null){
startActivity(new Intent(Splash.this, Main.class));
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
}else {
if (intent.hasExtra("type")) {
String type = getIntent().getStringExtra("type");
switch (type){
case "showRateUsDialog":
Intent i = new Intent(Splash.this, Main.class);
i.putExtra("type", "showRateUsDialog");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
break;
case "refer":
Intent i2 = new Intent(Splash.this, Refer.class);
i2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i2);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
break;
default:
startActivity(new Intent(Splash.this, Main.class));
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
}
}
}
}

if app is login and its in background and click on app launcher icon from home screen it will display login screen

for login:
SharedPreferences sharedPref2 = getSharedPreferences("", Context.MODE_PRIVATE);
String userid = sharedPref2.getString(SharedPref.USER_ID, user_id);
if (userid != null) {
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(i);
return;
}
if App is opening from background then it will display HomeActivity properly ,
but when app is in background and open it from launcher icon then only it displays login screen .
Put the whole code in a function and check if the user is logged in or not in your onCreate method of loginActivity.
#Override
onCreate(Bundle savedBundleState){
.....
if(isUserloggedIn()){
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(i);
finish();
}
}
boolean isUserloggedIn(){
String userid = sharedPref2.getString(SharedPref.USER_ID, user_id);
if (userid != null) {
return true;
}
else{
return false;}
}

How to sign in automatically if login user Information exist in sharedpreferences in android

I have Three activity which will load based on different type user. I stored logged-in user info in sharedpreferences when log-in. I remove user info after clicking logout button. Now I need to check if record exist in sharedpreferences until log-Out user can automatically sign in to app. How to do it. Here is my code:
try {
object = new JSONObject(root.getTextContent().toString());
StatusValue = object.getString("status");
UserInfoValue = object.getString("UserInfo");
} catch (JSONException e) {
e.printStackTrace();
}
SharedPreferences.Editor editor = getSharedPreferences("UserInfoValues", MODE_PRIVATE).edit();
editor.putString("UserInfos", UserInfoValue);
editor.commit();
// Log.d("Value:" ,Value);
txtView.setText(StatusValue);
if(StatusValue.equalsIgnoreCase("success"))
{
String userType = null;
//SharedPreferences prefs = getSharedPreferences("UserInfoValues", MODE_PRIVATE);
// String restoredText = prefs.getString("UserInfos", null);
try {
JSONObject infoObject = new JSONObject(UserInfoValue);
userType = infoObject.getString("UserType");
} catch (JSONException e) {
e.printStackTrace();
}
if(userType.equalsIgnoreCase("NormalUser"))
{
Intent intent=new Intent(LoginActivity.this,NewBookingActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Successfully Loged In As Normal User", Toast.LENGTH_LONG).show();
finish();
}
if(userType.equalsIgnoreCase("HelpDesk"))
{
Intent intent=new Intent(LoginActivity.this,DriverActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Successfully Loged In As HelpDesk User", Toast.LENGTH_LONG).show();
finish();
}
if(userType.equalsIgnoreCase("Car"))
{
Intent intent=new Intent(LoginActivity.this,DriverActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Successfully Loged In As Car User", Toast.LENGTH_LONG).show();
finish();
}
in your launcher Activity,
boolean isRegistered = preferences.getBoolean("isRegistered", false);
if(isRegistered){
//continue to your home screen
}else {
//show login page
}
and after user logs in, update your sharedpreference like this,
editor.putBoolean("isRegistered", true).commit();
and when user logs out, update your sharedpreference like this,
editor.putBoolean("isRegistered", false).commit();
Use shared preference when user login validated and go for next activity like this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.putString("type","admin");
editor.apply();
then where you use your splash put this:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
username = sharedPreferences.getString("username","");
password = sharedPreferences.getString("password","");
type = sharedPreferences.getString("type","");
if(!(username.equals("") && password.equals(""))){
if(type.equals("admin")){
Intent i = new Intent(getActivity(), AfterAdLog.class);
startActivity(i);
}else if(type.equals("member")){
Intent i1 = new Intent(getActivity(), AfterLogMem.class);
startActivity(i1);
}
}

TextInputLayout issue at Login time

I have TextInputLayout in login, when i click on login button if username is empty then show error same as with password when password is empty then show error but if username is empty and password is non empty at that time error is not shown so how can i solve this problem? My Code is like below!!!
#Override
public void onClick(View v) {
Intent mIntent;
switch (v.getId()) {
case R.id.txtSignIn:
hideKeyboard(mActivity, v);
if (etUserName.getText().toString().equals("")) {
etUserName.requestFocus();
etUserName.setCursorVisible(true);
tilPassword.setErrorEnabled(false);
tilUserName.setErrorEnabled(true);
tilUserName.setError(getString(R.string.username_required));
} else if (etPassword.getText().toString().equals("")) {
etPassword.requestFocus();
etPassword.setCursorVisible(true);
tilUserName.setErrorEnabled(false);
tilPassword.setErrorEnabled(true);
tilPassword.setError(getString(R.string.password_required));
} else {
tilUserName.setErrorEnabled(false);
tilPassword.setErrorEnabled(false);
showToast(mActivity, getString(R.string.successfully_login), 0);
mIntent = new Intent(SignIn.this, DashBoard.class);
startActivity(mIntent);
}
break;
case R.id.txtSignUp:
mIntent = new Intent(mActivity, SignUp.class);
startActivity(mIntent);
break;
case R.id.txtForgotPassword:
mIntent = new Intent(mActivity, ForgotPassword.class);
startActivity(mIntent);
break;
}
try {
} catch (Exception e) {
LOGD(getClass().getSimpleName(), e.getMessage());
LOGE(getClass().getSimpleName(), e.getMessage());
}
}
Use isEmpty() method since null and "" <- this is not equal you cannot derive if the EditText is empty or not .
Something like this below will pop an error on the screen is either password or username field is empty
if (etUserName.isEmpty() && etPassword.isEmpty()) {
<your code if nothing is entered>
}
For additional help check this out :
Check if EditText is empty.

Android getting NULL data sent in SERVICE with putExtra in activity

in own service i want to send data with intent but i am getting null from Activity.I have read about document from this solution but i can not resolve the problem.
SERVICE :
public void notifyTest(int unread){
Intent i = new Intent();
i.setClass(this, YourDialog.class);
i.putExtra("data", unread);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity ( i );
}
get data from Activity:
Intent intent = getIntent ();
String count = intent.getStringExtra("data");
i can not use BroadCostReceiver to resolve problem.
I think this error happened because your data is int, but you want to receive it as String.
Try to change it like this :
public void notifyTest(int unread){
Intent i = new Intent();
i.setClass(this, YourDialog.class);
i.putExtra("data", unread + ""); //convert to STRING
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity ( i );
}
Try this way,hope this will help you to solve your problem.
unread is int then :
getIntent().getIntExtra("data",0);
unread is String then :
getIntent().getStringExtra("data");
Use this to "put"
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifer = null;
i.putExtra("STRING_I_NEED", strName);
Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}

Categories

Resources