迭代JSON数组并使用Name值来标识TextView Android



我被卡住了。我从服务器收到一个JSON字符串。我将其加载到一个名为allTheArray的JSON数组中。现在,我想遍历数组并提取名称/值对。这是我能做到的。对于数组中的每个Name,我的布局中都有一个相应的TextView。为了便于记忆!我现在想遍历数组,并将正确的值放在正确的TextView中。伪代码。

For I =0 to length
Name is get name from allTheArray
Value is get value from allTheArray
TextViewWithTheAboveName.setText=Value
Next

这可能吗?在PHP中,你可以使用$$变量名等。我无法理解这一点。有什么建议吗。

button_clearWCC.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String TAG ="JSONWALK";
Toast.makeText(MainActivity.this, "Loading all fields", Toast.LENGTH_LONG).show();
for(int i = 0; i<allTheArray.names().length(); i++){
try {
String key=allTheArray.names().getString(i);
String value = allTheArray.getString(key);
//the key string is the name of the TextView
//I know I have just set the key to be a string but is there anyway I can use that to define which //TextView I change.
key.setText(value)
Log.i(TAG, "key = " + key + " value = " + value);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});

所以我就是这样解决的……不知道开销或效率,但它对我有效。使用键有效地获取TextView的id。然后为该id创建一个TextView t,然后使用它清空单元格或向单元格添加值。这可能会在其他地方产生影响,但尚未发现。

button_clearWCC.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String TAG ="JSONWALK";
Toast.makeText(MainActivity.this, "Clearing all fields", Toast.LENGTH_LONG).show();
for(int i = 0; i<allTheArray.names().length(); i++){
try {
String key=allTheArray.names().getString(i);
String value = allTheArray.getString(key);
//this bit solved it
int id = getResources().getIdentifier(key, "id", getBaseContext().getPackageName());
TextView t = (TextView) findViewById(id);
t.setText("");
//end of this bit solved it
Log.i(TAG, "key = " + key + " value = " + value);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});

最新更新