Example usage for android.text TextWatcher TextWatcher

List of usage examples for android.text TextWatcher TextWatcher

Introduction

In this page you can find the example usage for android.text TextWatcher TextWatcher.

Prototype

TextWatcher

Source Link

Usage

From source file:com.mbientlab.metawear.tutorial.starter.DeviceSetupActivityFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Grab Date/*from   w w  w  . ja  v  a  2s .  c o  m*/
    year = Calendar.getInstance().get(Calendar.YEAR);
    month = Calendar.getInstance().get(Calendar.MONTH) + 1;
    day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

    // Initialize variables used for trial name
    SubjectCode = (EditText) view.findViewById(R.id.SubjectCode);
    TrialNumber = (EditText) view.findViewById(R.id.TrialNumber);
    TrialType = (EditText) view.findViewById(R.id.TrialType);
    FileName_text = (TextView) view.findViewById(R.id.FileName_text);

    // Initialize buttons for device behavior
    ProgramState_text = (TextView) view.findViewById(R.id.ProgramState_text);
    ProgramState_switch = (Switch) view.findViewById(R.id.ProgramState);

    // Initialize thresholds and feedback toggles
    Threshold_L = (EditText) view.findViewById(R.id.Threshold_L);
    MotorToggle_switch = (Switch) view.findViewById(R.id.MotorToggle_switch);

    Threshold_L.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Threshold_L_string = Threshold_L.getText().toString();
            if (Threshold_L_string.length() > 0) {
                threshold_L = Double.parseDouble(Threshold_L_string);
            } else {

            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    SubjectCode.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            SubjectCode_string = SubjectCode.getText().toString();
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    TrialType.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            TrialType_string = TrialType.getText().toString();
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    TrialNumber.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            TrialNumber_string = TrialNumber.getText().toString();
            if (TrialNumber_string.length() > 0) {
                TrialNumber_int = Integer.parseInt(TrialNumber_string);
                TrialNumber_string_final = String.format("%03d", TrialNumber_int);
            } else {
            }

            /*if (TrialNumber_string.length() == 1){
            TrialNumber_string_final = "00"+TrialNumber_string;
            }
            if (TrialNumber_string.length() == 2){
            TrialNumber_string_final = "0"+TrialNumber_string;
            }
            if (TrialNumber_string.length() == 3){
            TrialNumber_string_final = TrialNumber_string;
            }*/
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    MotorToggle_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (MotorToggle_state == false) {
                MotorToggle_state = true;
            } else {
                MotorToggle_state = false;
            }
        }
    });

    ProgramState_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (ProgramState_status == false) {
                ProgramState_status = true;
                accelerometer.acceleration().addRouteAsync(new RouteBuilder() {
                    @Override
                    public void configure(RouteComponent source) {
                        source.stream(new Subscriber() {
                            @Override
                            public void apply(Data data, Object... env) {

                                // Read Accel and Prepare for writing to CSV
                                accel_raw_x = data.value(Acceleration.class).x();
                                accel_raw_y = data.value(Acceleration.class).y();
                                accel_raw_z = data.value(Acceleration.class).z();
                                accel_string_x = Double.toString(accel_raw_x);
                                accel_string_y = Double.toString(accel_raw_y);
                                accel_string_z = Double.toString(accel_raw_z);

                                if (initial_accel_loop == 1) {
                                    double vertical_sensor_norm_init = Math.sqrt(accel_raw_x * accel_raw_x
                                            + accel_raw_y * accel_raw_y + accel_raw_z * accel_raw_z);
                                    vertical_sensor_0 = accel_raw_x * 1 / vertical_sensor_norm_init;
                                    vertical_sensor_1 = accel_raw_y * 1 / vertical_sensor_norm_init;
                                    vertical_sensor_2 = accel_raw_z * 1 / vertical_sensor_norm_init;

                                    initial_accel_loop = 0;
                                }
                            }
                        });
                    }
                }).continueWith(new Continuation<Route, Void>() {

                    @Override
                    public Void then(Task<Route> task) throws Exception {
                        accelerometer.acceleration().start();
                        accelerometer.start();
                        Log.i("MainActivity", "Running!");

                        initial_accel_loop = 1;

                        ProgramState_text.setText("Collecting");
                        return null;
                    }
                });
                gyroscope.angularVelocity().addRouteAsync(new RouteBuilder() {
                    @Override
                    public void configure(RouteComponent source) {
                        source.stream(new Subscriber() {
                            @Override
                            public void apply(Data data, Object... env) {

                                // Read Gyro and Prepare for writing to CSV
                                gyro_raw_x = data.value(AngularVelocity.class).x();
                                gyro_raw_y = data.value(AngularVelocity.class).y();
                                gyro_raw_z = data.value(AngularVelocity.class).z();
                                gyro_raw_x = Math.toRadians(gyro_raw_x);
                                gyro_raw_y = Math.toRadians(gyro_raw_y);
                                gyro_raw_z = Math.toRadians(gyro_raw_z);

                                gyro_string_x = Double.toString(gyro_raw_x);
                                gyro_string_y = Double.toString(gyro_raw_y);
                                gyro_string_z = Double.toString(gyro_raw_z);

                                if (initial_accel_loop == 0) {
                                    // Get Timestamp
                                    currentTime = System.currentTimeMillis();
                                    deltaTime = (currentTime - previousTime) / 1000;

                                    if (gyro_raw_x != previous_gyro_raw_x) {
                                        previous_gyro_raw_x = gyro_raw_x;

                                        totalTime = totalTime + deltaTime;
                                        time_stamp = Double.toString(totalTime);
                                        previousTime = currentTime;

                                        //// CALCULATE INCLINATION ANGLE /////
                                        vertical_sensor_from_accel_0 = accel_raw_x;
                                        vertical_sensor_from_accel_1 = accel_raw_y;
                                        vertical_sensor_from_accel_2 = accel_raw_z;

                                        // normalize accelerometer estimate
                                        vertical_sensor_from_accel_norm = Math.sqrt(
                                                vertical_sensor_from_accel_0 * vertical_sensor_from_accel_0
                                                        + vertical_sensor_from_accel_1
                                                                * vertical_sensor_from_accel_1
                                                        + vertical_sensor_from_accel_2
                                                                * vertical_sensor_from_accel_2);

                                        vertical_sensor_from_accel_0 = vertical_sensor_from_accel_0
                                                / vertical_sensor_from_accel_norm;
                                        vertical_sensor_from_accel_1 = vertical_sensor_from_accel_1
                                                / vertical_sensor_from_accel_norm;
                                        vertical_sensor_from_accel_2 = vertical_sensor_from_accel_2
                                                / vertical_sensor_from_accel_norm;

                                        // GYROSCOPE INCLINATION ANGLE
                                        angular_velocity_body_matrix_0_0 = 0;
                                        angular_velocity_body_matrix_0_1 = -gyro_raw_z;
                                        angular_velocity_body_matrix_0_2 = gyro_raw_y;
                                        angular_velocity_body_matrix_1_0 = gyro_raw_z;
                                        angular_velocity_body_matrix_1_1 = 0;
                                        angular_velocity_body_matrix_1_2 = -gyro_raw_x;
                                        angular_velocity_body_matrix_2_0 = -gyro_raw_y;
                                        angular_velocity_body_matrix_2_1 = gyro_raw_x;
                                        angular_velocity_body_matrix_2_2 = 0;

                                        // rotational velocity based on gyroscope readings
                                        vertical_sensor_dot_from_gyro_0 = -(angular_velocity_body_matrix_0_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_0_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_0_2 * vertical_sensor_2);
                                        vertical_sensor_dot_from_gyro_1 = -(angular_velocity_body_matrix_1_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_1_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_1_2 * vertical_sensor_2);
                                        vertical_sensor_dot_from_gyro_2 = -(angular_velocity_body_matrix_2_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_2_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_2_2 * vertical_sensor_2);

                                        // rotational velocity based on difference to accelerometer estimate
                                        vertical_sensor_dot_from_accel_0 = -alpha
                                                * (vertical_sensor_0 - vertical_sensor_from_accel_0);
                                        vertical_sensor_dot_from_accel_1 = -alpha
                                                * (vertical_sensor_1 - vertical_sensor_from_accel_1);
                                        vertical_sensor_dot_from_accel_2 = -alpha
                                                * (vertical_sensor_2 - vertical_sensor_from_accel_2);

                                        // combine the two estimates
                                        vertical_sensor_dot_0 = vertical_sensor_dot_from_gyro_0
                                                + vertical_sensor_dot_from_accel_0;
                                        vertical_sensor_dot_1 = vertical_sensor_dot_from_gyro_1
                                                + vertical_sensor_dot_from_accel_1;
                                        vertical_sensor_dot_2 = vertical_sensor_dot_from_gyro_2
                                                + vertical_sensor_dot_from_accel_2;

                                        // integrate rotational velocity
                                        vertical_sensor_0 = vertical_sensor_0
                                                + deltaTime * vertical_sensor_dot_0;
                                        vertical_sensor_1 = vertical_sensor_1
                                                + deltaTime * vertical_sensor_dot_1;
                                        vertical_sensor_2 = vertical_sensor_2
                                                + deltaTime * vertical_sensor_dot_2;

                                        // normalize after integration
                                        vertical_sensor_norm = Math.sqrt(vertical_sensor_0 * vertical_sensor_0
                                                + vertical_sensor_1 * vertical_sensor_1
                                                + vertical_sensor_2 * vertical_sensor_2);
                                        vertical_sensor_0 = vertical_sensor_0 / vertical_sensor_norm;
                                        vertical_sensor_1 = vertical_sensor_1 / vertical_sensor_norm;
                                        vertical_sensor_2 = vertical_sensor_2 / vertical_sensor_norm;

                                        // calculate inclination angles
                                        inclination_angle = Math.acos(vertical_sensor_0 * sensor_axis_sensor_0
                                                + vertical_sensor_1 * sensor_axis_sensor_1
                                                + vertical_sensor_2 * sensor_axis_sensor_2);
                                        inclination_angle_from_accel = Math
                                                .acos(vertical_sensor_from_accel_0 * sensor_axis_sensor_0
                                                        + vertical_sensor_from_accel_1 * sensor_axis_sensor_1
                                                        + vertical_sensor_from_accel_2 * sensor_axis_sensor_2);
                                        // convert to degrees
                                        inclination_angle = Math.toDegrees(inclination_angle);
                                        inclination_angle_from_accel = Math
                                                .toDegrees(inclination_angle_from_accel);

                                        if (inclination_angle > threshold_L && MotorToggle_state == true) {
                                            motor_status = 1;
                                            //board.getModule(Haptic.class).startBuzzer;
                                            metawear.getModule(Haptic.class).startBuzzer((short) 40);
                                        } else {
                                            motor_status = 0;
                                        }

                                        Log.i("MainActivity", Integer.toString(motor_status));
                                        Log.i("MainActivity", Double.toString(inclination_angle));
                                        csv_entry = csv_entry + time_stamp + "," + inclination_angle + ","
                                                + MotorToggle_state + "," + motor_status + ","
                                                + inclination_angle_from_accel + "," + threshold_L + "," + alpha
                                                + "," + accel_string_x + "," + accel_string_y + ","
                                                + accel_string_z + "," + gyro_string_x + "," + gyro_string_y
                                                + "," + gyro_string_z + "\n";
                                    }
                                }
                            }
                        });
                    }
                }).continueWith(new Continuation<Route, Void>() {
                    @Override
                    public Void then(Task<Route> task) throws Exception {
                        gyroscope.angularVelocity().start();
                        gyroscope.start();

                        currentTime = System.currentTimeMillis();
                        previousTime = currentTime;
                        totalTime = 0;
                        return null;
                    }
                });
            } else {
                // Stop all activity
                Log.i("MainActivity", "Stopped");
                ProgramState_status = false;
                accelerometer.stop();
                accelerometer.acceleration().stop();
                gyroscope.stop();
                gyroscope.angularVelocity().stop();
                ProgramState_text.setText("Saved previous data, Ready to Start");

                filename = FileName_text.getText().toString();

                file = new File(ctx.getExternalFilesDir(null), filename);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(csv_entry.getBytes());
                    os.close();
                    Log.i("MainActivity", "File is created as..." + filename);
                } catch (IOException e) {
                    Log.i("MainActivity", "File NOT created ...!");
                    e.printStackTrace();
                }

                // Reinitialize CSV Entry
                csv_entry = "time" + "," + "inclination angle" + "," + "feedback toggle" + "," + "motor status"
                        + "," + "inclination angle from accelerometers" + "," + "threshold" + "," + "alpha"
                        + "," + "accelerometer_x" + "," + "accelerometer_y" + "," + "acceleromter_z" + ","
                        + "gyroscope_x" + "," + "gyroscope_y" + "," + "gyroscope_z" + "\n" + "sec" + "," + "deg"
                        + "," + "binary" + "," + "binary" + "," + "deg" + "," + "deg" + "," + " " + "," + "g"
                        + "," + "g" + "," + "g" + "," + "deg/sec" + "," + "deg/sec" + "," + "deg/sec" + "\n";
                ProgramState_text.setText("Data Saved and Cleared");

                // Ensure the first loop of next trial goes thru accel first
                initial_accel_loop = 1;

                // Next Trial Increment
                TrialNumber_int = TrialNumber_int + 1;
                TrialNumber.setText(TrialNumber_int.toString());
            }
        }
    });
}

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

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

    rootView.setTag(TAG);/*from  w  w w  .ja v a2s  .co  m*/

    // BEGIN_INCLUDE(initializeRecyclerView)
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mRecyclerView.setBackgroundColor(getResources().getColor(R.color.cardview_initial_background));
    RecyclerFastScroller fastScroller = (RecyclerFastScroller) rootView.findViewById(R.id.fastscroller);

    // Connect the recycler to the scroller (to let the scroller scroll the list)
    fastScroller.attachRecyclerView(mRecyclerView);

    addPlay = (FloatingActionButton) rootView.findViewById(R.id.add_play);
    if (fromDrawer && playListType != 2) {
        addPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int viewXY[] = new int[2];
                v.getLocationOnScreen(viewXY);
                /*if (mListener != null) {
                mListener.onFragmentInteraction("add_play", viewXY[0], viewXY[1]);
                }*/
                ((MainActivity) mActivity).usedFAB = true;
                ((MainActivity) mActivity).openGames("", true, 0, getString(R.string.title_games),
                        MainActivity.CurrentYear);
            }
        });
    } else {
        addPlay.setVisibility(View.GONE);
    }

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

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

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

    // 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 PlayAdapter(mActivity, this);

    /*if (((MainActivity)mActivity).mPlayAdapter != null) {
    mAdapter = ((MainActivity) mActivity).mPlayAdapter;
    }else{*/
    mAdapter = ((MainActivity) mActivity).initPlayAdapter(mSearchQuery, fromDrawer, playListType, currentYear);
    //}
    // Set CustomAdapter as the adapter for RecyclerView.
    mRecyclerView.setAdapter(mAdapter);
    // END_INCLUDE(initializeRecyclerView)

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

    /*boolean pauseOnScroll = true; // or true
    boolean pauseOnFling = true; // or false
    NewPauseOnScrollListener listener = new NewPauseOnScrollListener(ImageLoader.getInstance(), pauseOnScroll, pauseOnFling);
    mRecyclerView.addOnScrollListener(listener);*/

    if (!fromDrawer) {
        RelativeLayout playsLayout = (RelativeLayout) rootView.findViewById(R.id.playsLayout);
        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) {
                PlaysFragment myFragC1 = (PlaysFragment) getFragmentManager().findFragmentByTag("plays");
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.remove(myFragC1);
                transaction.commitAllowingStateLoss();
                getFragmentManager().executePendingTransactions();
                mActivity.onBackPressed();
            }

            @Override
            public void onDragStateChanged(int i) {

            }
        });

        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) playsLayout.getLayoutParams();
        params.setBehavior(behavior);
    }

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

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

            @Override
            public void afterTextChanged(Editable editable) {
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
        });

        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mSearch.getText().toString().equals("")) {
                    mSearchQuery = "";
                    ((MainActivity) mActivity).initPlayAdapter(mSearchQuery, fromDrawer, playListType,
                            currentYear);
                    mSearch.setText(mSearchQuery);

                    //mActivity.onBackPressed();
                }

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

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

                refreshDataset();
            }
        });
    }

    return rootView;
}

From source file:com.google.android.apps.forscience.whistlepunk.metadata.EditTriggerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_trigger_edit, parent, false);
    setHasOptionsMenu(true);/*from  w w w .ja v  a2  s .  c o  m*/

    mNoteGroup = (ViewGroup) view.findViewById(R.id.note_type_trigger_section);
    mAlertGroup = (ViewGroup) view.findViewById(R.id.alert_type_trigger_section);

    mTypeSpinner = (AppCompatSpinner) view.findViewById(R.id.trigger_type_spinner);
    ArrayAdapter<CharSequence> typeAdapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.trigger_type_list, android.R.layout.simple_spinner_item);
    typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mTypeSpinner.setAdapter(typeAdapter);

    mWhenSpinner = (AppCompatSpinner) view.findViewById(R.id.trigger_when_spinner);
    ArrayAdapter<CharSequence> whenAdapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.trigger_when_list, android.R.layout.simple_spinner_item);
    whenAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mWhenSpinner.setAdapter(whenAdapter);

    mValue = (EditText) view.findViewById(R.id.value_input);
    mNoteValue = (EditText) view.findViewById(R.id.trigger_note_text);
    mAudioAlert = (CheckBox) view.findViewById(R.id.alert_type_audio_selector);
    mVisualAlert = (CheckBox) view.findViewById(R.id.alert_type_visual_selector);
    mHapticAlert = (CheckBox) view.findViewById(R.id.alert_type_haptic_selector);
    if (!PermissionUtils.permissionIsGranted(getActivity(), Manifest.permission.VIBRATE)) {
        mHapticAlert.setEnabled(PermissionUtils.canRequestAgain(getActivity(), Manifest.permission.VIBRATE));
    }
    ;

    TextView unitsTextView = (TextView) view.findViewById(R.id.units);
    String units = AppSingleton.getInstance(getActivity()).getSensorAppearanceProvider()
            .getAppearance(mSensorId).getUnits(getActivity());
    unitsTextView.setText(units);

    if (!isNewTrigger()) {
        // Populate the view with the trigger's data.
        int actionType = mTriggerToEdit.getActionType();
        mValue.setText(mTriggerToEdit.getValueToTrigger().toString());
        mTypeSpinner.setSelection(actionType);
        mWhenSpinner.setSelection(mTriggerToEdit.getTriggerWhen());
        if (actionType == TriggerInformation.TRIGGER_ACTION_ALERT) {
            int[] alertTypes = mTriggerToEdit.getAlertTypes();
            for (int i = 0; i < alertTypes.length; i++) {
                int alertType = alertTypes[i];
                if (alertType == TriggerInformation.TRIGGER_ALERT_AUDIO) {
                    mAudioAlert.setChecked(true);
                } else if (alertType == TriggerInformation.TRIGGER_ALERT_VISUAL) {
                    mVisualAlert.setChecked(true);
                } else if (alertType == TriggerInformation.TRIGGER_ALERT_PHYSICAL) {
                    mHapticAlert.setChecked(true);
                }
            }
        } else if (actionType == TriggerInformation.TRIGGER_ACTION_NOTE) {
            mNoteValue.setText(mTriggerToEdit.getNoteText());
        }
        updateViewVisibilities(actionType);

        // Now add the save listeners if this is an edited trigger (not a new trigger).
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                saveTrigger();
            }
        };
        mNoteValue.addTextChangedListener(watcher);
        mValue.addTextChangedListener(watcher);
        mWhenSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                saveTrigger();
            }

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

            }
        });
        CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                saveTrigger();
            }
        };
        mAudioAlert.setOnCheckedChangeListener(checkedChangeListener);
        mVisualAlert.setOnCheckedChangeListener(checkedChangeListener);
    } else {
        // Default to an alert spinner that triggers "at" a value, and does a visual alert.
        mTypeSpinner.setSelection(TriggerInformation.TRIGGER_ACTION_ALERT);
        mWhenSpinner.setSelection(TriggerInformation.TRIGGER_WHEN_AT);
        mVisualAlert.setChecked(true);
    }

    mWhenSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            // Hide all but alert types if this is a ABOVE or BELOW.
            if (position == TriggerInformation.TRIGGER_WHEN_ABOVE
                    || position == TriggerInformation.TRIGGER_WHEN_BELOW) {
                mTypeSpinner.setSelection(TriggerInformation.TRIGGER_ACTION_ALERT);
                mTypeSpinner.setEnabled(false);
                updateViewVisibilities(TriggerInformation.TRIGGER_ACTION_ALERT);
                selectAlertTypeIfNeeded();
            } else {
                mTypeSpinner.setEnabled(true);
            }
            if (!isNewTrigger()) {
                saveTrigger();
            }
        }

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

        }
    });

    mTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            updateViewVisibilities(position);
            if (position == TriggerInformation.TRIGGER_ACTION_ALERT) {
                selectAlertTypeIfNeeded();
            }
            if (!isNewTrigger()) {
                saveTrigger();
            }
        }

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

        }
    });

    mHapticAlert.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // Don't let them check this checkbox if they deny the vibrate permission.
                if (!PermissionUtils.tryRequestingPermission(getActivity(), Manifest.permission.VIBRATE,
                        PERMISSION_VIBRATE, true)) {
                    mHapticAlert.setChecked(false);
                }
                ;
            }
            if (!isNewTrigger()) {
                saveTrigger();
            }
        }
    });
    return view;
}

