Example usage for android.widget ArrayAdapter getItem

List of usage examples for android.widget ArrayAdapter getItem

Introduction

In this page you can find the example usage for android.widget ArrayAdapter getItem.

Prototype

@Override
    public @Nullable T getItem(int position) 

Source Link

Usage

From source file:tw.com.geminihsu.app01.fragment.Fragment_PickUpTrain.java

private void setLister() {

    calendar = Calendar.getInstance();
    timePicker = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        }/* w ww .  ja v  a2 s .c  o  m*/
    };
    timerPicker.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new TimePickerDialog(getActivity(), timePicker, 24, 59, true).show();
        }
    });
    datePicker = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            date.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
        }

    };
    btn_datePicker.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new DatePickerDialog(getActivity(), datePicker, calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    radioGroup_orderTimetype.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == reservation.getId()) {
                linearLayout_date_picker.setVisibility(View.VISIBLE);
                linearLayout_time_picker.setVisibility(View.GONE);
            } else {
                linearLayout_date_picker.setVisibility(View.GONE);
                linearLayout_time_picker.setVisibility(View.VISIBLE);
            }
        }
    });

    radiogroup_destination_station.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == thsrStation.getId()) {
                getLocationFromDB("?");
            } else {

                getLocationFromDB("?");
            }
        }
    });

    radiogroup_leave_location.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == departure_thsr_train.getId()) {
                getLocationFromDB("?");
            } else {

                getLocationFromDB("?");
            }
        }
    });
    departure.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());

            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.select_dialog_item);
            arrayAdapter.add(getString(R.string.pop_map_option1));
            arrayAdapter.add(getString(R.string.pop_map_option2));

            builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String strName = arrayAdapter.getItem(which);

                    switch (which) {
                    case 0:
                        Intent map = new Intent(getActivity(), OrderMapActivity.class);
                        Bundle b = new Bundle();
                        b.putInt(Constants.ARG_POSITION, Constants.DEPARTURE_QUERY_GPS);
                        map.putExtras(b);
                        startActivityForResult(map, Constants.DEPARTURE_QUERY_GPS);

                        break;
                    case 1:
                        Intent page = new Intent(getActivity(), BookmarksMapListActivity.class);
                        Bundle flag = new Bundle();
                        flag.putInt(Constants.ARG_POSITION, Constants.DEPARTURE_QUERY_BOOKMARK);
                        page.putExtras(flag);
                        startActivityForResult(page, Constants.DEPARTURE_QUERY_BOOKMARK);

                        break;
                    }
                }
            });
            builderSingle.show();
        }
    });

    stop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());

            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.select_dialog_item);
            arrayAdapter.add(getString(R.string.pop_map_option1));
            arrayAdapter.add(getString(R.string.pop_map_option2));

            builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String strName = arrayAdapter.getItem(which);

                    switch (which) {
                    case 0:
                        Intent map = new Intent(getActivity(), OrderMapActivity.class);
                        Bundle b = new Bundle();
                        b.putInt(Constants.ARG_POSITION, Constants.STOP_QUERY_GPS);
                        map.putExtras(b);
                        startActivityForResult(map, Constants.STOP_QUERY_GPS);

                        break;
                    case 1:
                        Intent page = new Intent(getActivity(), BookmarksMapListActivity.class);
                        Bundle flag = new Bundle();
                        flag.putInt(Constants.ARG_POSITION, Constants.STOP_QUERY_BOOKMARK);
                        page.putExtras(flag);
                        startActivityForResult(page, Constants.STOP_QUERY_BOOKMARK);

                        break;
                    }
                }
            });
            builderSingle.show();
        }
    });

    destination.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());

            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.select_dialog_item);
            arrayAdapter.add(getString(R.string.pop_map_option1));
            arrayAdapter.add(getString(R.string.pop_map_option2));

            builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String strName = arrayAdapter.getItem(which);

                    switch (which) {
                    case 0:
                        Intent map = new Intent(getActivity(), OrderMapActivity.class);
                        Bundle b = new Bundle();
                        b.putInt(Constants.ARG_POSITION, Constants.DESTINATION_QUERY_GPS);
                        map.putExtras(b);
                        startActivityForResult(map, Constants.DESTINATION_QUERY_GPS);

                        break;
                    case 1:
                        Intent page = new Intent(getActivity(), BookmarksMapListActivity.class);
                        Bundle flag = new Bundle();
                        flag.putInt(Constants.ARG_POSITION, Constants.DESTINATION_QUERY_BOOKMARK);
                        page.putExtras(flag);
                        startActivityForResult(page, Constants.DESTINATION_QUERY_BOOKMARK);

                        break;
                    }
                }
            });
            builderSingle.show();
        }
    });

    getDataFromDB();
    linearLayout_spec.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(getActivity());
            dialog.setContentView(R.layout.client_take_ride_selectspec_requirement);
            dialog.setTitle(getString(R.string.txt_take_spec));
            Button cancel = (Button) dialog.findViewById(R.id.button_category_cancel);
            Button ok = (Button) dialog.findViewById(R.id.button_category_ok);

            //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // set the custom dialog components - text, image and button
            ListView requirement = (ListView) dialog.findViewById(R.id.listViewDialog);

            requirement.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                    ClientTakeRideSelectSpecListItem item = mCommentListData.get(position);
                    item.check = !item.check;
                    mCommentListData.set(position, item);
                    listViewAdapter.notifyDataSetChanged();
                }
            });

            if (listViewAdapter == null) {
                listViewAdapter = new ClientTakeRideSelectSpecListItemAdapter(getActivity(), 0,
                        mCommentListData);

            }
            requirement.setAdapter(listViewAdapter);
            listViewAdapter.notifyDataSetChanged();

            dialog.show();
            cancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dialog.cancel();
                }
            });

            String require;
            ok.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    String require = "";
                    for (ClientTakeRideSelectSpecListItem item : mCommentListData) {
                        if (item.check) {
                            spec_list.add(item);
                            require += item.book_title + ",";
                        }
                    }

                    if (!require.isEmpty())
                        require = require.substring(0, require.length() - 1);
                    spec_value.setText(require);
                    dialog.cancel();
                }
            });

        }
    });

    spec.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(getActivity());
            dialog.setContentView(R.layout.client_take_ride_selectspec_requirement);
            dialog.setTitle(getString(R.string.txt_take_spec));
            Button cancel = (Button) dialog.findViewById(R.id.button_category_ok);

            //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // set the custom dialog components - text, image and button
            ListView requirement = (ListView) dialog.findViewById(R.id.listViewDialog);

            getDataFromDB();
            listViewAdapter = new ClientTakeRideSelectSpecListItemAdapter(getActivity(), 0, mCommentListData);
            requirement.setAdapter(listViewAdapter);
            listViewAdapter.notifyDataSetChanged();

            dialog.show();
            cancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dialog.cancel();
                }
            });

        }
    });

    spinner_go_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapter, View v, int position, long id) {
            currentLocation = tainStationList.get(position);
            destination_detail = new LocationAddress();
            destination_detail.setLongitude(Double.parseDouble(currentLocation.getLng()));
            destination_detail.setLatitude(Double.parseDouble(currentLocation.getLat()));
            destination_detail.setAddress(currentLocation.getStreetAddress().substring(3,
                    currentLocation.getStreetAddress().length()));
            destination_detail.setLocation(currentLocation.getLocation());
            String zipCpde = (getTrainStationZip(currentLocation.getLocation()));
            destination_detail.setZipCode(zipCpde);
            destination_detail.setCountryName("Taiwan");
            destination_detail.setLocality(currentLocation.getStreetAddress());
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

    spinner_departure.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapter, View v, int position, long id) {
            currentLocation = tainStationList.get(position);
            departure_detail = new LocationAddress();
            departure_detail.setLongitude(Double.parseDouble(currentLocation.getLng()));
            departure_detail.setLatitude(Double.parseDouble(currentLocation.getLat()));
            departure_detail.setAddress(currentLocation.getStreetAddress().substring(3,
                    currentLocation.getStreetAddress().length()));
            departure_detail.setLocation(currentLocation.getLocation());
            //departure_detail.setZipCode(currentLocation.getStreetAddress().substring(0,3));
            String zipCode = (getTrainStationZip(currentLocation.getLocation()));
            departure_detail.setZipCode(zipCode);
            departure_detail.setCountryName("Taiwan");
            departure_detail.setLocality(currentLocation.getStreetAddress());
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });
}

From source file:uk.org.ngo.squeezer.NowPlayingFragment.java

/**
 * Manages the list of connected players in the action bar.
 *
 * @param players A list of players to show. May be empty (use {@code
 * Collections.&lt;Player>emptyList()}) but not null.
 * @param activePlayer The currently active player. May be null.
 *//*  www  . j ava2  s.  c  om*/
@UiThread
private void updatePlayerDropDown(@NonNull Collection<Player> players, @Nullable Player activePlayer) {
    if (!isAdded()) {
        return;
    }

    // Only include players that are connected to the server.
    ArrayList<Player> connectedPlayers = new ArrayList<Player>();
    for (Player player : players) {
        if (player.getConnected()) {
            connectedPlayers.add(player);
        }
    }

    ActionBar actionBar = mActivity.getSupportActionBar();

    // If there are multiple players connected then show a spinner allowing the user to
    // choose between them.
    if (connectedPlayers.size() > 1) {
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        final ArrayAdapter<Player> playerAdapter = new ArrayAdapter<Player>(actionBar.getThemedContext(),
                android.R.layout.simple_spinner_dropdown_item, connectedPlayers) {
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                return Util.getActionBarSpinnerItemView(getContext(), convertView, parent,
                        getItem(position).getName());
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                return Util.getActionBarSpinnerItemView(getContext(), convertView, parent,
                        getItem(position).getName());
            }
        };
        actionBar.setListNavigationCallbacks(playerAdapter, new ActionBar.OnNavigationListener() {
            @Override
            public boolean onNavigationItemSelected(int position, long id) {
                if (!playerAdapter.getItem(position).equals(mService.getActivePlayer())) {
                    Log.i(TAG, "onNavigationItemSelected.setActivePlayer(" + playerAdapter.getItem(position)
                            + ")");
                    mService.setActivePlayer(playerAdapter.getItem(position));
                    updateUiFromPlayerState(mService.getActivePlayerState());
                }
                return true;
            }
        });
        if (activePlayer != null) {
            actionBar.setSelectedNavigationItem(playerAdapter.getPosition(activePlayer));
        }
    } else {
        // 0 or 1 players, disable the spinner, and either show the sole player in the
        // action bar, or the app name if there are no players.
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        if (connectedPlayers.size() == 1) {
            actionBar.setTitle(connectedPlayers.get(0).getName());
        } else {
            // TODO: Alert the user if there are no connected players.
            actionBar.setTitle(R.string.app_name);
        }
    }
}

From source file:eu.trentorise.smartcampus.jp.ItineraryChoicesFragment.java

