Example usage for android.os Bundle getSerializable

List of usage examples for android.os Bundle getSerializable

Introduction

In this page you can find the example usage for android.os Bundle getSerializable.

Prototype

@Override
@Nullable
public Serializable getSerializable(@Nullable String key) 

Source Link

Document

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Usage

From source file:com.microsoft.aad.adal.AuthenticationContext.java

/**
 * This method wraps the implementation for onActivityResult at the related
 * Activity class. This method is called at UI thread.
 * //from  w ww  .j  av a2 s  .c  o  m
 * @param requestCode Request code provided at the start of the activity.
 * @param resultCode Result code set from the activity.
 * @param data {@link Intent}
 */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // This is called at UI thread when Activity sets result back.
    // ResultCode is set back from AuthenticationActivity. RequestCode is
    // set when we start the activity for result.
    if (requestCode == AuthenticationConstants.UIRequest.BROWSER_FLOW) {
        if (data == null) {
            // If data is null, RequestId is unknown. It could not find
            // callback to respond to this request.
            Logger.e(TAG, "onActivityResult BROWSER_FLOW data is null.", "",
                    ADALError.ON_ACTIVITY_RESULT_INTENT_NULL);
        } else {
            Bundle extras = data.getExtras();
            final int requestId = extras.getInt(AuthenticationConstants.Browser.REQUEST_ID);
            final AuthenticationRequestState waitingRequest = getWaitingRequest(requestId);
            if (waitingRequest != null) {
                Logger.v(TAG, "onActivityResult RequestId:" + requestId);
            } else {
                Logger.e(TAG, "onActivityResult did not find waiting request for RequestId:" + requestId, "",
                        ADALError.ON_ACTIVITY_RESULT_INTENT_NULL);
                // There is no matching callback to send error
                return;
            }

            // Cancel or browser error can use recorded request to figure
            // out original correlationId send with request.
            String correlationInfo = getCorrelationInfoFromWaitingRequest(waitingRequest);
            if (resultCode == AuthenticationConstants.UIResponse.TOKEN_BROKER_RESPONSE) {
                String accessToken = data.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_ACCESS_TOKEN);
                String accountName = data.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_NAME);
                mBrokerProxy.saveAccount(accountName);
                long expireTime = data.getLongExtra(AuthenticationConstants.Broker.ACCOUNT_EXPIREDATE, 0);
                Date expire = new Date(expireTime);
                UserInfo userinfo = UserInfo.getUserInfoFromBrokerResult(data.getExtras());
                AuthenticationResult brokerResult = new AuthenticationResult(accessToken, null, expire, false,
                        userinfo, "", "");
                if (brokerResult != null && brokerResult.getAccessToken() != null) {
                    waitingRequest.mDelagete.onSuccess(brokerResult);
                    return;
                }
            } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL) {
                // User cancelled the flow by clicking back button or
                // activating another activity
                Logger.v(TAG, "User cancelled the flow RequestId:" + requestId + correlationInfo);
                waitingRequestOnError(waitingRequest, requestId, new AuthenticationCancelError(
                        "User cancelled the flow RequestId:" + requestId + correlationInfo));
            } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_AUTHENTICATION_EXCEPTION) {
                Serializable authException = extras
                        .getSerializable(AuthenticationConstants.Browser.RESPONSE_AUTHENTICATION_EXCEPTION);
                if (authException != null && authException instanceof AuthenticationException) {
                    AuthenticationException exception = (AuthenticationException) authException;
                    Logger.w(TAG, "Webview returned exception", exception.getMessage(),
                            ADALError.WEBVIEW_RETURNED_AUTHENTICATION_EXCEPTION);
                    waitingRequestOnError(waitingRequest, requestId, exception);
                } else {
                    waitingRequestOnError(waitingRequest, requestId, new AuthenticationException(
                            ADALError.WEBVIEW_RETURNED_INVALID_AUTHENTICATION_EXCEPTION));
                }
            } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR) {
                String errCode = extras.getString(AuthenticationConstants.Browser.RESPONSE_ERROR_CODE);
                String errMessage = extras.getString(AuthenticationConstants.Browser.RESPONSE_ERROR_MESSAGE);
                Logger.v(TAG, "Error info:" + errCode + " " + errMessage + " for requestId: " + requestId
                        + correlationInfo);
                waitingRequestOnError(waitingRequest, requestId, new AuthenticationException(
                        ADALError.SERVER_INVALID_REQUEST, errCode + " " + errMessage));
            } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_COMPLETE) {
                final AuthenticationRequest authenticationRequest = (AuthenticationRequest) extras
                        .getSerializable(AuthenticationConstants.Browser.RESPONSE_REQUEST_INFO);
                final String endingUrl = extras.getString(AuthenticationConstants.Browser.RESPONSE_FINAL_URL);
                if (endingUrl.isEmpty()) {
                    AuthenticationException e = new AuthenticationException(
                            ADALError.WEBVIEW_RETURNED_EMPTY_REDIRECT_URL,
                            "Webview did not reach the redirectUrl. " + authenticationRequest.getLogInfo());
                    Logger.e(TAG, e.getMessage(), "", e.getCode());
                    waitingRequestOnError(waitingRequest, requestId, e);
                } else {
                    // Browser has the url and it will exchange auth code
                    // for token
                    final CallbackHandler callbackHandle = new CallbackHandler(mHandler,
                            waitingRequest.mDelagete);

                    // Executes all the calls inside the Runnable to return
                    // immediately to
                    // UI thread. All UI
                    // related actions will be performed using the Handler.
                    sThreadExecutor.submit(new Runnable() {

                        @Override
                        public void run() {
                            Logger.v(TAG, "Processing url for token. " + authenticationRequest.getLogInfo());
                            Oauth2 oauthRequest = new Oauth2(authenticationRequest, mWebRequest);
                            AuthenticationResult result = null;
                            try {
                                result = oauthRequest.getToken(endingUrl);
                                Logger.v(TAG, "OnActivityResult processed the result. "
                                        + authenticationRequest.getLogInfo());
                            } catch (Exception exc) {
                                String msg = "Error in processing code to get token. "
                                        + authenticationRequest.getLogInfo();
                                Logger.e(TAG, msg, ExceptionExtensions.getExceptionMessage(exc),
                                        ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, exc);

                                // Call error at UI thread
                                waitingRequestOnError(callbackHandle, waitingRequest, requestId,
                                        new AuthenticationException(
                                                ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, msg,
                                                exc));
                                return;
                            }

                            try {
                                if (result != null) {
                                    Logger.v(TAG, "OnActivityResult is setting the token to cache. "
                                            + authenticationRequest.getLogInfo());

                                    if (!StringExtensions.IsNullOrBlank(result.getAccessToken())) {
                                        setItemToCache(authenticationRequest, result, true);
                                    }

                                    if (waitingRequest != null && waitingRequest.mDelagete != null) {
                                        Logger.v(TAG, "Sending result to callback. "
                                                + authenticationRequest.getLogInfo());
                                        callbackHandle.onSuccess(result);
                                    }
                                } else {
                                    callbackHandle.onError(new AuthenticationException(
                                            ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN));
                                }
                            } finally {
                                removeWaitingRequest(requestId);
                            }
                        }
                    });
                }
            }
        }
    }
}

