简体   繁体   中英

Passing selective data via intents

I am making a basic contacts app with 4 fields; name, number, website and location.

Now while making the entry, the checks and prompts the user to type in case they leave and number blank.

But i want web and location to be optional. When the data exists; I want it to be passed on but when it doesn't exist, i want it to do nothing.

Here is my code.

if(etName.getText().toString().isEmpty() || etNumber.getText().toString().isEmpty())
{
    Toast.makeText(this, "Please fill out the necessary fields", Toast.LENGTH_SHORT).show();
}
else
{
    Intent intent = new Intent();
    intent.putExtra("name", etName.getText().toString());
    intent.putExtra("number", etNumber.getText().toString().trim());

    if(etWeb.getText().toString().trim() != null)
    {
        intent.putExtra("web", etNumber.getText().toString().trim());
    }
    if(etLocation.getText().toString() != null)
    {
        intent.putExtra("location", etLocation.getText().toString().trim());
    }

The problem is the code says that condition etWeb.getText().toString().trim() != null and etLocation.getText().toString().trim() != null are always True

What changes should I make?

你应该检查isEmpty(),而不是null。

You can check string is not empty instead of not null

if(!android.text.TextUtils.isEmpty(etWeb.getText().toString().trim())){
 intent.putExtra("web", etWeb.getText().toString().trim());
}

or can check

 if(etWeb.getText().toString().trim().length() > 0){
     intent.putExtra("web", etWeb.getText().toString().trim());
  }

You can try below code to check weather data is available or not.

if(!etWeb.getText().toString().equals(""))
{
    intent.putExtra("web", etNumber.getText().toString().trim());
}

Above code will check if data is present in the field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM