【问题标题】:How to set Assets json file data in two spinner + android?如何在两个 spinner + android 中设置 Assets json 文件数据?
【发布时间】:2017-07-22 05:37:32
【问题描述】:

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 扩展 Activity {

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

}

【问题讨论】:

  • 到目前为止你尝试了什么??
  • 我更新了我的问题和广告代码,您能看到并回复我吗?

标签: android json


【解决方案1】:

试试这个可以帮助你的代码

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

如有任何疑问,请咨询我

【讨论】:

  • 我想在微调器中添加国家名称,并在此基础上设置城市名称。这里只有两个国家,例如 json,但 json 中有很多长列表
  • 比发送你所有的 json 和上面的代码是 jsut 示例锄头从资产中读取 json
  • 可以分享你所有的json吗
  • Json 文件数据用于记录近 190 个国家/地区列表,因此我无法对其提出质疑,但我仅在我的问题中分享了该 json 文件的演示
  • 请查收邮件,我发给你
【解决方案2】:

在微调器中添加菜单项

<?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;
    }

【讨论】:

    【解决方案3】:

    到目前为止,您所做的一切都是正确的。只要提出我的建议,您就可以使用一长串 JSON 数据。

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

    添加了以下功能来检索特定国家的城市列表:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      相关资源
      最近更新 更多