if (String == null or String == "") doesn't activate [duplicate] - android

This question already has answers here:
String comparison - Android [duplicate]
(17 answers)
Closed 6 years ago.
I got this problem where I have three if statements and every one of them has IF String == null or String == "" and even the getText doesn't give any value, these doesn't activate.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_two:
final String hei = h.getText().toString();
final String wei = w.getText().toString();
String waist = wc.getText().toString();
if (hei == null || wei == null ){
final Animation animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein);
checker.setText("Please, put your information in these spots!");
checker.startAnimation(animationFadeIn);
}
else if (waist == null){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
builder.setMessage("If you let Waist circumference empty, we will ask it from you later.")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(getApplicationContext(), number3.class);
i.putExtra("height" , hei);
i.putExtra("weight" , wei);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
AlertDialog alert = builder.create();
alert.show();
}
else{
Log.d("BMI Height" , String.valueOf(wei));
Log.d("BMI Weight" , String.valueOf(hei));
Intent i = new Intent(getApplicationContext(), healthcalculator3.class);
i.putExtra("height" , hei);
i.putExtra("WC" , waist);
i.putExtra("weight" , wei);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
And even if all those (waist, wei, hei) are null or not value set, it only activates the last ELSE and the machine thinks that they have some data/value.

You can also try this like
if (hei == null || wei == null || hei.equals("") || wei.equals("")){
// your body here
}

Try this check
if(!TextUtils.isEmpty(string){
//body here
}

The best way to compare strings is use stringInstance.equals("what to compare"), so your code will be:
hei.equals("")
Also you can use length of string:
hei.length() > 0

Related

Iterate through arraylist and show alert dialog for each item in array list and then move to next item when click positive button

I am creating an auto caller app in which i have used a button which takes data from arrayList, iterate through the arraylist and ask user on each element if want to do next call or pause on that for this i have used alert dialog, but the loop is not getting pause on each element it went to the last element and show alert dialog for that contact number.
private List<ContactEntity> mContactsList = new ArrayList<>();
private ContactEntity c;
private int i = 0;
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.start_call) {
Toast.makeText(this, "Call Started" + mContactsList.size(), Toast.LENGTH_LONG).show();
startAutoCall();
}
return super.onOptionsItemSelected(item);
}
private void startAutoCall() {
if (mContactsList.isEmpty()) {
Toast.makeText(this, "Import Contacts ", Toast.LENGTH_LONG).show();
} else {
c = mContactsList.get(i);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
while(i < mContactsList.size()){
c = mContactsList.get(i);
Log.d(TAG, "startAutoCall: " + c.getId());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Auto Dialer Start");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
}
});
AlertDialog dialog = builder.create();
dialog.show();
i++;
}
}
}
It's not a good idea to build alert dialog inside a loop. Instead, create one and update the value for each element in the list on button click. Override onClickListener for the dialog so that you can control the flow better.
Here's a snippet in kotlin.
if(mContactList.isNotEmpty()){
c = mContactList.get(i)
val builder = AlertDialog.Builder(this)
builder.setTitle("Auto Dialer Start")
builder.setMessage("Your message here...")
builder.setPositiveButton("OK", null)
val dialog = builder.create()
dialog.setOnShowListener{ dialogInterface->
val btnOk = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
btnOk.setOnClickListener{
//Your code here...
if(i == mContactList.size-1){
dialogInterface.dismiss()
}else {
i++
c = mContactList.get(i)
}
}
}
dialog.show()
}

I want to get value inside my String JsonObject