From source file:com.uncc.finalproject.AlbumGalleryFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
    rootView.setTag(TAG);/*from   w  w  w.jav  a 2s.com*/

    FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
    fab.setImageResource(R.drawable.ic_menu_share);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Select Users");
            builder.setMultiChoiceItems(charSequenceItems, primitive_boolean_selected,
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            primitive_boolean_selected[which] = isChecked;
                        }
                    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            albumACL = new ParseACL();
                            checked_counter = 0;

                            for (int counter = 0; counter < primitive_boolean_selected.length; counter++) {
                                albumACL.setReadAccess(user_ids.get(counter),
                                        primitive_boolean_selected[counter]);
                                albumACL.setWriteAccess(user_ids.get(counter),
                                        primitive_boolean_selected[counter]);
                                if (primitive_boolean_selected[counter])
                                    checked_counter++;
                            }

                            if (user_names.size() > checked_counter) {
                                Log.d("demo", "public " + user_names.size() + " > " + checked_counter);
                                albumACL.setPublicReadAccess(false);
                                albumACL.setPublicWriteAccess(false);
                            } else {
                                albumACL.setPublicReadAccess(true);
                                albumACL.setPublicWriteAccess(true);
                            }

                            albumACL.setReadAccess(ParseUser.getCurrentUser(), true);
                            albumACL.setWriteAccess(ParseUser.getCurrentUser(), true);

                            ParseQuery<ParseObject> album = ParseQuery.getQuery("Albums");
                            album.whereEqualTo("album_name", album_name);
                            album.getFirstInBackground(new GetCallback<ParseObject>() {
                                @Override
                                public void done(ParseObject object, ParseException e) {
                                    if (e == null) {
                                        object.setACL(albumACL);
                                        object.put("counterACL", checked_counter);
                                        object.saveInBackground();
                                        Toast.makeText(getActivity(), "Album Updated", Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                }
                            });
                        }
                    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    }).create().show();
        }
    });

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

    if (savedInstanceState != null) {
        mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState.getSerializable(KEY_LAYOUT_MANAGER);
    }

    setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
    mAdapter = new CustomAdapter(mDataset, getActivity(), getContext(), "photos");
    mRecyclerView.setAdapter(mAdapter);
    setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);

    return rootView;
}

From source file:com.nbplus.iotlib.IoTInterface.java