From source file:com.github.irshulx.Components.InputExtensions.java

public CustomEditText getNewEditTextInst(final String hint, CharSequence text) {
    final CustomEditText editText = new CustomEditText(
            new ContextThemeWrapper(this.editorCore.getContext(), R.style.WysiwygEditText));
    addEditableStyling(editText);//from   www  .j a v  a 2s . c  o m
    editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    if (hint != null) {
        editText.setHint(hint);
    }
    if (text != null) {
        setText(editText, text);
    }

    /**
     * create tag for the editor
     */

    EditorControl editorTag = editorCore.createTag(EditorType.INPUT);
    editorTag.textSettings = new TextSettings(this.DEFAULT_TEXT_COLOR);
    editText.setTag(editorTag);
    editText.setBackgroundDrawable(
            ContextCompat.getDrawable(this.editorCore.getContext(), R.drawable.invisible_edit_text));
    editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            return editorCore.onKey(v, keyCode, event, editText);
        }
    });
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                editText.clearFocus();
            } else {
                editorCore.setActiveView(v);
            }
        }
    });
    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

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

        @Override
        public void afterTextChanged(Editable s) {

            String text = Html.toHtml(editText.getText());
            Object tag = editText.getTag(R.id.control_tag);
            if (s.length() == 0 && tag != null)
                editText.setHint(tag.toString());
            if (s.length() > 0) {
                /*
                 * if user had pressed enter, replace it with br
                 */
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == '\n') {
                        CharSequence subChars = s.subSequence(0, i);
                        SpannableStringBuilder ssb = new SpannableStringBuilder(subChars);
                        text = Html.toHtml(ssb);
                        if (text.length() > 0)
                            setText(editText, text);

                        if (i + 1 == s.length()) {
                            s.clear();
                        }

                        int index = editorCore.getParentView().indexOfChild(editText);
                        /* if the index was 0, set the placeholder to empty, behaviour happens when the user just press enter
                         */
                        if (index == 0) {
                            editText.setHint(null);
                            editText.setTag(R.id.control_tag, hint);
                        }
                        int position = index + 1;
                        CharSequence newText = null;
                        SpannableStringBuilder editable = new SpannableStringBuilder();
                        int lastIndex = s.length();
                        int nextIndex = i + 1;
                        if (nextIndex < lastIndex) {
                            newText = s.subSequence(nextIndex, lastIndex);
                            for (int j = 0; j < newText.length(); j++) {
                                editable.append(newText.charAt(j));
                                if (newText.charAt(j) == '\n') {
                                    editable.append('\n');
                                }
                            }
                        }
                        insertEditText(position, hint, editable);
                        break;
                    }
                }
            }
            if (editorCore.getEditorListener() != null) {
                editorCore.getEditorListener().onTextChanged(editText, s);
            }
        }
    });
    if (this.lineSpacing != -1) {
        setLineSpacing(editText, this.lineSpacing);
    }
    return editText;
}