@Override
public void onStart() {
    super.onStart();

    getSherlockActivity().getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

    TextView dateTextView = (TextView) getView().findViewById(R.id.choices_date);
    // Date dateDate = Utils.sjDateString2date(singleJourney.getDate());
    // dateTextView.setText(new SimpleDateFormat(Config.FORMAT_DATE_UI,
    // Locale.US).format(dateDate));
    dateTextView.setText(Utils.serverDate2UIDate(singleJourney.getDate()));

    TextView timeTextView = (TextView) getView().findViewById(R.id.choices_time);
    // Date timeDate =
    // Utils.sjTimeString2date(singleJourney.getDepartureTime());
    // timeTextView.setText(new SimpleDateFormat(Config.FORMAT_TIME_UI,
    // Locale.ITALY).format(timeDate));
    timeTextView.setText(Utils.serverTime2UITime(singleJourney.getDepartureTime()));

    TextView fromTextView = (TextView) getView().findViewById(R.id.choices_from);
    fromTextView.setText(singleJourney.getFrom().getName());

    TextView toTextView = (TextView) getView().findViewById(R.id.choices_to);
    toTextView.setText(singleJourney.getTo().getName());

    View itinerariesPromotedView = getView().findViewById(R.id.choices_promoted_layout);
    ListView itinerariesPromotedList = (ListView) getView().findViewById(R.id.choices_promoted_listView);
    ListView itinerariesList = (ListView) getView().findViewById(R.id.choices_listView);
    noItemsView = (LinearLayout) getView().findViewById(R.id.no_items_label);
    noItemsView.setVisibility(View.GONE);

    if (itinerariesPromotedAdapter == null) {
        itinerariesPromotedAdapter = new ItinerariesListAdapter(getSherlockActivity(),
                R.layout.itinerarychoices_row);
    }/*w w w. jav  a  2s . c  o  m*/
    itinerariesPromotedList.setAdapter(itinerariesPromotedAdapter);

    if (itinerariesAdapter == null) {
        itinerariesAdapter = new ItinerariesListAdapter(getSherlockActivity(), R.layout.itinerarychoices_row);
    }
    itinerariesList.setAdapter(itinerariesAdapter);

    if (!mLoaded) {
        SCAsyncTask<SingleJourney, Void, List<Itinerary>> task = new SCAsyncTask<SingleJourney, Void, List<Itinerary>>(
                getSherlockActivity(), new PlanNewJourneyProcessor(getSherlockActivity(), itinerariesList,
                        itinerariesAdapter, itinerariesPromotedView, itinerariesPromotedAdapter, noItemsView));
        task.execute(singleJourney);
        mLoaded = true;
    }

    AdapterView.OnItemClickListener onClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ArrayAdapter<Itinerary> adapter = null;
            if (parent.getId() == R.id.choices_promoted_listView) {
                adapter = itinerariesPromotedAdapter;
            } else if ((parent.getId() == R.id.choices_listView)) {
                adapter = itinerariesAdapter;
            }

            if (adapter != null) {
                // ActionBar actionBar =
                // getSherlockActivity().getSupportActionBar();
                //
                // // navigation mode tabs
                // if (actionBar.getNavigationMode() !=
                // ActionBar.NAVIGATION_MODE_TABS) {
                // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                // }
                //
                // actionBar.removeAllTabs();
                //
                // // Itinerary steps
                // ActionBar.Tab tab = actionBar.newTab();
                // tab.setText(R.string.tab_itinerary);
                // tab.setTabListener(new
                // TabListener<ItineraryFragment>(getSherlockActivity(),
                // "itinerary",
                // ItineraryFragment.class, null));
                // Bundle bundle = new Bundle();
                // bundle.putSerializable(ItineraryFragment.JOURNEY,
                // singleJourney);
                // bundle.putSerializable(ItineraryFragment.ITINERARY,
                // adapter.getItem(position));
                // tab.setTag(bundle);
                // actionBar.addTab(tab);
                //
                // // Itinerary map
                // tab = actionBar.newTab();
                // tab.setText(R.string.tab_map);
                // tab.setTabListener(new
                // TabListener<ItineraryFragment>(getSherlockActivity(),
                // "map",
                // ItineraryFragment.class, null));
                // bundle = new Bundle();
                // bundle.putSerializable(ItineraryFragment.JOURNEY,
                // singleJourney);
                // bundle.putSerializable(ItineraryFragment.ITINERARY,
                // adapter.getItem(position));
                // tab.setTag(bundle);
                // actionBar.addTab(tab);
                //
                // actionBar.selectTab(actionBar.getTabAt(0));

                FragmentTransaction fragmentTransaction = getSherlockActivity().getSupportFragmentManager()
                        .beginTransaction();
                Fragment fragment = ItineraryFragment.newInstance(singleJourney, adapter.getItem(position));
                fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                fragmentTransaction.replace(Config.mainlayout, fragment,
                        ItineraryChoicesFragment.this.getTag());
                fragmentTransaction.addToBackStack(fragment.getTag());
                fragmentTransaction.commit();
            }
        }
    };

    itinerariesPromotedList.setOnItemClickListener(onClickListener);
    itinerariesList.setOnItemClickListener(onClickListener);

    itinerariesPromotedAdapter.notifyDataSetChanged();
    itinerariesAdapter.notifyDataSetChanged();

    if (itinerariesPromotedAdapter.isEmpty()) {
        itinerariesPromotedView.setVisibility(View.GONE);
    } else {
        itinerariesPromotedView.setVisibility(View.VISIBLE);
    }

    if (itinerariesAdapter.isEmpty()) {
        itinerariesList.setVisibility(View.GONE);
    } else {
        itinerariesList.setVisibility(View.VISIBLE);
    }
}

