Set TextView with json parse when Button onClick

Question

I want to make app if button clicked, the textview changed with json parse data. so, how i do that?

this is my code :

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

        }
    }

Show source
| android   | json   2017-01-03 10:01 3 Answers

Answers ( 3 )

  1. 2017-01-03 11:01

    Just read logcat:

    org.json.JSONException: Unterminated object at character 17 of {"harga_jus":"{"mangga":"5000","jeruk":"3000","apel"4000"}}

    Your json should be:

    String str_json = "{\"harga_jus\":{\"mangga\":\"5000\",\"jeruk\":\"3000\",\"apel\":\"4000\"}}";
    
  2. 2017-01-03 11:01

    your json is not valid, replace your string with below :

    String str_json = "{\"harga_jus\":{\"mangga\":\"5000\",\"jeruk\":\"3000\",\"apel\":\"4000\"}}";
    
  3. 2017-01-03 11:01
        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();
        }
    
◀ Go back