From source file:com.keepassdroid.PasswordActivity.java

private void initForFingerprint() {
    fingerPrintHelper = new FingerPrintHelper(this, this);
    if (fingerPrintHelper.hasEnrolledFingerprints()) {

        // when text entered we can enable the logon/purchase button and if required update encryption/decryption mode
        passwordView.addTextChangedListener(new TextWatcher() {
            @Override//  w  ww  . j a  va  2s. c om
            public void beforeTextChanged(final CharSequence s, final int start, final int count,
                    final int after) {

            }

            @Override
            public void onTextChanged(final CharSequence s, final int start, final int before,
                    final int count) {

            }

            @Override
            public void afterTextChanged(final Editable s) {
                final boolean validInput = s.length() > 0;
                // encrypt or decrypt mode based on how much input or not
                int messageId;
                if (validInput) {
                    messageId = R.string.store_with_fingerprint;
                } else if (EmptyUtils.isNullOrEmpty(prefsNoBackup.getString(getPreferenceKeyValue(), null))) {
                    messageId = R.string.no_password_stored;
                } else {
                    messageId = R.string.scanning_fingerprint;
                }
                confirmationView.setText(messageId);
                mode = validInput ? toggleMode(Cipher.ENCRYPT_MODE) : toggleMode(Cipher.DECRYPT_MODE);

            }
        });

        // callback for fingerprint findings
        fingerPrintHelper.setAuthenticationCallback(new FingerprintManagerCompat.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(final int errorCode, final CharSequence errString) {

                if (errorCode != 5) { // FINGERPRINT_ERROR_CANCELLED (not defined in support library)
                    onException(errString);
                }
            }

            @Override
            public void onAuthenticationHelp(final int helpCode, final CharSequence helpString) {

                onException();
                confirmationView.setText(helpString);
            }

            @Override
            public void onAuthenticationSucceeded(final FingerprintManagerCompat.AuthenticationResult result) {

                if (mode == Cipher.ENCRYPT_MODE) {

                    // newly store the entered password in encrypted way
                    final String password = passwordView.getText().toString();
                    fingerPrintHelper.encryptData(password);

                } else if (mode == Cipher.DECRYPT_MODE) {

                    // retrieve the encrypted value from preferences
                    final String encryptedValue = prefsNoBackup.getString(getPreferenceKeyValue(), null);
                    if (encryptedValue != null) {
                        fingerPrintHelper.decryptData(encryptedValue);
                    }
                }
            }

            @Override
            public void onAuthenticationFailed() {
                onException(R.string.fingerprint_notrecognized);
            }
        });
    }
}