private void handleDeviceConnectedNotification(Bundle b) {
    if (b == null) {
        Log.w(TAG, "bundle data is null");
        return;/* w w  w  .j a  v a  2 s . co m*/
    }

    String deviceUuid = b.getString(IoTServiceCommand.KEY_DEVICE_UUID);
    if (StringUtils.isEmptyString(deviceUuid)) {
        Log.w(TAG, "deviceUuid is null");
        return;
    }

    if (mKeepAliveDeviceList.containsKey(deviceUuid)) {
        Log.d(TAG, "Keep alive device connection success.");
        mKeepAliveDeviceList.get(deviceUuid).setScenarioPosition(0);
        mKeepAliveDeviceList.get(deviceUuid)
                .setDeviceScenario(getKeepAliveDeviceScenario(mKeepAliveDeviceList.get(deviceUuid)));
        proceedKeepAliveDeviceCommand(deviceUuid);

        mBondedKeepaliveDeviceNumbers--;
        if (mBondedWithServerList.size() == 0
                || (mBondedEmergencyDeviceNumbers <= 0 && mBondedKeepaliveDeviceNumbers <= 0)) {
            Bundle extras = new Bundle();
            extras.putBoolean(IoTServiceCommand.KEY_DATA, false);
            sendMessageToService(IoTServiceCommand.SCANNING_STOP, extras);
        }
        return;
    }

    if (mCurrentRetrieveDevice == null || !deviceUuid.equals(mCurrentRetrieveDevice.getDeviceId())) {
        Log.w(TAG, "current retrieve device is empty or not matched..");
        if (mCurrentRetrieveDevice != null) {
            Log.w(TAG, "mCurrentRetrieveDevice.getDeviceId() = " + mCurrentRetrieveDevice.getDeviceId());
        }
        Log.w(TAG, "connected device getDeviceId() = " + deviceUuid);

        Bundle extras = new Bundle();
        IoTHandleData data = new IoTHandleData();
        data.setDeviceId(deviceUuid);
        //data.setDeviceTypeId(mCurrentRetrieveDevice.getDeviceTypeId());

        extras.putParcelable(IoTServiceCommand.KEY_DATA, data);
        sendMessageToService(IoTServiceCommand.DEVICE_DISCONNECT, extras);
        return;
    }

    mConnectionRetryCount = 0;
    b.setClassLoader(ArrayList.class.getClassLoader());
    HashMap<String, ArrayList<String>> disCoveredServices = (HashMap<String, ArrayList<String>>) b
            .getSerializable(IoTServiceCommand.KEY_DATA);
    if (disCoveredServices == null || disCoveredServices.size() == 0) {
        Log.w(TAG, "empty disCoveredServices list");
        Bundle extras = new Bundle();
        IoTHandleData data = new IoTHandleData();
        data.setDeviceId(deviceUuid);
        data.setDeviceTypeId(mCurrentRetrieveDevice.getDeviceTypeId());

        extras.putParcelable(IoTServiceCommand.KEY_DATA, data);
        sendMessageToService(IoTServiceCommand.DEVICE_DISCONNECT, extras);
        return;
    }

    // check.. has known scenario.
    ArrayList<IoTDeviceScenario> deviceScenario = null;
    mCurrentRetrieveDevice.setDiscoveredServices(disCoveredServices);
    if (mIsEmergencyDataCollecting) {
        deviceScenario = getEmergencyDeviceScenario(mCurrentRetrieveDevice);
    } else {
        deviceScenario = getKnownIoTDeviceScenarios(mCurrentRetrieveDevice);
    }

    if (deviceScenario == null) {
        Log.w(TAG, "I have no scenario for this device = " + mCurrentRetrieveDevice.getDeviceName());
        Bundle extras = new Bundle();
        IoTHandleData data = new IoTHandleData();
        data.setDeviceId(deviceUuid);
        data.setDeviceTypeId(mCurrentRetrieveDevice.getDeviceTypeId());

        extras.putParcelable(IoTServiceCommand.KEY_DATA, data);
        sendMessageToService(IoTServiceCommand.DEVICE_DISCONNECT, extras);
        return;
    }
    mCurrentRetrieveDevice.setDeviceScenario(deviceScenario);
    mCurrentRetrieveDevice.setScenarioPosition(0);

    proceedDeviceCommand();
}

