如何在两个spinner + android中设置Assets json文件数据?

时间:2017-07-22 05:37:32

标签: android json

Json文件:

{
"Iraq":["Baghdad","Karkh","Sulaymaniyah","Kirkuk","Erbil","Basra","Bahr","Tikrit","Najaf","Al Hillah","Mosul","Haji Hasan","Al `Amarah","Basere","Manawi","Hayat"],

 "Lebanon":["Beirut","Zgharta","Bsalim","Halba","Ashrafiye","Sidon","Dik el Mehdi","Baalbek","Tripoli","Baabda","Adma","Hboub","Yanar","Dbaiye","Aaley","Broummana","Sarba","Chekka"]
}

我需要在第二个微调器中按照所选的微调器国家/地区在第一个微调器和城市名称中显示国家/地区名称。

如何编写android?

我的代码:

公共类Search_for_room扩展了活动{

JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<CollegeList> world;
String value,key;
List<String> al;
ArrayAdapter<String> adapter;
HashMap<String, String> m_li  = new HashMap<String, String>();
public  ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
CustomAdapterStatus customAdapter;
Search_for_room activity = null;
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_for_room);
    activity = this;
    ArrayList<String> items=getCountries("countriesToCities.json");
    spinner=(Spinner)findViewById(R.id.spCountry);
    spinnerCity=(Spinner)findViewById(R.id.spCity);
}

private ArrayList<String> getCountries(String fileName){
    JSONArray jsonArray=null;
    ArrayList<String> cList=new ArrayList<String>();
    try {
        InputStream is = getResources().getAssets().open(fileName);
        int size = is.available();
        byte[] data = new byte[size];
        is.read(data);
        is.close();
        String json = new String(data, "UTF-8");
        JSONObject jsonObj = new JSONObject(json);

       // JSONObject resultObject = jsonObj.getJSONObject("result");
        System.out.print("======Key: "+jsonObj);

        Iterator<String> stringIterator = jsonObj.keys();
        while(stringIterator.hasNext()) {
            key = stringIterator.next();
            value = jsonObj.getString(key);
            System.out.println("------------"+key);
            m_li.put(key,value);
            al = new ArrayList<String>(m_li.keySet());

            final SpinnerModel sched = new SpinnerModel();

            /******* Firstly take data in model object ******/
            sched.setCountryName(value);
            //   sched.setImage(key);
            sched.setStates(key);

            /******** Take Model Object in ArrayList **********/
            CustomListViewValuesArr.add(sched);
            Resources res = getResources();
            customAdapter = new CustomAdapterStatus(activity, R.layout.spinner_item, CustomListViewValuesArr,res);
            spinner.setAdapter(adapter);
        }
    }catch (JSONException ex){
        ex.printStackTrace();
        /*jsonArray=new JSONArray(json);
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jobj = jsonArray.getJSONObject(i);
                System.out.pri
                //cList.add(String.valueOf(jobj.keys()));
            }
        }*/
    }catch (IOException e){
        e.printStackTrace();
    }
    return cList;
}

}

3 个答案:

答案 0 :(得分:0)

尝试此代码可以帮助您

 try {
        // load json from assets    
        JSONObject obj = new JSONObject(loadJSONFromAsset());

        // than get your both json array
        JSONArray IraqArray = obj.getJSONArray("Iraq");
        JSONArray LebanonArray = obj.getJSONArray("Lebanon");

        // declare your array to store json array value
        String Iraq[] = new String[IraqArray.length()];
        String Lebanon[] = new String[LebanonArray.length()];

         //get json array of   Iraq
        for (int i = 0; i < IraqArray.length(); i++) {
            Iraq[i] = IraqArray.getString(i);
        }
         //get json array of   Lebanon
        for (int i = 0; i < LebanonArray.length(); i++) {
            Lebanon[i] = LebanonArray.getString(i);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

如果有任何疑问,请询问我

答案 1 :(得分:0)

在微调器中添加菜单项

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="Select Week"
        app:actionViewClass="android.widget.Spinner"
        android:textColor="@android:color/white"
        android:textSize="11dp"
        app:showAsAction="always" />
</menu>

将你的json添加到数组列表

 public void onPostExecute(String response) {
        try {
            list.clear();
            MatchData vid = null;
            Gson gson = new Gson();
            JSONObject object = new JSONObject(response);
            JSONArray array = object.getJSONArray("items");
            for (int i = 0; i < array.length(); i++) {
                vid = gson.fromJson(array.getJSONObject(i).toString(), MatchData.class);

                list.add(vid);
            }
            matchDataAdapter = new MatchDataAdapter(MainActivity.this, list);
            mRecyclerView.setAdapter(matchDataAdapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }
}

最后将适配器设置为微调器

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);
        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);  

        **ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lists);**
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = (String) parent.getSelectedItem();
                Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG).show();
                week = Integer.parseInt(selected);
                requestforinfo();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return true;
    }

答案 2 :(得分:0)

你现在已经做了一切正确的事情。只需提出我的建议,你就可以使用很长的JSON数据列表。

首先通过在顶部声明来使整个活动/片段可以访问文件的JSON响应。

添加以下功能以检索特定国家/地区的cityList:

private ArrayList<String> getCityList(String countryName){
    ArrayList<String> cityList = new ArrayList<>();

    //Here jsonObj is the your JSON response from the file.
    try {
        JSONArray jArray =jsonObj.getJSONArray(countryName);

        for(int i=0;i<jArray.length();i++){
            cityList.add(jArray.getString(i));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return cityList;
}

然后在spinnerItemSelected上添加调用以下函数:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selected = ((SpinnerModel) parent.getSelectedItem()).getCountryName();

         //For sake of your answer I had used String Array and ArrayAdapter. You can modify as you want.
           ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(YourActivity.this, R.layout.single_textview,getCityList(selected));
           spinnerCity.setAdapter(cityAdapter);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });