You must ensure that your application reads the Json file correctly. Below is the working code:
package com.example.a386019.spinnerjson; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class SpinnerActivity extends AppCompatActivity { String json_string; JSONObject jsonObj; JSONArray jsonArray; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spinner); json_string= loadJSONFromAsset(); ArrayList<String> messages = new ArrayList<String>(); { try { jsonObj =new JSONObject(json_string); jsonArray =jsonObj.getJSONArray("formules"); String formule,url; for (int i = 0; i < jsonArray.length(); i++){ JSONObject jObj = jsonArray.getJSONObject(i); formule= jObj.getString("formule"); messages.add(formule); } } catch (JSONException e) { e.printStackTrace(); } } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, messages); Spinner spinner = (Spinner)findViewById(R.id.spinner); spinner.setAdapter(adapter); } public String loadJSONFromAsset() { String json = null; try { InputStream is = getAssets().open("formules.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; } }
and layout:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.a386019.spinnerjson.SpinnerActivity"> <Spinner android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/spinner" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="42dp" /> </RelativeLayout>
and json file in ASSETS folder:
{ "formules": [ { "formule": "Linear Motion", }, { "formule": "Constant Acceleration Motion", }, { "formule": "Projectile Motion", }, { "formule": "Force", }, { "formule": "Work, Power, Energy", }, ] }
source share