From source file:edu.usf.cutr.opentripplanner.android.fragments.DirectionListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ImageButton btnDisplayMap = (ImageButton) header.findViewById(R.id.btnDisplayMap);
    ImageButton btnShareDirections = (ImageButton) header.findViewById(R.id.btnShareDirections);
    ImageButton btnAlarmDirections = (ImageButton) header.findViewById(R.id.btnAlarmDirections);
    final OtpFragment ofl = this.getFragmentListener();
    final DirectionListFragment dlf = this;
    OnClickListener oclDisplayDirection = new OnClickListener() {
        @Override/*from  w ww .  ja va 2s  .c o  m*/
        public void onClick(View arg0) {
            ofl.onSwitchedToMainFragment(dlf);
        }
    };
    btnDisplayMap.setOnClickListener(oclDisplayDirection);
    btnShareDirections.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            // create popup menu
            View menuItemView = getView().findViewById(R.id.btnShareDirections);
            PopupMenu popup = new PopupMenu(getActivity(), menuItemView);
            popup.getMenuInflater().inflate(R.menu.share_menu, popup.getMenu());
            menuItemView.setOnTouchListener(PopupMenuCompat.getDragToOpenListener(popup));

            //registering popup with OnMenuItemClickListener
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {

                    Intent itn = new Intent();
                    itn.setAction(Intent.ACTION_SEND);
                    itn.setType("text/plain");

                    // fill intend content based on chosen menu item
                    switch (item.getItemId()) {
                    case R.id.btnShareDirectionsShort:
                        itn.putExtra(Intent.EXTRA_TEXT, getDepartureArrivalHeaders(false));
                        break;
                    case R.id.btnShareDirectionsDetailed:
                        itn.putExtra(Intent.EXTRA_TEXT, getDepartureArrivalHeaders(true));
                        break;
                    default:
                        break;
                    }
                    startActivity(Intent.createChooser(itn, "Share via"));
                    return true;
                }
            });

            popup.show();
        }
    });
    btnAlarmDirections.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            // create popup menu
            View menuItemView = getView().findViewById(R.id.btnAlarmDirections);
            PopupMenu popup = new PopupMenu(getActivity(), menuItemView);
            popup.getMenuInflater().inflate(R.menu.alarm_menu, popup.getMenu());
            menuItemView.setOnTouchListener(PopupMenuCompat.getDragToOpenListener(popup));

            //registering popup with OnMenuItemClickListener
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {

                    switch (item.getItemId()) {
                    case R.id.btnAlarmDirectionsAlarm:
                        setAlarmItinerary();
                        break;
                    case R.id.btnAlarmDirectionsNotifications:
                        setNotificationsItinerary();
                        break;
                    case R.id.btnAlarmDirectionsCalendar:
                        setCalendarItinerary();
                        break;
                    default:
                        break;
                    }
                    return true;
                }
            });

            popup.show();
        }
    });

    fromHeader = (TextView) header.findViewById(R.id.fromHeader);
    toHeader = (TextView) header.findViewById(R.id.toHeader);
    departureTimeHeader = (TextView) header.findViewById(R.id.departureTimeHeader);
    arrivalTimeHeader = (TextView) header.findViewById(R.id.arrivalTimeHeader);
    tripList = (Spinner) header.findViewById(R.id.itinerarySelection);

    if (savedInstanceState != null) {
        otpBundle = (OTPBundle) savedInstanceState.getSerializable(OTPApp.BUNDLE_KEY_OTP_BUNDLE);
        fragmentListener.setOTPBundle(otpBundle);
    } else {
        otpBundle = fragmentListener.getOTPBundle();
    }

    fromHeader.setText(otpBundle.getFromText());
    toHeader.setText(otpBundle.getToText());
    setDepartureArrivalHeaders();

    ArrayList<Leg> currentItinerary = new ArrayList<Leg>();
    currentItinerary.addAll(fragmentListener.getCurrentItinerary());
    ArrayList<Itinerary> itineraryList = new ArrayList<Itinerary>();
    itineraryList.addAll(fragmentListener.getCurrentItineraryList());
    int currentItineraryIndex = fragmentListener.getCurrentItineraryIndex();

    ArrayList<Direction> directions = new ArrayList<Direction>();
    DirectionsGenerator dirGen = new DirectionsGenerator(currentItinerary,
            getActivity().getApplicationContext());
    ArrayList<Direction> tempDirections = dirGen.getDirections();
    if (tempDirections != null && !tempDirections.isEmpty()) {
        directions.addAll(tempDirections);
    }

    final Activity activity = this.getActivity();
    String[] itinerarySummaryList = new String[itineraryList.size()];

    boolean isTransitIsTagSet = false;
    for (int i = 0; i < itinerarySummaryList.length; i++) {
        isTransitIsTagSet = false;
        Itinerary it = itineraryList.get(i);
        for (Leg leg : it.legs) {
            TraverseMode traverseMode = TraverseMode.valueOf(leg.mode);
            if (traverseMode.isTransit()) {
                itinerarySummaryList[i] = ConversionUtils.getRouteShortNameSafe(leg.routeShortName,
                        leg.routeLongName, getActivity().getApplicationContext()) + ". ";
                isTransitIsTagSet = true;
                break;
            }
        }
        if (!isTransitIsTagSet) {
            itinerarySummaryList[i] = Integer.toString(i + 1) + ".   ";//Shown index is i + 1, to use 1-based indexes for the UI instead of 0-based
        }
    }

    for (int i = 0; i < itinerarySummaryList.length; i++) {
        Itinerary it = itineraryList.get(i);
        long tripDuration;
        if (PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext())
                .getInt(OTPApp.PREFERENCE_KEY_API_VERSION, OTPApp.API_VERSION_V1) == OTPApp.API_VERSION_V1) {
            tripDuration = it.duration;
        } else {
            tripDuration = it.duration / 1000;
        }
        itinerarySummaryList[i] += getString(R.string.step_by_step_total_duration) + " " + ConversionUtils
                .getFormattedDurationTextNoSeconds(tripDuration, false, getActivity().getApplicationContext());
        if (isTransitIsTagSet) {
            itinerarySummaryList[i] += "   " + getString(R.string.step_by_step_walking_duration) + " "
                    + ConversionUtils.getFormattedDurationTextNoSeconds(it.walkTime, false,
                            getActivity().getApplicationContext());
        }
    }

    ArrayAdapter<String> itineraryAdapter = new ArrayAdapter<String>(activity,
            android.R.layout.simple_spinner_item, itinerarySummaryList);

    itineraryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    tripList.setAdapter(itineraryAdapter);

    AdapterView.OnItemSelectedListener itinerarySpinnerListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (fragmentListener.getCurrentItineraryIndex() != position) {
                fragmentListener.onItinerarySelected(position, 3);
            }

            setDepartureArrivalHeaders();

            if (!isFragmentFirstLoad) {
                ArrayList<Direction> directions = new ArrayList<Direction>();
                DirectionsGenerator dirGen = new DirectionsGenerator(fragmentListener.getCurrentItinerary(),
                        getActivity().getApplicationContext());
                ArrayList<Direction> tempDirections = dirGen.getDirections();
                if (tempDirections != null && !tempDirections.isEmpty()) {
                    directions.addAll(tempDirections);
                }

                Direction direction_data[] = directions.toArray(new Direction[directions.size()]);

                DirectionExpandableListAdapter adapter = new DirectionExpandableListAdapter(
                        DirectionListFragment.this.getActivity(), R.layout.list_direction_item,
                        R.layout.list_subdirection_item, direction_data);

                elv.setAdapter(adapter);

            }
            openIfNonTransit();

            isFragmentFirstLoad = false;

        }

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

        }
    };
    tripList.setSelection(currentItineraryIndex);
    tripList.setOnItemSelectedListener(itinerarySpinnerListener);

    // Populate list with our static array of titles.
    elv = getExpandableListView();

    Direction direction_data[] = directions.toArray(new Direction[directions.size()]);

    DirectionExpandableListAdapter adapter = new DirectionExpandableListAdapter(this.getActivity(),
            R.layout.list_direction_item, R.layout.list_subdirection_item, direction_data);

    elv.addHeaderView(header);

    elv.setAdapter(adapter);

    elv.setGroupIndicator(null); // Get rid of the down arrow

    openIfNonTransit();

    if (savedInstanceState == null) {
        if (otpBundle.isFromInfoWindow()) {
            elv.expandGroup(otpBundle.getCurrentStepIndex());
            elv.setSelectedGroup(otpBundle.getCurrentStepIndex());
            otpBundle.setFromInfoWindow(false);
        }
    }
}

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);
    }// w  w  w  . j  ava2s  . com
    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:ch.bfh.evoting.alljoyn.BusHandler.java