From source file:com.google.firebase.codelab.friendlychat.ChatFragment.java

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

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
    mUsername = ANONYMOUS;/*from   w w  w .j a  va  2 s.c  o m*/

    // Initialize Firebase Auth
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();

    mUsername = mFirebaseUser.getDisplayName();
    mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();

    mProgressBar = (ProgressBar) getView().findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) getView().findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(getActivity());
    mLinearLayoutManager.setStackFromEnd(true);

    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class,
            R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {

        @Override
        protected FriendlyMessage parseSnapshot(DataSnapshot snapshot) {
            FriendlyMessage friendlyMessage = super.parseSnapshot(snapshot);
            if (friendlyMessage != null) {
                friendlyMessage.setId(snapshot.getKey());
            }
            return friendlyMessage;
        }

        @Override
        protected void populateViewHolder(MessageViewHolder viewHolder, FriendlyMessage friendlyMessage,
                int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            viewHolder.messageTextView.setText(friendlyMessage.getText());
            viewHolder.messengerTextView.setText(friendlyMessage.getName());
            if (friendlyMessage.getPhotoUrl() == null) {
                viewHolder.messengerImageView.setImageDrawable(
                        ContextCompat.getDrawable(getActivity(), R.drawable.ic_account_circle_black_36dp));
            } else {
                Glide.with(ChatFragment.this).load(friendlyMessage.getPhotoUrl())
                        .into(viewHolder.messengerImageView);
            }

            // write this message to the on-device index
            FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));

            // log a view action on it
            FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
        }
    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    // Initialize Firebase Measurement.
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(getActivity());

    // Initialize Firebase Remote Config.
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

    // Define Firebase Remote Config Settings.
    FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
            .setDeveloperModeEnabled(true).build();

    // Define default config values. Defaults are used when fetched config values are not
    // available. Eg: if an error occurred fetching values from the server.
    Map<String, Object> defaultConfigMap = new HashMap<>();
    defaultConfigMap.put("friendly_msg_length", 1000L);

    // Apply config settings and default values.
    mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
    mFirebaseRemoteConfig.setDefaults(defaultConfigMap);

    // Fetch remote config.
    fetchConfig();

    mMessageEditText = (EditText) getView().findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
            mSharedPreferences.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (Button) getView().findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
                    mUsername, mPhotoUrl);
            mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage);
            mMessageEditText.setText("");
            mFirebaseAnalytics.logEvent(MESSAGE_SENT_EVENT, null);
        }
    });
}

