Rubit Rubit - 6 months ago 18
Android Question

What is the function of the "loginName = "Friend"" below?

The loginName here is input for username. I assume that the "loginName = "Friend" will display "Friend" as default username if there is no input, but it's not right. So what is the meaning of that code and if I want to display "Friend" as default, How can I do?

package com.example.rubit.interactivestory.ui;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.example.rubit.interactivestory.R;

public class Story extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story);

Intent intent = getIntent();
String loginName = intent.getStringExtra(getString(R.string.login_name));

if (loginName == null) {
loginName = "Friend";
}
Toast.makeText(this,loginName,Toast.LENGTH_LONG).show();
}
}

Answer

It is the default for when the input is null. But you probably have the issue that it's not null but empty (""). You should also check for:

if (loginName == null || TextUtils.isEmpty(loginName)) {
        loginName = "Friend";
}
Comments