@Override
public void handleMessage(Message msg) {
    Status status = null;/*  ww  w .jav a 2  s  . co  m*/
    Intent intent;
    switch (msg.what) {
    case INIT: {
        doInit();
        break;
    }
    case CREATE_GROUP: {
        Bundle data = msg.getData();
        String groupName = data.getString("groupName");
        String groupPassword = data.getString("groupPassword");
        status = doCreateGroup(groupName, groupPassword);
        Log.d(TAG, "status of group creation " + status);
        switch (status) {
        case OK:
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("NetworkServiceStarted"));
            break;
        case ALLJOYN_JOINSESSION_REPLY_ALREADY_JOINED:
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("NetworkServiceStarted"));
            break;
        case INVALID_DATA:
            //invalid group name
            intent = new Intent("networkConnectionFailed");
            intent.putExtra("error", 1);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            break;
        case ALREADY_FINDING:
            //group name already exists
            intent = new Intent("networkConnectionFailed");
            intent.putExtra("error", 2);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            break;
        default:
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("networkConnectionFailed"));
            break;
        }
        break;
    }
    case DESTROY_GROUP: {
        status = doDestroyGroup((String) msg.obj);
        break;
    }
    case JOIN_GROUP: {
        Bundle data = msg.getData();
        String groupName = data.getString("groupName");
        String groupPassword = data.getString("groupPassword");
        String saltShortDigest = data.getString("saltShortDigest");
        status = doJoinGroup(groupName, groupPassword, saltShortDigest);
        Log.d(TAG, "status of group join " + status);
        switch (status) {

        case OK:
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("NetworkServiceStarted"));
            break;
        case ALLJOYN_JOINSESSION_REPLY_ALREADY_JOINED:
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("NetworkServiceStarted"));
            break;
        case INVALID_DATA:
            //invalid group name
            intent = new Intent("networkConnectionFailed");
            intent.putExtra("error", 1);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            break;
        case ALLJOYN_FINDADVERTISEDNAME_REPLY_FAILED:
            //group not found
            intent = new Intent("networkConnectionFailed");
            intent.putExtra("error", 3);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

            break;
        case ALLJOYN_JOINSESSION_REPLY_FAILED:
            //group not joined
            intent = new Intent("networkConnectionFailed");
            intent.putExtra("error", 4);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            break;
        default:
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("networkConnectionFailed"));
            break;
        }
        break;
    }
    case LEAVE_GROUP: {
        status = doLeaveGroup((String) msg.obj);
        break;
    }
    case UNLOCK_GROUP: {
        status = doUnlockGroup((String) msg.obj);
        break;
    }
    case LOCK_GROUP: {
        status = doLockGroup((String) msg.obj);
        break;
    }
    case SET_PORT: {
        doSetPort((Short) msg.obj);
        break;
    }
    case JOIN_OR_CREATE: {
        status = doJoinOrCreate((String) msg.obj);
        break;
    }
    case PING: {
        Bundle data = msg.getData();
        String groupName = data.getString("groupName");
        String pingString = data.getString("pingString");
        boolean encrypted = data.getBoolean("encrypted", true);
        Type type = (Type) data.getSerializable("type");
        doPing(groupName, pingString, encrypted, type);
        break;
    }
    case REPROCESS_MESSAGE: {
        Bundle data = msg.getData();
        AllJoynMessage message = (AllJoynMessage) data.getSerializable("message");
        this.processMessage(message);
        break;
    }
    case DISCONNECT: {
        doDisconnect();
        break;
    }
    default:
        break;
    }
}