From source file:com.bisonswap.bisonswap.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mUsername = ANONYMOUS;/*from  www.  j a  va2  s  . c  om*/

    // Initialize Firebase Auth
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();

    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mFirebaseUser.getDisplayName();
        mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
    }

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API).build();

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);

    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class,
            R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {

        @Override
        protected FriendlyMessage parseSnapshot(DataSnapshot snapshot) {
            FriendlyMessage friendlyMessage = super.parseSnapshot(snapshot);
            if (friendlyMessage != null) {
                friendlyMessage.setId(snapshot.getKey());
            }
            return friendlyMessage;
        }

        @Override
        protected void populateViewHolder(MessageViewHolder viewHolder, FriendlyMessage friendlyMessage,
                int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            viewHolder.messageTextView.setText(friendlyMessage.getText());
            viewHolder.messengerTextView.setText(friendlyMessage.getName());
            if (friendlyMessage.getPhotoUrl() == null) {
                viewHolder.messengerImageView.setImageDrawable(
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_black_36dp));
            } else {
                Glide.with(MainActivity.this).load(friendlyMessage.getPhotoUrl())
                        .into(viewHolder.messengerImageView);
            }

            // write this message to the on-device index
            FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));

            // log a view action on it
            FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
        }
    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    // Initialize and request AdMob ad.
    mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    // Initialize Firebase Measurement.
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    // Initialize Firebase Remote Config.
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

    // Define Firebase Remote Config Settings.
    FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
            .setDeveloperModeEnabled(true).build();

    // Define default config values. Defaults are used when fetched config values are not
    // available. Eg: if an error occurred fetching values from the server.
    Map<String, Object> defaultConfigMap = new HashMap<>();
    defaultConfigMap.put("friendly_msg_length", 10L);

    // Apply config settings and default values.
    mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
    mFirebaseRemoteConfig.setDefaults(defaultConfigMap);

    // Fetch remote config.
    fetchConfig();

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
            mSharedPreferences.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (Button) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
                    mUsername, mPhotoUrl);
            mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage);
            mMessageEditText.setText("");
            mFirebaseAnalytics.logEvent(MESSAGE_SENT_EVENT, null);
        }
    });
}

