来自原始文件的json值,并在android中显示除AutoCompleteTextView之外的edittext

时间:2017-05-06 06:54:04

标签: android android-activity

为国家代码及其对应的值制作的主类,使用了hashmap除了AutoCompleteTextView之外还有更好的方法吗

来自原始json文件的样本json值{"国家":{"国家":[{" 7840":0.1565},{" 7940& #34;:0.0497},{" 79407":0.1487},{" 79409":0.1487}

public class MainActivity extends AppCompatActivity {
    // private String mSource = "[{\"7840\":0.1565},{\"7940\":0.0497},{\"79407\":0.1487}]";
        private List<CountryCode> mCountryCodes = new ArrayList<>();
        private AutoCompleteTextView mEtKey;
        private EditText mEtValue;

        private CountryAdapter mAdapter;

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            parseJson();
            initViews();
        }
     private void initViews() {
            mEtKey = (AutoCompleteTextView) findViewById(R.id.etKey);

            mAdapter = new CountryAdapter(this, mCountryCodes);
            mEtKey.setAdapter(mAdapter);
    try {
    mEtKey.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mEtValue.setText(((CountryCode) parent.getAdapter().getItem(position)).getValue());
               // int value = Integer.parseInt(((CountryCode) parent.getAdapter().getItem(position)).getValue());
               // value = value / 1;
              //  mEtValue.setText(String.valueOf(value));

            }
        });
    }catch(Exception ex)
            {ex.printStackTrace();};

            mEtValue = (EditText) findViewById(R.id.etValue);
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        private void parseJson() {
            InputStream inputStream = getResources().openRawResource(R.raw.rates);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            int ctr;
            try {
                ctr = inputStream.read();
                while (ctr != -1) {
                    byteArrayOutputStream.write(ctr);
                    ctr = inputStream.read();
                }
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.v("Text Data", byteArrayOutputStream.toString());
            try {
                // Parse the data into jsonobject to get original data in form of json.
                JSONObject jObject = new JSONObject(
                        byteArrayOutputStream.toString());
                JSONObject jObjectResult = jObject.getJSONObject("countries");
                JSONArray jArray = jObjectResult.getJSONArray("country");
                String jsonStr = jArray.toString();

            try {
                JSONArray entries = new JSONArray(jsonStr);
                for (int i = 0; i < entries.length(); i++) {
                    JSONObject entry = entries.getJSONObject(i);
                    Iterator keys = entry.keys();
                    while (keys.hasNext()) {
                        String key = (String) keys.next();
                        mCountryCodes.add(new CountryCode(key, entry.getString(key)));
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } catch (JSONException e)
            {
                e.printStackTrace();
            }

        }}

Country ADAPTER - 用于从原始文件获取值的适配器活动,这是另一个用于生成适配器并动态获取值的活动。

public class CountryAdapter extends BaseAdapter implements Filterable {

    Context mContext;
    List<CountryCode> mItems, mTempItems, mSuggestions;
    /**
     * Custom Filter implementation for custom suggestions we provide.
     */
    Filter dialFilter = new Filter() {
        @Override
        public CharSequence convertResultToString(Object resultValue) {
            String str = ((CountryCode) resultValue).getKey();
            return str;
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            if (constraint != null) {
                mSuggestions.clear();
                for (CountryCode code : mTempItems) {
                    // First match against the whole, non-splitted value
                    if (code.getKey().startsWith(constraint.toString())) {
                        mSuggestions.add(code);
                    }
                }
                FilterResults filterResults = new FilterResults();
                filterResults.values = mSuggestions;
                filterResults.count = mSuggestions.size();
                return filterResults;
            } else {
                return new FilterResults();
            }
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            List<CountryCode> filterList = (ArrayList<CountryCode>) results.values;
            if (results != null && results.count > 0) {
                if (mSuggestions == null) {
                    mSuggestions = new ArrayList<>();
                }
                notifyDataSetChanged();
            }
        }
    };

    public CountryAdapter(Context context, List<CountryCode> objects) {
        this.mContext = context;
        this.mItems = objects;
        mTempItems = new ArrayList<CountryCode>(mItems);
        mSuggestions = new ArrayList<CountryCode>();
    }

    @Override
    public int getCount() {
        return mSuggestions.size();
    }

    @Override
    public CountryCode getItem(int position) {
        return mSuggestions.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.lyt_item, parent, false);
        }
        CountryCode code = mSuggestions.get(position);
        if (code != null) {
            TextView lblName = (TextView) view.findViewById(R.id.lbl_key);
            TextView lblValue = (TextView) view.findViewById(R.id.lbl_value);

            lblName.setText(code.getKey());
            lblValue.setText(code.getValue());
        }
        return view;
    }

    @Override
    public Filter getFilter() {
        return dialFilter;
    }
}

0 个答案:

没有答案