From source file:com.android.contacts.quickcontact.QuickContactActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Trace.beginSection("onCreate()");
    super.onCreate(savedInstanceState);

    if (RequestPermissionsActivity.startPermissionActivity(this)
            || RequestDesiredPermissionsActivity.startPermissionActivity(this)) {
        return;//from   w ww . jav  a 2 s  .  c  om
    }

    final int previousScreenType = getIntent().getIntExtra(EXTRA_PREVIOUS_SCREEN_TYPE, ScreenType.UNKNOWN);
    Logger.logScreenView(this, ScreenType.QUICK_CONTACT, previousScreenType);

    if (CompatUtils.isLollipopCompatible()) {
        getWindow().setStatusBarColor(Color.TRANSPARENT);
    }

    processIntent(getIntent());

    // Show QuickContact in front of soft input
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

    setContentView(R.layout.quickcontact_activity);

    mMaterialColorMapUtils = new MaterialColorMapUtils(getResources());

    mScroller = (MultiShrinkScroller) findViewById(R.id.multiscroller);

    mContactCard = (ExpandingEntryCardView) findViewById(R.id.communication_card);
    mNoContactDetailsCard = (ExpandingEntryCardView) findViewById(R.id.no_contact_data_card);
    mRecentCard = (ExpandingEntryCardView) findViewById(R.id.recent_card);
    mAboutCard = (ExpandingEntryCardView) findViewById(R.id.about_card);

    mCollapsedSuggestionCardView = (CardView) findViewById(R.id.collapsed_suggestion_card);
    mExpandSuggestionCardView = (CardView) findViewById(R.id.expand_suggestion_card);
    mCollapasedSuggestionHeader = findViewById(R.id.collapsed_suggestion_header);
    mCollapsedSuggestionCardTitle = (TextView) findViewById(R.id.collapsed_suggestion_card_title);
    mExpandSuggestionCardTitle = (TextView) findViewById(R.id.expand_suggestion_card_title);
    mSuggestionSummaryPhoto = (ImageView) findViewById(R.id.suggestion_icon);
    mSuggestionForName = (TextView) findViewById(R.id.suggestion_for_name);
    mSuggestionContactsNumber = (TextView) findViewById(R.id.suggestion_for_contacts_number);
    mSuggestionList = (LinearLayout) findViewById(R.id.suggestion_list);
    mSuggestionsCancelButton = (Button) findViewById(R.id.cancel_button);
    mSuggestionsLinkButton = (Button) findViewById(R.id.link_button);
    if (savedInstanceState != null) {
        mIsSuggestionListCollapsed = savedInstanceState.getBoolean(KEY_IS_SUGGESTION_LIST_COLLAPSED, true);
        mPreviousContactId = savedInstanceState.getLong(KEY_PREVIOUS_CONTACT_ID);
        mSuggestionsShouldAutoSelected = savedInstanceState.getBoolean(KEY_SUGGESTIONS_AUTO_SELECTED, true);
        mSelectedAggregationIds = (TreeSet<Long>) savedInstanceState
                .getSerializable(KEY_SELECTED_SUGGESTION_CONTACTS);
    } else {
        mIsSuggestionListCollapsed = true;
        mSelectedAggregationIds.clear();
    }
    if (mSelectedAggregationIds.isEmpty()) {
        disableLinkButton();
    } else {
        enableLinkButton();
    }
    mCollapasedSuggestionHeader.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            mCollapsedSuggestionCardView.setVisibility(View.GONE);
            mExpandSuggestionCardView.setVisibility(View.VISIBLE);
            mIsSuggestionListCollapsed = false;
            mExpandSuggestionCardTitle.requestFocus();
            mExpandSuggestionCardTitle.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
        }
    });

    mSuggestionsCancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            mCollapsedSuggestionCardView.setVisibility(View.VISIBLE);
            mExpandSuggestionCardView.setVisibility(View.GONE);
            mIsSuggestionListCollapsed = true;
        }
    });

    mNoContactDetailsCard.setOnClickListener(mEntryClickHandler);
    mContactCard.setOnClickListener(mEntryClickHandler);
    mContactCard.setExpandButtonText(getResources().getString(R.string.expanding_entry_card_view_see_all));
    mContactCard.setOnCreateContextMenuListener(mEntryContextMenuListener);

    mRecentCard.setOnClickListener(mEntryClickHandler);
    mRecentCard.setTitle(getResources().getString(R.string.recent_card_title));

    mAboutCard.setOnClickListener(mEntryClickHandler);
    mAboutCard.setOnCreateContextMenuListener(mEntryContextMenuListener);

    mPhotoView = (QuickContactImageView) findViewById(R.id.photo);
    final View transparentView = findViewById(R.id.transparent_view);
    if (mScroller != null) {
        transparentView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mScroller.scrollOffBottom();
            }
        });
    }

    // Allow a shadow to be shown under the toolbar.
    ViewUtil.addRectangularOutlineProvider(findViewById(R.id.toolbar_parent), getResources());

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setActionBar(toolbar);
    getActionBar().setTitle(null);
    // Put a TextView with a known resource id into the ActionBar. This allows us to easily
    // find the correct TextView location & size later.
    toolbar.addView(getLayoutInflater().inflate(R.layout.quickcontact_title_placeholder, null));

    mHasAlreadyBeenOpened = savedInstanceState != null;
    mIsEntranceAnimationFinished = mHasAlreadyBeenOpened;
    mWindowScrim = new ColorDrawable(SCRIM_COLOR);
    mWindowScrim.setAlpha(0);
    getWindow().setBackgroundDrawable(mWindowScrim);

    mScroller.initialize(mMultiShrinkScrollerListener, mExtraMode == MODE_FULLY_EXPANDED);
    // mScroller needs to perform asynchronous measurements after initalize(), therefore
    // we can't mark this as GONE.
    mScroller.setVisibility(View.INVISIBLE);

    setHeaderNameText(R.string.missing_name);

    mSelectAccountFragmentListener = (SelectAccountDialogFragmentListener) getFragmentManager()
            .findFragmentByTag(FRAGMENT_TAG_SELECT_ACCOUNT);
    if (mSelectAccountFragmentListener == null) {
        mSelectAccountFragmentListener = new SelectAccountDialogFragmentListener();
        getFragmentManager().beginTransaction()
                .add(0, mSelectAccountFragmentListener, FRAGMENT_TAG_SELECT_ACCOUNT).commit();
        mSelectAccountFragmentListener.setRetainInstance(true);
    }
    mSelectAccountFragmentListener.setQuickContactActivity(this);

    SchedulingUtils.doOnPreDraw(mScroller, /* drawNextFrame = */ true, new Runnable() {
        @Override
        public void run() {
            if (!mHasAlreadyBeenOpened) {
                // The initial scrim opacity must match the scrim opacity that would be
                // achieved by scrolling to the starting position.
                final float alphaRatio = mExtraMode == MODE_FULLY_EXPANDED ? 1
                        : mScroller.getStartingTransparentHeightRatio();
                final int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
                final int desiredAlpha = (int) (0xFF * alphaRatio);
                ObjectAnimator o = ObjectAnimator.ofInt(mWindowScrim, "alpha", 0, desiredAlpha)
                        .setDuration(duration);

                o.start();
            }
        }
    });

    if (savedInstanceState != null) {
        final int color = savedInstanceState.getInt(KEY_THEME_COLOR, 0);
        SchedulingUtils.doOnPreDraw(mScroller, /* drawNextFrame = */ false, new Runnable() {
            @Override
            public void run() {
                // Need to wait for the pre draw before setting the initial scroll
                // value. Prior to pre draw all scroll values are invalid.
                if (mHasAlreadyBeenOpened) {
                    mScroller.setVisibility(View.VISIBLE);
                    mScroller.setScroll(mScroller.getScrollNeededToBeFullScreen());
                }
                // Need to wait for pre draw for setting the theme color. Setting the
                // header tint before the MultiShrinkScroller has been measured will
                // cause incorrect tinting calculations.
                if (color != 0) {
                    setThemeColor(mMaterialColorMapUtils.calculatePrimaryAndSecondaryColor(color));
                }
            }
        });
    }

    Trace.endSection();
}