From source file:com.nextgis.mobile.forms.DescriptionFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    this.setRetainInstance(true);

    View view = inflater.inflate(R.layout.descriptfragment, container, false);

    final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(),
            android.R.layout.simple_spinner_item);

    final Map<String, ArrayList<String>> mlCategories = new HashMap<String, ArrayList<String>>();
    //fill spinners from xml data

    XmlPullParser parser = Xml.newPullParser();
    try {//  w ww  . j  a v a  2  s .  com
        File file = new File(getActivity().getExternalFilesDir(null), "categories.xml");
        if (file != null) {
            if (!file.exists()) {
                createExternalStoragePrivateFile();
                file = new File(getActivity().getExternalFilesDir(null), "categories.xml");
            }

            InputStream in = new BufferedInputStream(new FileInputStream(file));

            InputStreamReader isr = new InputStreamReader(in);

            // auto-detect the encoding from the stream
            parser.setInput(isr);
            int eventType = parser.getEventType();
            String sCatVal = null;
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    String name = parser.getName();
                    if (name.equalsIgnoreCase("category")) {
                        sCatVal = parser.getAttributeValue(null, "name");
                        adapter.add(sCatVal);
                        mlCategories.put(sCatVal, new ArrayList<String>());
                    } else if (name.equalsIgnoreCase("subcategory")) {
                        if (sCatVal != null) {
                            String sSubCatVal = parser.getAttributeValue(null, "name");
                            mlCategories.get(sCatVal).add(sSubCatVal);
                        }
                    }
                    break;
                }
                eventType = parser.next();
            }

            if (in != null) {
                in.close();
            }
        }
    } catch (IOException e) {
        // TODO            
    } catch (Exception e) {
        // TODO
    }

    Spinner spinner = (Spinner) view.findViewById(R.id.spinner_cat);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            final Spinner subspinner = (Spinner) getView().findViewById(R.id.spinner_subcat);
            //subspinner
            String sCat = adapter.getItem(arg2).toString();
            TextView textview = (TextView) getView().findViewById(R.id.spinner_subcat_custom);
            if (sCat.equalsIgnoreCase("custom")) {
                //enable text item
                textview.setEnabled(true);
            } else {
                textview.setEnabled(false);
            }
            ArrayAdapter<String> subadapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_spinner_item, mlCategories.get(sCat));
            subadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            subspinner.setAdapter(subadapter);
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });

    onStoreValues();

    return view;
}

From source file:com.nextgis.maplibui.formcontrol.DoubleCombobox.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {
    mSubCombobox = new Spinner(getContext());
    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_LEVEL1_KEY);
    mSubFieldName = attributes.getString(JSON_FIELD_LEVEL2_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));

    String lastValue = null;//from ww w . j a  v  a  2  s  . c  o  m
    String subLastValue = null;
    if (ControlHelper.hasKey(savedState, mFieldName) && ControlHelper.hasKey(savedState, mSubFieldName)) {
        lastValue = savedState.getString(ControlHelper.getSavedStateKey(mFieldName));
        subLastValue = savedState.getString(ControlHelper.getSavedStateKey(mSubFieldName));
    } else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);
        int subColumn = featureCursor.getColumnIndex(mSubFieldName);
        if (column >= 0)
            lastValue = featureCursor.getString(column);
        if (subColumn >= 0)
            subLastValue = featureCursor.getString(subColumn);
    } else if (mIsShowLast) {
        lastValue = preferences.getString(mFieldName, null);
        subLastValue = preferences.getString(mSubFieldName, null);
    }

    JSONArray values = attributes.optJSONArray(JSON_VALUES_KEY);
    int defaultPosition = 0;
    int lastValuePosition = -1;
    int subLastValuePosition = -1;
    mAliasValueMap = new HashMap<>();
    mSubAliasValueMaps = new HashMap<>();
    mAliasSubListMap = new HashMap<>();

    final ArrayAdapter<String> comboboxAdapter = new ArrayAdapter<>(getContext(),
            R.layout.formtemplate_double_spinner);
    setAdapter(comboboxAdapter);

    if (values != null) {
        for (int j = 0; j < values.length(); j++) {
            JSONObject keyValue = values.getJSONObject(j);
            String value = keyValue.getString(JSON_VALUE_NAME_KEY);
            String valueAlias = keyValue.getString(JSON_VALUE_ALIAS_KEY);

            Map<String, String> subAliasValueMap = new HashMap<>();
            AliasList subAliasList = new AliasList();

            mAliasValueMap.put(valueAlias, value);
            mSubAliasValueMaps.put(valueAlias, subAliasValueMap);
            mAliasSubListMap.put(valueAlias, subAliasList);
            comboboxAdapter.add(valueAlias);

            if (keyValue.has(JSON_DEFAULT_KEY) && keyValue.getBoolean(JSON_DEFAULT_KEY))
                defaultPosition = j;

            if (null != lastValue && lastValue.equals(value)) // if modify data
                lastValuePosition = j;

            JSONArray subValues = keyValue.getJSONArray(JSON_VALUES_KEY);
            for (int k = 0; k < subValues.length(); k++) {
                JSONObject subKeyValue = subValues.getJSONObject(k);
                String subValue = subKeyValue.getString(JSON_VALUE_NAME_KEY);
                String subValueAlias = subKeyValue.getString(JSON_VALUE_ALIAS_KEY);

                subAliasValueMap.put(subValueAlias, subValue);
                subAliasList.aliasList.add(subValueAlias);

                if (subKeyValue.has(JSON_DEFAULT_KEY) && subKeyValue.getBoolean(JSON_DEFAULT_KEY))
                    subAliasList.defaultPosition = k;

                if (null != subLastValue && subLastValue.equals(subValue)) { // if modify data
                    lastValuePosition = j;
                    subLastValuePosition = k;
                }
            }
        }
    }

    setSelection(lastValuePosition >= 0 ? lastValuePosition : defaultPosition);
    final int subLastValuePositionFinal = subLastValuePosition;

    // The drop down view
    comboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    float minHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14,
            getResources().getDisplayMetrics());
    setPadding(0, (int) minHeight, 0, (int) minHeight);
    mSubCombobox.setPadding(0, (int) minHeight, 0, (int) minHeight);

    setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedValueAlias = comboboxAdapter.getItem(position);
            AliasList subAliasList = mAliasSubListMap.get(selectedValueAlias);

            ArrayAdapter<String> subComboboxAdapter = new ArrayAdapter<>(view.getContext(),
                    R.layout.formtemplate_double_spinner, subAliasList.aliasList);
            subComboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            mSubCombobox.setAdapter(subComboboxAdapter);
            mSubCombobox.setSelection(mFirstShow && subLastValuePositionFinal >= 0 ? subLastValuePositionFinal
                    : subAliasList.defaultPosition);

            if (mFirstShow) {
                mFirstShow = false;
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
}

