首页 > 解决方案 > Android - 根据用户输入传递自定义字符串

问题描述

我正在创建一个 android 应用程序,在其中我从 edittext 字段获取用户输入,然后将这些输入作为字符串传递给自定义字符串。

我在消除用户提供的空字符串时遇到了麻烦。

下面是我的代码:

EditText siteName = findViewById(R.id.editSite); //these types are of EditText values provided by the user
            strSite = "site%3A" + siteName.getText().toString();
            if (strSite.matches("")) {
                strSite = null;
                return;
            }

            fileType = findViewById(R.id.editFile);
            strFile = "filetype%3A" + fileType.getText().toString();
            if (strFile.matches("")) {
                strFile = null;
                return;
            }

            inUrl = findViewById(R.id.editUrl);
            strUrl = "inurl%3A" + inUrl.getText().toString();
            if (strUrl.matches("")) {
                strUrl = null;
                return;
            }

            inTitle = findViewById(R.id.editTitle);
            strTitle = "intext%3A" + inTitle.getText().toString();
            if (strTitle.matches("")) {
                strTitle = null;
                return;
            }

            indexOf = findViewById(R.id.editIndex);
            strIndex = "indexof%3A" + indexOf.getText().toString();
            if (strIndex.matches("")) {
                strIndex = null;
                return;
            }

            String dork = strSite +" "+ strFile+" "+strUrl+" "+strTitle+" "+strIndex; //this is the custom string

所以这里的动机是将空字符串设置为空String dork

请让我知道是否可以通过这种方式完成或使用复选框很容易。

提前致谢

标签: javastring

解决方案


所以在做了一些研究之后,我找到了解决上述问题的方法。非常简单,只需使用 String 类型的 ArrayList 然后将非空字符串推入其中,请找到以下代码:

ArrayList<String> arrstr;
   arrstr = new ArrayList<String>();
   if(!(strSite.equals("site%3A"))){
      arrstr.add(strSite);
   }else {
      arrstr.add("");
   } 
// same for other string inputs from user.
  ...

将字符串数组转换为字符串:使用Apache Commons Lang以便我可以使用StringUtils.join

String dork = StringUtils.join(arrstr, " ");

推荐阅读