如果点击按钮,我想创建应用程序,使用json解析数据更改textview。那么,我是怎么做到的?
这是我的代码:
public class MainActivity extends AppCompatActivity {
TextView tampilkan;
Button btn1;
String str_json = "{\"harga_jus\":\"{\"mangga\":\"5000\",\"jeruk\":\"3000\",\"apel\"4000\"}}";
String copy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tampilkan = (TextView)findViewById(R.id.tampil);
btn1 = (Button)findViewById(R.id.btn);
try {
JSONObject harga_jus = new JSONObject(str_json);
JSONObject jus = harga_jus.getJSONObject("harga_jus");
final String mangga = jus.getString("mangga");
copy = mangga;
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tampilkan.setText(copy);
}
});
}
catch (Exception e){
e.printStackTrace();
}
}
}
答案 0 :(得分:3)
请阅读logcat:
org.json.JSONException:{" harga_jus":" {" mangga":" 5000",&##的第17个字符的未终止对象34;哲鲁克":" 3000""阿佩尔" 4000"}}
你的json应该是:
Model.User.find({
_id: userid
"notification":{ $elemMatch: { "isRead": false} }
}).exec(function (err, result) {
console.log(result);
res.send(result);
})
答案 1 :(得分:3)
final TextView tampilkan = (TextView) findViewById(R.id.tampil);
Button btn1 = (Button) findViewById(R.id.btn);
String JSON = "{ \"harga_jus\": { \"mangga\": \"5000\", \"jeruk\": \"3000\", \"apel\": \"4000\" } }";
try {
JSONObject harga_jus = new JSONObject(JSON);
JSONObject jus = harga_jus.getJSONObject("harga_jus");
final String mangga = jus.getString("mangga");
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tampilkan.setText(mangga);
}
});
} catch (Exception e) {
e.printStackTrace();
}
答案 2 :(得分:2)
你的json无效,用下面的字符串替换你的字符串:
String str_json = "{\"harga_jus\":{\"mangga\":\"5000\",\"jeruk\":\"3000\",\"apel\":\"4000\"}}";