From source file:com.lastsoft.plog.GamesFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_games, container, false);

    rootView.setTag(TAG);//from  w ww .  jav a  2s. c  o  m

    // BEGIN_INCLUDE(initializeRecyclerView)
    mCoordinatorLayout = (CoordinatorLayout) rootView.findViewById(R.id.coordinatorLayout);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mRecyclerView.setBackgroundColor(getResources().getColor(R.color.cardview_initial_background));
    pullToRefreshView = (SwipeRefreshLayout) rootView.findViewById(R.id.pull_to_refresh_listview);
    pullToRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            initDataset(true);
        }
    });

    RecyclerFastScroller fastScroller = (RecyclerFastScroller) rootView.findViewById(R.id.fastscroller);
    fastScroller.attachRecyclerView(mRecyclerView);
    //fastScroller = (VerticalRecyclerViewFastScroller) rootView.findViewById(R.id.fastscroller);

    // Connect the recycler to the scroller (to let the scroller scroll the list)
    //fastScroller.setRecyclerView(mRecyclerView, pullToRefreshView);

    // Connect the scroller to the recycler (to let the recycler scroll the scroller's handle)
    //mRecyclerView.setOnScrollListener(fastScroller.getOnScrollListener());

    addPlayer = (FloatingActionButton) rootView.findViewById(R.id.add_game);
    if (fromDrawer && playListType != 2) {
        //fastScroller.setRecyclerView(mRecyclerView, pullToRefreshView);
        mRecyclerView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean enable = false;
                boolean firstItemVisiblePull = recyclerView.getChildPosition(recyclerView.getChildAt(0)) == 0;
                boolean topOfFirstItemVisiblePull = recyclerView.getChildAt(0).getTop() == recyclerView
                        .getChildAt(0).getTop();
                ;
                enable = firstItemVisiblePull && topOfFirstItemVisiblePull;
                pullToRefreshView.setEnabled(enable);
            }
        });
        addPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int viewXY[] = new int[2];
                v.getLocationOnScreen(viewXY);
                if (mListener != null) {
                    mListener.onFragmentInteraction("add_game", viewXY[0], viewXY[1]);
                }
            }
        });
    } else {
        if (!fromDrawer) {
            RelativeLayout gamesLayout = (RelativeLayout) rootView.findViewById(R.id.gamesLayout);
            final SwipeDismissBehavior<LinearLayout> behavior = new SwipeDismissBehavior();
            behavior.setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_START_TO_END);
            behavior.setStartAlphaSwipeDistance(1.0f);
            behavior.setSensitivity(0.15f);
            behavior.setListener(new SwipeDismissBehavior.OnDismissListener() {
                @Override
                public void onDismiss(final View view) {
                    GamesFragment myFragC1 = (GamesFragment) getFragmentManager().findFragmentByTag("games");
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                    transaction.remove(myFragC1);
                    transaction.commitAllowingStateLoss();
                    getFragmentManager().executePendingTransactions();
                    mActivity.onBackPressed();
                }

                @Override
                public void onDragStateChanged(int i) {

                }
            });

            CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) gamesLayout
                    .getLayoutParams();
            params.setBehavior(behavior);

        }
        //fastScroller.setRecyclerView(mRecyclerView, null);
        pullToRefreshView.setEnabled(false);
        addPlayer.setVisibility(View.GONE);
    }

    mProgress = (LinearLayout) rootView.findViewById(R.id.progressContainer);
    mText = (TextView) rootView.findViewById(R.id.LoadingText);

    // LinearLayoutManager is used here, this will layout the elements in a similar fashion
    // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
    // elements are laid out.
    mLayoutManager = new LinearLayoutManager(mActivity);

    mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

    if (savedInstanceState != null) {
        // Restore saved layout manager type.
        mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState.getSerializable(KEY_LAYOUT_MANAGER);
    }
    setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

    //mAdapter = new CustomAdapter(mDataset, mDataset_Thumb);
    mAdapter = new GameAdapter(this, mActivity, mSearchQuery, fromDrawer, playListType, sortType, fragmentName,
            currentYear);
    // Set CustomAdapter as the adapter for RecyclerView.
    mRecyclerView.setAdapter(mAdapter);

    if (mSearch != null) {
        mSearch.setHint(
                getString(R.string.filter) + mAdapter.getItemCount() + getString(R.string.filter_games));
    }

    fabMargin = getResources().getDimensionPixelSize(R.dimen.fab_margin);
    mRecyclerView.addOnScrollListener(new MyRecyclerScroll() {
        @Override
        public void show() {
            addPlayer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
        }

        @Override
        public void hide() {
            addPlayer.animate().translationY(addPlayer.getHeight() + fabMargin)
                    .setInterpolator(new AccelerateInterpolator(2)).start();
        }
    });

    if (mSearch != null) {
        mSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                mSearchQuery = cs.toString();
                //initDataset();
                mAdapter = new GameAdapter(GamesFragment.this, mActivity, mSearchQuery, fromDrawer,
                        playListType, sortType, fragmentName, currentYear);
                // Set CustomAdapter as the adapter for RecyclerView.
                mRecyclerView.setAdapter(mAdapter);

                if (mSearch != null) {
                    mSearch.setHint(getString(R.string.filter) + mAdapter.getItemCount()
                            + getString(R.string.filter_games));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }

        });

        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mSearch.getText().toString().equals("")) {
                    mSearchQuery = "";
                    mSearch.setText(mSearchQuery);
                    //mActivity.onBackPressed();
                }

                //fastScroller.scrollHider();

                InputMethodManager inputManager = (InputMethodManager) mActivity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);

                inputManager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                mSearch.clearFocus();
                mRecyclerView.requestFocus();

                initDataset(false);

                if (mSearch != null) {
                    mSearch.setHint(getString(R.string.filter) + mAdapter.getItemCount()
                            + getString(R.string.filter_games));
                }
            }
        });
    }

    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    if (Game.findBaseGames("", sortType, year).size() == 0) {
        initDataset(false);
    } else {
        mText.setVisibility(View.GONE);
        mProgress.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
    }

    // END_INCLUDE(initializeRecyclerView)
    return rootView;
}

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

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

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

    // Create UI references.
    mDeleteDialog = (DeleteDialogFragment) getFragmentManager().findFragmentByTag(DELETE_DIALOG_ID);
    if (mDeleteDialog != null) {
        mDeleteDialog.setListener(this);
    }//www .j  a va  2s  . c  o m
    mClassLayout = (LinearLayout) view.findViewById(R.id.obs_detail_class);
    mClassSpinner = (Spinner) view.findViewById(R.id.obs_detail_class_spinner);
    mClassSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {

            mQuestionLayout.setVisibility(View.GONE);
            mTestLayout.setVisibility(View.GONE);
            mFindingLayout.setVisibility(View.GONE);
            mSymptomLayout.setVisibility(View.GONE);

            switch (pos) {
            case Constants.CLASS_QUESTION:
                mQuestionLayout.setVisibility(View.VISIBLE);
                break;
            case Constants.CLASS_TEST:
                mTestLayout.setVisibility(View.VISIBLE);
                break;
            case Constants.CLASS_FINDING:
                mFindingLayout.setVisibility(View.VISIBLE);
                break;
            case Constants.CLASS_SYMPTOM:
                mSymptomLayout.setVisibility(View.VISIBLE);
                break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    mQuestionLayout = (LinearLayout) view.findViewById(R.id.obs_detail_question);
    mQuestionTextView = (EditText) view.findViewById(R.id.obs_detail_question_text);
    mTestLayout = (LinearLayout) view.findViewById(R.id.obs_detail_test);
    mTestConceptView = (Spinner) view.findViewById(R.id.obs_detail_test_concept);
    mTestConceptView.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            ListViewItem item = (ListViewItem) parent.getItemAtPosition(pos);
            mTestUnitView.setText(item.getField2());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    mTestUnitView = (TextView) view.findViewById(R.id.obs_detail_test_unit);
    mTestValueView = (EditText) view.findViewById(R.id.obs_detail_test_value);
    mFindingLayout = (LinearLayout) view.findViewById(R.id.obs_detail_finding);
    mFindingValueCodedView = (AutoCompleteTextView) view.findViewById(R.id.obs_detail_finding_value_coded);
    mFindingValueCodedView.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!findingCodeBlock) {
                findingCode = -1;
            }
            findingCodeBlock = false;
            searchFindings(s.toString().trim());
        }
    });

    mFindingValueCodedView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
            findingCode = (int) id;
        }
    });
    mFindingCertaintyView = (CheckBox) view.findViewById(R.id.obs_detail_finding_certainty);
    mFindingSeverityCodedView = (CheckBox) view.findViewById(R.id.obs_detail_finding_severity_coded);
    mSymptomLayout = (LinearLayout) view.findViewById(R.id.obs_detail_symptom);
    mSymptomValueView = (AutoCompleteTextView) view.findViewById(R.id.obs_detail_symptom_value);
    mSymptomValueView.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!symptomCodeBlock) {
                symptomCode = -1;
            }
            symptomCodeBlock = false;
            searchSymptoms(s.toString().trim());
        }
    });
    mSymptomValueView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
            symptomCode = (int) id;
        }
    });

    // Restore UI from saved instance or load data.
    if (savedInstanceState != null) {
        findingCode = savedInstanceState.getInt(ARG_FINDING_CODE);
        symptomCode = savedInstanceState.getInt(ARG_SYMPTOM_CODE);

        mObs = (Obs) savedInstanceState.getSerializable(ARG_OBS);
        if (mObs != null) {
            mTestConcepts = savedInstanceState.getParcelableArrayList(ARG_TEST_CONCEPTS);

            ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<>(getActivity(),
                    android.R.layout.simple_spinner_item, mTestConcepts);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mTestConceptView.setAdapter(adapter);
            restoreView();
        }
    } else {
        findingCode = -1;
        symptomCode = -1;
        loadObs();
    }
    return view;
}

From source file:com.bernard.beaconportal.activities.activity.MessageList.java

/**
 * Set the initial display mode (message list, message view, or split view).
 * /*  w w w . ja  va2  s .  com*/
 * <p>
 * <strong>Note:</strong> This method has to be called after
 * {@link #findFragments()} because the result depends on the availability
 * of a {@link MessageViewFragment} instance.
 * </p>
 * 
 * @param savedInstanceState
 *            The saved instance state that was passed to the activity as
 *            argument to {@link #onCreate(Bundle)}. May be {@code null}.
 */
private void initializeDisplayMode(Bundle savedInstanceState) {
    if (useSplitView()) {
        mDisplayMode = DisplayMode.SPLIT_VIEW;
        return;
    }

    if (savedInstanceState != null) {
        DisplayMode savedDisplayMode = (DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE);
        if (savedDisplayMode != DisplayMode.SPLIT_VIEW) {
            mDisplayMode = savedDisplayMode;
            return;
        }
    }

    if (mMessageViewFragment != null || mMessageReference != null) {
        mDisplayMode = DisplayMode.MESSAGE_VIEW;
    } else {
        mDisplayMode = DisplayMode.MESSAGE_LIST;
    }
}