如何将 JSONObject 中的数据提取到 EditText 字段

How to extract data inside a JSONObject to EditText fields

在下面显示的代码中,配置文件包含用户配置文件中的所有数据,如 fname、lname 和电子邮件(jsonObject 格式)。我想提取这些详细信息并填写下面显示的 EditText 框。

一旦我打开此表单,这些详细信息将自动填充到那些 EditText 字段中。

String profile = getIntent().getStringExtra("profile");
try {
    JSONObject profileJSON = new JSONObject(profile);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
fnameET = (EditText) findViewById(R.id.registerfName);
lnameET = (EditText) findViewById(R.id.registerlName);
emailET = (EditText) findViewById(R.id.registerEmail);

如有任何帮助,我们将不胜感激

使用 JSONObject.getString(key) 使用来自 JSONObejct 的键获取所有值:

JSONObject profileJSON = new JSONObject(profile);
fnameET = (EditText) findViewById(R.id.registerfName);
fnameET.setText(profileJSON.getString("fname"));
//.... do same to get otger values from profileJSON

同时添加 nullempty 在传递给 setText 方法

之前检查从 JSONObject 检索到的值

这样做

fnameET = (EditText) findViewById(R.id.registerfName);
lnameET = (EditText) findViewById(R.id.registerlName);
emailET = (EditText) findViewById(R.id.registerEmail);
String profile = getIntent().getStringExtra("profile");
try {
    JSONObject profileJSON = new JSONObject(profile);
    if(profileJSON.has("fname"))
        fnameET.setText(profileJSON.getString("fname"));
    if(profileJSON.has("lname"))
        lnameET.setText(profileJSON.getString("lname"));
    if(profileJSON.has("email"))
        emailET.setText(profileJSON.getString("email"));
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}
if(profileJSON!=null){

String userFirstName,userLastName,userEmail;

userFirstName = profileJSON.getString("fname");

userLastName = profileJSON.getString("lname");

userEmail = profileJSON.getString("email");

if(userFirstName!=null){
fnameET.setText(userFirstName);
}

if(userLastName!=null){
 lnameET.setText(userLastName);

}

if(userEmail!=null){
emailET.setText(userEmail);
}



}