在Textview为空时设置默认值

Set the Default value in Textview when it is empty

我正在使用 AlertDialog Box 通过以下代码为我的聊天应用程序请求用户名

 private void request_user_name() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Enter name:");

    final EditText input_field = new EditText(this);

    builder.setView(input_field);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
              name = input_field.getText().toString();
        }
    });

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
            request_user_name();
        }
    });

    builder.show();
}

我调用下面的代码将 user_name 字符串传递给另一个 activity

intent.putExtra("user_name",name);

但是当它为空时,应用程序崩溃。

如果文本字段为空,我如何设置默认值并在出现 none 时将默认用户名传递给下一个 activity。

类似

if ( name == null ) {
    // if Textfield is empty set the username anonymous as default
}
else {
    //username from the alertdialog box  
}

报错的日志猫是 log Cat error

第 51 行的代码如下

user_name = getIntent().getExtras().get("user_name").toString();

对不起我的代码,我还处于初学者阶段。

提前致谢。

试试这个

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
          name = input_field.getText().toString().trim();

          if(name.isEmpty()){
             name = default_name;
          }

          ...

          intent.putExtra("user_name", name);

          ... 
    }
});

编辑:尝试使用此方法获取数据

Bundle bundle = intent.getExtras();       
if(bundle != null){
    String name = bundle.getString("user_name");      
}

而不是调用 if ( name == null ) {} 请直接使用下面的崩溃以避免崩溃 -

if(getIntent()!=null)
  {
 if(getIntent().getStringExtra("user_name")!=null)
 {
    String rcvdData=getIntent().getStringExtra("user_name");
   }
  }