我想让应用程序,如果点击按钮,文本视图改变与json解析数据。所以,我该怎么做?
这是我的代码:

 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();
            }

        }
    }

最佳答案

    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();
    }

10-07 13:01