简体   繁体   English

EditText:如何删除从Json获得的“空”字符串

[英]EditText: how to remove “null” string obtained from a Json

Is there any way I can eliminate the "null" string of an editing text brought from a JSONObject response? 有什么方法可以消除JSONObject响应带来的编辑文本的“空”字符串? and just show the empty EditText. 并显示空的EditText。

He did it in the following way. 他以以下方式做到了。

 if (jsonResponse.getString(DataManager.Name).equals("null"){
    edtName.setText("");
 }else{

  edtName.setText(jsonResponse.getString(usersDataInfo.getNombre()));

 }

But when the field comes with information, it enters the instruction again and removes the information. 但是,当字段附带信息时,它将再次输入指令并删除信息。

JSON JSON格式

{
    "ID": 23,
    "NOMBRE": null,
    "APELLIDOPATERNO": null,
    "APELLIDOMATERNO": null,
    "TELEFONO": null,
    "CELULAR": null,
    "NACIMIENTO": null,
    "SEXO": null,
    "USUARIOID": 7
}

Use the method isNull() to check for null value. 使用方法isNull()检查空值。

ie: 即:

if (jsonResponse.isNull("NOMBRE")) {
  edtName.setText("")
} else {
  edtName.setText(jsonResponse.getString("NOMBRE"))
}

or in case your returning someting, simply: 或者如果您返回某物,只需:

jsonResponse.isNull("CELULAR") ? (return someting) : (return another thing)

I've created a sample and for me it's working, take a look : 我创建了一个示例,对于我来说,它正在运行,请看一下:

public class MainActivity extends AppCompatActivity {

    private EditText etEjemplo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etEjemplo = findViewById(R.id.etEjemplo);

        String json = "{\n" +
                "\t\"ID\": 23,\n" +
                "\t\"NOMBRE\": null,\n" +
                "\t\"APELLIDOPATERNO\": null,\n" +
                "\t\"APELLIDOMATERNO\": null,\n" +
                "\t\"TELEFONO\": null,\n" +
                "\t\"CELULAR\": null,\n" +
                "\t\"NACIMIENTO\": null,\n" +
                "\t\"SEXO\": null,\n" +
                "\t\"USUARIOID\": 7\n" +
                "}";

        try {
            JSONObject jObj = new JSONObject(json);
            String nombre = jObj.getString("NOMBRE");
            //You can use jObj.isNull("NOMBRE") instead
            if(nombre.equals("null")){
                etEjemplo.setText("");
            }
            else{
                etEjemplo.setText(nombre);
            }
            //One line case 
            //etEjemplo.setText(nombre.equals("null") ? "" : nombre);
            //or
            //etEjemplo.setText(jObj.isNull("NOMBRE") ? "" : nombre);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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