From source file:com.example.sergio.quizmetestgui.MainActivityChat.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mUsername = ANONYMOUS;//from  w w  w .jav a2s  .c  o m

    // Initialize Firebase Auth
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();

    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mFirebaseUser.getDisplayName();
        //            mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
    }

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API).build();

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);

    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class,
            R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {

        @Override
        protected FriendlyMessage parseSnapshot(DataSnapshot snapshot) {
            FriendlyMessage friendlyMessage = super.parseSnapshot(snapshot);
            if (friendlyMessage != null) {
                friendlyMessage.setId(snapshot.getKey());
            }
            return friendlyMessage;
        }

        @Override
        protected void populateViewHolder(MessageViewHolder viewHolder, FriendlyMessage friendlyMessage,
                int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            viewHolder.messageTextView.setText(friendlyMessage.getText());
            viewHolder.messengerTextView.setText(friendlyMessage.getName());
            if (friendlyMessage.getPhotoUrl() == null) {
                viewHolder.messengerImageView.setImageDrawable(ContextCompat.getDrawable(MainActivityChat.this,
                        R.drawable.ic_account_circle_black_36dp));
            } else {
                Glide.with(MainActivityChat.this).load(friendlyMessage.getPhotoUrl())
                        .into(viewHolder.messengerImageView);
            }

            // write this message to the on-device index
            FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));

            // log a view action on it
            FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
        }
    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    // Initialize and request AdMob ad.
    /* mAdView = (AdView) findViewById(R.id.adView);
     AdRequest adRequest = new AdRequest.Builder().build();
     mAdView.loadAd(adRequest);*/

    // Initialize Firebase Measurement.
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    // Initialize Firebase Remote Config.
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

    // Define Firebase Remote Config Settings.
    FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
            .setDeveloperModeEnabled(true).build();

    // Define default config values. Defaults are used when fetched config values are not
    // available. Eg: if an error occurred fetching values from the server.
    Map<String, Object> defaultConfigMap = new HashMap<>();
    defaultConfigMap.put("friendly_msg_length", 10L);

    // Apply config settings and default values.
    mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
    mFirebaseRemoteConfig.setDefaults(defaultConfigMap);

    // Fetch remote config.
    fetchConfig();

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
            mSharedPreferences.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (Button) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
                    mUsername, mPhotoUrl);
            mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage);
            mMessageEditText.setText("");
            mFirebaseAnalytics.logEvent(MESSAGE_SENT_EVENT, null);
        }
    });
}

