Search code examples
androidjsontextviewassets

Print a json file in textView


Here my json file: settings.json (in assets folder):

{
  "settings": [
    {
      "level": "upper"
    }
  ]
}

I working in Android Studio. I print the upper word in a TextView from the json file, but this not working, my app is crashed. Ideas? my code in java file:

public class MainActivity extends AppCompatActivity {
    ArrayList<String> level = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {

            JSONObject obj = new JSONObject(loadJSONFromAsset());

            JSONArray userArray = obj.getJSONArray("settings");

            for (int i = 0; i < userArray.length(); i++) {

                JSONObject userDetail = userArray.getJSONObject(i);

                level.add(userDetail.getString("level"));
            }
            } catch(JSONException e){
                e.printStackTrace();

            }
        TextView textView = (TextView) findViewById(R.id.textView);

        textView.setText(level.get(0));

        setContentView(R.layout.activity_main);
    }
    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("settings.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

Thank you. Android, json, source code...


Solution

  • I hope this will work for you,

    Write Your onCreate() method like this,

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            try {
    
                JSONObject obj = new JSONObject(loadJSONFromAsset());
                JSONArray userArray = obj.getJSONArray("settings");
                for (int i = 0; i < userArray.length(); i++) {
                    JSONObject userDetail = userArray.getJSONObject(i);
                    level.add(userDetail.getString("level"));
                }
                } catch(JSONException e){
                    e.printStackTrace();
    
                }
            TextView textView = (TextView) findViewById(R.id.textView);
    
            textView.setText(level.get(0));
        }
    

    set setContentView() method first then initialize your textview.In your code you accessing text view before layout initialized.