From source file:org.cvasilak.jboss.mobile.admin.fragments.DeploymentsViewFragment.java

public void showRepositoryDeploymentsOptionsMenu() {
    progress = ProgressDialog.show(getSherlockActivity(), "", getString(R.string.queryingServer));

    application.getOperationsManager().fetchDeployments(null, new Callback() {
        @Override/*ww w .j  a  v a2 s .  c  o  m*/
        public void onSuccess(JsonElement reply) {
            progress.dismiss();

            String name, runtimeName, BYTES_VALUE;
            boolean enabled = false;

            JsonObject jsonObj = reply.getAsJsonObject();

            final ArrayAdapter<Deployment> repoAdapter = new ArrayAdapter<Deployment>(getActivity(),
                    android.R.layout.simple_list_item_single_choice);

            for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) {
                name = e.getKey();

                JsonObject detailsJsonObj = e.getValue().getAsJsonObject();

                if (detailsJsonObj.get("enabled") != null)
                    enabled = detailsJsonObj.get("enabled").getAsBoolean();

                runtimeName = detailsJsonObj.get("runtime-name").getAsString();

                // "content" : [{"hash" : { "BYTES_VALUE" : "Pb4xyzgJmsxruKEf5eGOLu6lBjw="}}],
                BYTES_VALUE = detailsJsonObj.get("content").getAsJsonArray().get(0).getAsJsonObject()
                        .get("hash").getAsJsonObject().get("BYTES_VALUE").getAsString();

                repoAdapter.add(new Deployment(name, runtimeName, enabled, BYTES_VALUE));
            }

            // time to display content repository
            AlertDialog.Builder filesDialog = new AlertDialog.Builder(getActivity());

            filesDialog.setTitle(R.string.add_deployment_from_repository);
            filesDialog.setSingleChoiceItems(repoAdapter, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // enable buttons if a deployment is clicked
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(true);
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                }
            });

            // Cancel Button
            filesDialog.setNegativeButton(R.string.cancel, null);

            // Add to Group Button
            filesDialog.setNeutralButton(R.string.add_to_group, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    int selectedPosition = ((AlertDialog) dialogInterface).getListView()
                            .getCheckedItemPosition();

                    addDeployment(repoAdapter.getItem(selectedPosition), false, Arrays.asList(group));
                }
            });

            // Add to Group and Enable Button
            filesDialog.setPositiveButton(R.string.add_to_group_enable, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    int selectedPosition = ((AlertDialog) dialogInterface).getListView()
                            .getCheckedItemPosition();

                    addDeployment(repoAdapter.getItem(selectedPosition), true, Arrays.asList(group));
                }
            });
            filesDialog.setCancelable(true);

            AlertDialog dialog = filesDialog.create();
            // initially show add* buttons disabled
            // wait until a deployment is enabled
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialogInterface) {
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(false);
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                }
            });

            dialog.show();
        }

        @Override
        public void onFailure(Exception e) {
            progress.dismiss();

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

            alertDialog.setTitle(R.string.dialog_error_title).setMessage(e.getMessage())
                    .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false)
                    .setIcon(android.R.drawable.ic_dialog_alert).show();

        }
    });
}