From source file:com.cgopir.trackme.chat.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mUsername = ANONYMOUS;//  w ww. ja va2  s. c  o  m

    // Initialize Firebase Auth
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();

    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mFirebaseUser.getDisplayName();
        if (mFirebaseUser.getPhotoUrl() != null) {
            mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
        }
    }

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API).build();

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);

    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class,
            R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {

        @Override
        protected FriendlyMessage parseSnapshot(DataSnapshot snapshot) {
            FriendlyMessage friendlyMessage = super.parseSnapshot(snapshot);
            if (friendlyMessage != null) {
                friendlyMessage.setId(snapshot.getKey());
            }
            return friendlyMessage;
        }

        @Override
        protected void populateViewHolder(MessageViewHolder viewHolder, FriendlyMessage friendlyMessage,
                int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            viewHolder.messageTextView.setText(friendlyMessage.getText());
            viewHolder.messengerTextView.setText(friendlyMessage.getName());
            if (friendlyMessage.getPhotoUrl() == null) {
                viewHolder.messengerImageView.setImageDrawable(
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_black_36dp));
            } else {
                Glide.with(MainActivity.this).load(friendlyMessage.getPhotoUrl())
                        .into(viewHolder.messengerImageView);
            }

            // write this message to the on-device index
            FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));

            // log a view action on it
            FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
        }
    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    // Initialize and request AdMob ad.
    //mAdView = (AdView) findViewById(R.id.adView);
    //AdRequest adRequest = new AdRequest.Builder().build();
    //mAdView.loadAd(adRequest);

    // Initialize Firebase Measurement.
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    // Initialize Firebase Remote Config.
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

    // Define Firebase Remote Config Settings.
    FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
            .setDeveloperModeEnabled(true).build();

    // Define default config values. Defaults are used when fetched config values are not
    // available. Eg: if an error occurred fetching values from the server.
    Map<String, Object> defaultConfigMap = new HashMap<>();
    defaultConfigMap.put("friendly_msg_length", 10L);

    // Apply config settings and default values.
    mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
    mFirebaseRemoteConfig.setDefaults(defaultConfigMap);

    // Fetch remote config.
    fetchConfig();

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
            mSharedPreferences.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (Button) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
                    mUsername, mPhotoUrl);
            mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage);
            mMessageEditText.setText("");
            mFirebaseAnalytics.logEvent(MESSAGE_SENT_EVENT, null);
        }
    });
}

From source file:com.openatk.field_work.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbHelper = new DatabaseHelper(this);
    syncHelper = new TrelloSyncHelper();

    //Get fragments
    FragmentManager fm = getSupportFragmentManager();
    atkMapFragment = (ATKSupportMapFragment) fm.findFragmentById(R.id.map);
    fragmentJob = (FragmentJob) fm.findFragmentByTag("edit_job");
    fragmentAddField = (FragmentAddField) fm.findFragmentByTag("add_field");

    //Show and hide listview really fast. TODO is there a better way to do this
    //I would like this to retain if possible...
    fragmentListView = (FragmentListView) fm.findFragmentById(R.id.list_view);
    FragmentTransaction ft = fm.beginTransaction();
    ft.hide(fragmentListView); //TODO check state, are we in list view state? if so don't hide
    ft.commit();/*from   www. j av  a  2 s . com*/

    if (savedInstanceState == null) {
        // First incarnation of this activity.
        atkMapFragment.setRetainInstance(true);
        fragmentListView.setRetainInstance(true);
        if (fragmentJob != null)
            fragmentJob.setRetainInstance(true);
        if (fragmentAddField != null)
            fragmentAddField.setRetainInstance(true);

        fragmentJob = null;
        fragmentAddField = null;
    } else {
        // Reincarnated activity. The obtained map is the same map instance
        // in the previous
        // activity life cycle. There is no need to reinitialize it.
        map = atkMapFragment.getAtkMap();
    }

    actionBar = getActionBar();
    // Specify that a dropdown list should be displayed in the action bar.
    // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    // Hide the title
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayUseLogoEnabled(false);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);

    LayoutInflater inflater = (LayoutInflater) this.getApplicationContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.action_bar, null);

    RelativeLayout item = (RelativeLayout) view.findViewById(R.id.action_bar_layout);

    spinnerMenu = (Spinner) view.findViewById(R.id.action_bar_operation_spinner);
    actionBarSearch = (EditText) view.findViewById(R.id.action_bar_search_box);
    actionBar.setCustomView(item, new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT));

    actionBarSearch.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus == false) {
                closeKeyboard();
            }
        }
    });
    actionBarSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if (fragmentListView != null)
                fragmentListView.search(s.toString());
        }

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    // Get last selected items on rotate
    this.savedInstanceState = savedInstanceState;

    // Specify a SpinnerAdapter to populate the dropdown list.
    spinnerMenuAdapter = new ArrayAdapter<Operation>(this, R.layout.operation_list_item, operationsList);
    spinnerMenu.setAdapter(spinnerMenuAdapter);

    RelativeLayoutKeyboardDetect layout = (RelativeLayoutKeyboardDetect) this.findViewById(R.id.mainActivity);
    layout.setListener(this);

    setUpMapIfNeeded();
    if (this.savedInstanceState != null) {
        int viewState = savedInstanceState.getInt("currentViewState", STATE_DEFAULT);
        setState(viewState);
    }
}