try {
JSONObject jobj = new JSONObject(response);
String status = jobj.getString("status");
String error = jobj.getString("result");
if(status == "1"){
builder.setTitle("Server Message");
builder.setMessage("Please validate your ID in registered email.");
}else if(status == "0")
{
builder.setTitle("Server Message");
builder.setMessage(error);
}else{
builder.setTitle("Server Message");
builder.setMessage(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent mainIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(mainIntent);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
my response is {"status":"1","result":"true")
But I can't do if else to the "status" mean I can't get value of "1" inside the status.
Two mistakes
Getting integer and boolean as string
Comparing string with ==
Do this
int status = jobj.getInt("status");
Boolean error = jobj.getBoolean("result");
if(status == 1){
builder.setTitle("Server Message");
builder.setMessage("Please validate your ID in registered email.");
}else if(status == 0)
{
...
...
"==" is reference compare.
So, replace "==" to equals()
status.equals("1")
I hope this will work for you.
By using String
String status = jobj.getString("status");
String error = jobj.getString("result");
if(status.equalsIgnoreCase("1")){
builder.setTitle("Server Message");
builder.setMessage("Please validate your ID in registered email.");
}else if(status.equalsIgnoreCase("0")){
// your other code.
}

Registration condition not working? Android

I am trying to make registration activity without using SQLite in android.
In which user enters data at run time and if he do not fill all sections then user will not proceed to another activity. But the problem is if user is not entering anything then its also proceeding to another activity.
here is my code. Plz help me whats the error.
public void onClick(View v) {
EditText us = (EditText)findViewById(R.id.us);
EditText pas = (EditText)findViewById(R.id.pas);
EditText em = (EditText)findViewById(R.id.em);
EditText ph = (EditText)findViewById(R.id.ph);
String UserName= us.getText().toString();
String Email= em.getText().toString();
String Password= pas.getText().toString();
String PhoneNo= ph.getText().toString();
us.getEditableText().toString();
em.getEditableText().toString();
pas.getEditableText().toString();
ph.getEditableText().toString();
if ((us != null) && (em != null) && (pas != null) &&(ph != null)){
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
SendOfferActivity.class);
startActivity(intent);
}
else{
AlertDialog.Builder builder1 = new AlertDialog.Builder(Registration.this);
builder1.setMessage("Enter Valid Information.");
builder1.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}});
}
But the problem is if user is not entering anything then its also
proceeding to another activity. here is my code
you are just checking if the object are not null, but what you want really check is if the EditTexts contain something. You use
if (!TextUtils.isEmpty(am.getText().toString()) /* do the same for the other */) {
}
to check the content of your EditTexts
You are just checking the EditText elements and you show test if the user typed something.
String usTxt = us.getText().toString();
String emTxt = em.getText().toString();
String pasTxt = pas.getText().toString();
String phTxt = ph.getText().toString();
if (!usTxt.isEmpty() && !emTxt.isEmpty() && !pasTxt.isEmpty() && !phTxt.isEmpty())
{
// your code
}
if ((!UserName.isEmpty()) && (!Email.isEmpty()) && (!Password.isEmpty() &&(!PhoneNo.isEmpty())){}

alertdialog redirection to url

I used the android alertdialog in order to redirect to a url, the redirection should go according to user choice, here is the code:
final CharSequence[]stringArray = {"1" ,"2" , "3"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (stringArray.toString().equals("1")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(st));
startActivity(intent);
}
else if (stringArray.toString().contains("2")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(st2));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
but when I click 1 or 2 there is no redirection to the url
what is wrong with the code?
You are checking your arrays items which is not valid way to implement. You need to check for selected item's id which you can get from onclick method only.
As the array count starts from "0" so can check your selected item with "0 to 2" where your 0 will be considered as "1" selected and so on.
Check out below code:
final CharSequence[] stringArray = { "1", "2", "3" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (item == 0)
// if (stringArray.toString().equals("1"))
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(st));
startActivity(intent);
} else if (item == 1)
// else if (stringArray.toString().contains("2"))
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(st2));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
Please use following code:-
final CharSequence[] stringArray = { "1", "2", "3" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (position == 0) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(st));
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(st2));
startActivity(intent);
}
else if (position == 2) {
// write some code
}
}
});
AlertDialog alert = builder.create();
alert.show();

How to disable other buttons until the first button is clicked

I'm a newbie in android. I have got four buttons when I click my first tab. I want user to click the first button first rather than randomly clicking other buttons first. so need to disable other buttons until my first button is clicked and once the first button is clicked and when the user returns back all the buttons need to be enabled. How do I do this? Please help!!
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgbtn_details)
{
attendees_imgbtn.setEnabled(true);
resources_imgbtn.setEnabled(true);
contacts_imgbtn.setEnabled(true);
count = 1;
Intent detail_intent=new Intent(getActivity().getApplicationContext(),DetailsActivity.class);
detail_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(detail_intent);
}
else if(v.getId() == R.id.imgbtn_attendees && count == 0)
{
if(count == 1)
{
Intent attendee_intent = new Intent(getActivity().getApplicationContext(),AttendeesActivity.class);
attendee_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(attendee_intent);
}
else
{
attendees_imgbtn.setEnabled(false);
resources_imgbtn.setEnabled(false);
contacts_imgbtn.setEnabled(false);
}
}
else if(v.getId() == R.id.imgbtn_resources && count == 0)
{
if(count == 1)
{
Intent resources_intent = new Intent(getActivity().getApplicationContext(),ResourcesActivity.class);
resources_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(resources_intent);
}
else
{
attendees_imgbtn.setEnabled(false);
resources_imgbtn.setEnabled(false);
contacts_imgbtn.setEnabled(false);
}
}
else if(v.getId() == R.id.imgbtn_contacts && count == 0)
{
if(count == 1)
{
Intent contact_intent = new Intent(getActivity().getApplicationContext(),ContactsActivity.class);
contact_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contact_intent);
}
else
{
attendees_imgbtn.setEnabled(false);
resources_imgbtn.setEnabled(false);
contacts_imgbtn.setEnabled(false);
}
}
}
Use setEnable(true) for buttons to enable and disable buttons
I think you need to pass variable specifying that you want to enable buttons or not.
First time, pass it as:
Intent intent = new Intent (this, NextAct.class);
intent.putExtra ("ENABLE", "No");
When you want to enable the buttons, pass String as Yes:
Intent intent = new Intent (this, NextAct.class);
intent.putExtra ("ENABLE", "YES");
Then check in your NextAct class for this string.
Intent intent = getIntent();
String enableBtn = intent.getStringExtra("ENABLE");
if (enableBtn != null && enableBtn.equalsIgnoreCase("YES")) {
button2.setEnabled(true);
button3.setEnabled(true);
button4.setEnabled(true);
} else {
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
}
So your buttons will be enabled only when you want them to.
Hope that helps.
define a static Boolean variable wasClicked....if but1 was clicked make variable true otherwise false...override this method....as user comes back it will check first than enable or disable as 1st but was clicked or not.
#Override
protected void onResume() {
// TODO Auto-generated method stub
if(!wasClicked){
but2.setClickable(false);
but3.setClickable(false);
but4.setClickable(false);
}else{
but2.setClickable(true);
but3.setClickable(true);
but4.setClickable(true);
}
}

Categories

Resources