From source file:com.android.contacts.interactions.ImportDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final LayoutInflater dialogInflater = (LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Adapter that shows a list of string resources
    final ArrayAdapter<AdapterEntry> adapter = new ArrayAdapter<AdapterEntry>(getActivity(),
            R.layout.select_dialog_item) {

        @Override//from  w  w w.  j  a  v a  2  s .co m
        public View getView(int position, View convertView, ViewGroup parent) {
            final View result = convertView != null ? convertView
                    : dialogInflater.inflate(R.layout.select_dialog_item, parent, false);
            final TextView primaryText = (TextView) result.findViewById(R.id.primary_text);
            final TextView secondaryText = (TextView) result.findViewById(R.id.secondary_text);
            final AdapterEntry entry = getItem(position);
            secondaryText.setVisibility(View.GONE);
            if (entry.mChoiceResourceId == R.string.import_from_sim) {
                final CharSequence secondary = getSimSecondaryText(entry.mSim);
                if (TextUtils.isEmpty(secondary)) {
                    secondaryText.setVisibility(View.GONE);
                } else {
                    secondaryText.setText(secondary);
                    secondaryText.setVisibility(View.VISIBLE);
                }
            }
            primaryText.setText(entry.mLabel);
            return result;
        }

        CharSequence getSimSecondaryText(SimCard sim) {
            int count = getSimContactCount(sim);

            CharSequence phone = sim.getFormattedPhone();
            if (phone == null) {
                phone = sim.getPhone();
            }
            if (phone != null) {
                phone = sBidiFormatter.unicodeWrap(PhoneNumberUtilsCompat.createTtsSpannable(phone),
                        TextDirectionHeuristicsCompat.LTR);
            }

            if (count != -1 && phone != null) {
                // We use a template instead of format string so that the TTS span is preserved
                final CharSequence template = getResources()
                        .getQuantityString(R.plurals.import_from_sim_secondary_template, count);
                return TextUtils.expandTemplate(template, String.valueOf(count), phone);
            } else if (phone != null) {
                return phone;
            } else if (count != -1) {
                // count != -1
                return getResources().getQuantityString(R.plurals.import_from_sim_secondary_contact_count_fmt,
                        count, count);
            } else {
                return null;
            }
        }
    };

    addItems(adapter);

    final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final int resId = adapter.getItem(which).mChoiceResourceId;
            if (resId == R.string.import_from_sim) {
                handleSimImportRequest(adapter.getItem(which).mSim);
            } else if (resId == R.string.import_from_vcf_file) {
                handleImportRequest(resId, SimCard.NO_SUBSCRIPTION_ID);
            } else {
                Log.e(TAG, "Unexpected resource: " + getActivity().getResources().getResourceEntryName(resId));
            }
            dialog.dismiss();
        }
    };

    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), getTheme())
            .setTitle(R.string.dialog_import).setNegativeButton(android.R.string.cancel, null);
    if (adapter.isEmpty()) {
        // Handle edge case; e.g. SIM card was removed.
        builder.setMessage(R.string.nothing_to_import_message);
    } else {
        builder.setSingleChoiceItems(adapter, -1, clickListener);
    }

    return builder.create();
}

From source file:org.cvasilak.jboss.mobile.app.fragments.DeploymentsViewFragment.java

public void showRepositoryDeploymentsOptionsMenu() {
    ProgressDialogFragment.showDialog(getActivity(), R.string.queryingServer);

    application.getOperationsManager().fetchDeployments(null, new Callback() {
        @Override/*from  w w  w.  j  a  v a2  s .  c  o  m*/
        public void onSuccess(JsonElement reply) {
            ProgressDialogFragment.dismissDialog(getActivity());

            String name, runtimeName, BYTES_VALUE;
            boolean enabled = false;

            JsonObject jsonObj = reply.getAsJsonObject();

            final ArrayAdapter<Deployment> repoAdapter = new ArrayAdapter<Deployment>(getActivity(),
                    android.R.layout.select_dialog_singlechoice);

            for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) {
                name = e.getKey();

                JsonObject detailsJsonObj = e.getValue().getAsJsonObject();

                if (detailsJsonObj.get("enabled") != null)
                    enabled = detailsJsonObj.get("enabled").getAsBoolean();

                runtimeName = detailsJsonObj.get("runtime-name").getAsString();

                // "content" : [{"hash" : { "BYTES_VALUE" : "Pb4xyzgJmsxruKEf5eGOLu6lBjw="}}],
                BYTES_VALUE = detailsJsonObj.get("content").getAsJsonArray().get(0).getAsJsonObject()
                        .get("hash").getAsJsonObject().get("BYTES_VALUE").getAsString();

                repoAdapter.add(new Deployment(name, runtimeName, enabled, BYTES_VALUE));
            }

            selectedAlertDialogItemPos = -1; // reset any previous selected value

            // time to display content repository
            AlertDialog.Builder filesDialog = new AlertDialog.Builder(getActivity());

            filesDialog.setTitle(R.string.add_deployment_from_repository);
            filesDialog.setSingleChoiceItems(repoAdapter, selectedAlertDialogItemPos,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            selectedAlertDialogItemPos = ((AlertDialog) dialogInterface).getListView()
                                    .getCheckedItemPosition();

                            // enable buttons if a deployment is clicked
                            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL)
                                    .setEnabled(true);
                            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE)
                                    .setEnabled(true);
                        }
                    });

            // Cancel Button
            filesDialog.setNegativeButton(R.string.cancel, null);

            // Add to Group Button
            filesDialog.setNeutralButton(R.string.add_to_group, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    addDeployment(repoAdapter.getItem(selectedAlertDialogItemPos), false, Arrays.asList(group));
                }
            });

            // Add to Group and Enable Button
            filesDialog.setPositiveButton(R.string.add_to_group_enable, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    addDeployment(repoAdapter.getItem(selectedAlertDialogItemPos), true, Arrays.asList(group));
                }
            });
            filesDialog.setCancelable(true);

            ParameterizedDialogFragment dialog = new ParameterizedDialogFragment(filesDialog,
                    new DialogInterface.OnShowListener() {
                        @Override
                        public void onShow(DialogInterface dialogInterface) {
                            ((AlertDialog) dialogInterface).getListView()
                                    .setItemChecked(selectedAlertDialogItemPos, true);

                            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL)
                                    .setEnabled(selectedAlertDialogItemPos != -1);
                            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE)
                                    .setEnabled(selectedAlertDialogItemPos != -1);
                        }
                    });

            dialog.show(getActivity().getSupportFragmentManager(), null);
        }

        @Override
        public void onFailure(Exception e) {
            ProgressDialogFragment.dismissDialog(getActivity());

            ErrorDialogFragment.showDialog(getActivity(), e.getMessage());
        }
    });
}

From source file:de.uni_koblenz_landau.apow.PatientDetailEditFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.patient_detail_edit_fragment, container, false);

    // Create UI references.
    mBirthDateDialog = (DateDialogFragment) getFragmentManager().findFragmentByTag(BIRTHDATE_DIALOG_ID);
    if (mBirthDateDialog != null) {
        mBirthDateDialog.setListener(this);
    }/*from  www . j a v a  2 s  .co  m*/
    mDeathDateDialog = (DateDialogFragment) getFragmentManager().findFragmentByTag(DEATHDATE_DIALOG_ID);
    if (mDeathDateDialog != null) {
        mDeathDateDialog.setListener(this);
    }

    mIdentifierView = (EditText) view.findViewById(R.id.patient_detail_edit_identifier);
    mNamePrefixView = (EditText) view.findViewById(R.id.patient_detail_edit_name_prefix);
    mGivenNameView = (EditText) view.findViewById(R.id.patient_detail_edit_name_given_name);
    mMiddleNameView = (EditText) view.findViewById(R.id.patient_detail_edit_name_middle_name);
    mFamilyNamePrefixView = (EditText) view.findViewById(R.id.patient_detail_edit_name_family_name_prefix);
    mFamilyNameView = (EditText) view.findViewById(R.id.patient_detail_edit_name_family_name);
    mFamilyName2View = (EditText) view.findViewById(R.id.patient_detail_edit_name_family_name2);
    mFamilyNameSuffixView = (EditText) view.findViewById(R.id.patient_detail_edit_name_family_name_suffix);
    mDegreeView = (EditText) view.findViewById(R.id.patient_detail_edit_name_degree);
    mGenderView = (Spinner) view.findViewById(R.id.patient_detail_edit_gender);
    mBirthdateView = (TextView) view.findViewById(R.id.patient_detail_edit_birthdate);
    mBirthdateEstimatedView = (CheckBox) view.findViewById(R.id.patient_detail_edit_birthdate_estimated);
    mAddress1View = (EditText) view.findViewById(R.id.patient_detail_edit_address_address1);
    mAddress2View = (EditText) view.findViewById(R.id.patient_detail_edit_address_address2);
    mCityVillageView = (EditText) view.findViewById(R.id.patient_detail_edit_address_cityvillage);
    mDistrictsView = (Spinner) view.findViewById(R.id.patient_detail_edit_address_district);
    mRegionsView = (Spinner) view.findViewById(R.id.patient_detail_edit_address_region);
    mRegionsView.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            Region region = (Region) parent.getItemAtPosition(pos);
            ArrayAdapter<District> adapter = new ArrayAdapter<>(getActivity(),
                    android.R.layout.simple_spinner_item, region.getDistricts());
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mDistrictsView.setAdapter(adapter);

            if (parent.getTag() != null) {
                mDistrictsView.setSelection((int) parent.getTag());
                parent.setTag(null);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    mCountryView = (EditText) view.findViewById(R.id.patient_detail_edit_address_country);
    mLongitudeView = (EditText) view.findViewById(R.id.patient_detail_edit_address_longitude);
    mLatitudeView = (EditText) view.findViewById(R.id.patient_detail_edit_address_latitude);
    mDeathdateView = (TextView) view.findViewById(R.id.patient_detail_edit_deathdate);
    mDeadLayout = (LinearLayout) view.findViewById(R.id.patient_detail_edit_dead_group);

    mDeadLayout = (LinearLayout) view.findViewById(R.id.patient_detail_edit_dead_group);
    mDeadView = (CheckBox) view.findViewById(R.id.patient_detail_edit_dead);
    mDeadView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckBox dead = (CheckBox) v;
            if (dead.isChecked()) {
                mDeadLayout.setVisibility(View.VISIBLE);
            } else {
                mDeadLayout.setVisibility(View.GONE);
            }
        }
    });

    // Restore UI from saved instance or load data.
    if (savedInstanceState != null) {
        mPatient = (Patient) savedInstanceState.getSerializable(ARG_PATIENT);
        if (mPatient != null) {
            mRegions = (List<Region>) savedInstanceState.getSerializable(ARG_REGIONS);
            ArrayAdapter<Region> adapter = new ArrayAdapter<>(getActivity(),
                    android.R.layout.simple_spinner_item, mRegions);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mRegionsView.setAdapter(adapter);
            ArrayAdapter<District> adapter1 = new ArrayAdapter<>(getActivity(),
                    android.R.layout.simple_spinner_item, mRegions.get(0).getDistricts());
            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mDistrictsView.setAdapter(adapter1);

            String selectedRegion = savedInstanceState.getString(ARG_SELECTED_REGION);
            String selectedDistrict = savedInstanceState.getString(ARG_SELECTED_DISTRICT);
            for (int i = 0; i < adapter.getCount(); i++) {
                Region region = adapter.getItem(i);
                if (region.getRegionName().equals(selectedRegion)) {
                    for (int j = 0; j < region.getDistricts().size(); j++) {
                        if (region.getDistricts().get(j).getDistrictName().equals(selectedDistrict)) {
                            mRegionsView.setTag(j);
                            mRegionsView.setSelection(i, false);
                            adapter1 = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item,
                                    region.getDistricts());
                            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            mDistrictsView.setAdapter(adapter1);
                            mDistrictsView.setSelection(j, false);
                            break;
                        }
                    }
                    break;
                }
            }

            if (savedInstanceState.getBoolean(ARG_DEAD)) {
                mDeadLayout.setVisibility(View.VISIBLE);
            } else {
                mDeadLayout.setVisibility(View.GONE);
            }
        }
    } else {
        loadPatient();
    }

    return view;
}

From source file:de.uni_koblenz_landau.apow.PatientDetailEditFragment.java

/**
 * Called by EncounterDetailTask, when loading is finished.
 *//*from ww  w . jav a  2s .c om*/
@Override
public void onPatientFetched(Patient patient, List<Region> regions) {
    mPatientDetailTask = null;

    // If result is not empty, update UI, else show error message.
    if (regions != null) {
        mRegions = regions;
        ArrayAdapter<Region> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item,
                regions);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mRegionsView.setAdapter(adapter);
        ArrayAdapter<District> adapter1 = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_spinner_item, regions.get(0).getDistricts());
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mDistrictsView.setAdapter(adapter1);

        if (patient != null) {
            mPatient = patient;
            if (mPatient.getPatientIdentifier() != null) {
                Helper.setViewText(mIdentifierView, mPatient.getPatientIdentifier().getIdentifier());
            }

            if (mPatient.getPersonName() != null) {
                getActivity().setTitle(mPatient.getPersonName().getFullName());
                Helper.setViewText(mNamePrefixView, mPatient.getPersonName().getPrefix());
                Helper.setViewText(mGivenNameView, mPatient.getPersonName().getGivenName());
                Helper.setViewText(mMiddleNameView, mPatient.getPersonName().getMiddleName());
                Helper.setViewText(mFamilyNamePrefixView, mPatient.getPersonName().getFamilyNamePrefix());
                Helper.setViewText(mFamilyNameView, mPatient.getPersonName().getFamilyName());
                Helper.setViewText(mFamilyName2View, mPatient.getPersonName().getFamilyName2());
                Helper.setViewText(mFamilyNameSuffixView, mPatient.getPersonName().getFamilyNameSuffix());
                Helper.setViewText(mDegreeView, mPatient.getPersonName().getDegree());
            }

            if (mPatient.getGender() != null) {
                switch (mPatient.getGender()) {
                case "U":
                    mGenderView.setSelection(0);
                    break;
                case "F":
                    mGenderView.setSelection(1);
                    break;
                case "M":
                    mGenderView.setSelection(2);
                    break;
                }
            } else {
                mGenderView.setSelection(0);
            }
            if (mPatient.getBirthdate() != null) {
                Helper.setViewText(mBirthdateView,
                        Helper.dateToLocaleString(mPatient.getBirthdate(), getActivity()));
            }
            mBirthdateEstimatedView.setChecked(mPatient.isBirthdateEstimated());
            if (mPatient.getPersonAddress() != null) {
                Helper.setViewText(mAddress1View, mPatient.getPersonAddress().getAddress1());
                Helper.setViewText(mAddress2View, mPatient.getPersonAddress().getAddress2());
                Helper.setViewText(mCityVillageView, mPatient.getPersonAddress().getCityVillage());

                String selectedRegion = mPatient.getPersonAddress().getStateProvince();
                String selectedDistrict = mPatient.getPersonAddress().getCountyDistrict();
                for (int i = 0; i < adapter.getCount(); i++) {
                    Region region = adapter.getItem(i);
                    if (region.getRegionName().equals(selectedRegion)) {
                        for (int j = 0; j < region.getDistricts().size(); j++) {
                            if (region.getDistricts().get(j).getDistrictName().equals(selectedDistrict)) {
                                mRegionsView.setTag(j);
                                mRegionsView.setSelection(i, false);
                                adapter1 = new ArrayAdapter<>(getActivity(),
                                        android.R.layout.simple_spinner_item, region.getDistricts());
                                adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                mDistrictsView.setAdapter(adapter1);
                                mDistrictsView.setSelection(j, false);
                                break;
                            }
                        }
                        break;
                    }
                }
                Helper.setViewText(mCountryView, mPatient.getPersonAddress().getCountry());
                Helper.setViewText(mLongitudeView, mPatient.getPersonAddress().getLongitude());
                Helper.setViewText(mLatitudeView, mPatient.getPersonAddress().getLatitude());
            }

            mDeadView.setChecked(mPatient.getDead());
            if (mPatient.getDead()) {
                if (mPatient.getDeathDate() != null) {
                    Helper.setViewText(mDeathdateView,
                            Helper.dateToLocaleString(mPatient.getDeathDate(), getActivity()));
                }
                mDeadLayout.setVisibility(View.VISIBLE);
            } else {
                mDeadLayout.setVisibility(View.GONE);
            }
        } else {
            mPatient = new Patient();
            PatientIdentifier patientIdentifier = new PatientIdentifier();
            PatientIdentifierType patientIdentifierType = new PatientIdentifierType();
            patientIdentifierType.setName(Constants.IDENTIFIER_TYPE_NAME);
            patientIdentifier.setIdentifierType(patientIdentifierType);
            mPatient.addIdentifier(patientIdentifier);
            PersonName personName = new PersonName();
            mPatient.addName(personName);
            PersonAddress personAddress = new PersonAddress();
            mPatient.addAddress(personAddress);
        }
    } else {
        Toast.makeText(getActivity(), R.string.error_database, Toast.LENGTH_SHORT).show();
    }
}