Example usage for java.text DateFormat getTimeInstance

List of usage examples for java.text DateFormat getTimeInstance

Introduction

In this page you can find the example usage for java.text DateFormat getTimeInstance.

Prototype

public static final DateFormat getTimeInstance() 

Source Link

Document

Gets the time formatter with the default formatting style for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:org.svij.taskwarriorapp.TaskAddActivity.java

public void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task_add);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    final TextView tvDueDate = (TextView) findViewById(R.id.tvDueDate);
    tvDueDate.setOnClickListener(new View.OnClickListener() {

        @Override// www .j  a  v a 2s .com
        public void onClick(View v) {
            DatePickerFragment date = new DatePickerFragment();
            date.setCallBack(onDate);
            date.setTimestamp(timestamp);
            date.show(getSupportFragmentManager().beginTransaction(), "date_dialog");
        }
    });

    final TextView tvDueTime = (TextView) findViewById(R.id.tvDueTime);
    tvDueTime.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            TimePickerFragment date = new TimePickerFragment();
            date.setCallBack(onTime);
            date.setTimestamp(timestamp);
            date.show(getSupportFragmentManager().beginTransaction(), "time_dialog");
        }
    });

    tvDueDate.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueTime.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
                cal.set(Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH));
                cal.set(Calendar.DAY_OF_MONTH, Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                timestamp = cal.getTimeInMillis();
            }
            tvDueDate.setText("");
            return true;
        }
    });

    tvDueTime.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueDate.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                timestamp = cal.getTimeInMillis();
            }
            tvDueTime.setText("");
            return true;
        }
    });

    TaskDataSource dataSource = new TaskDataSource(this);
    ArrayList<String> projectsAR = dataSource.getProjects();
    projectsAR.removeAll(Collections.singleton(null));
    String[] projects = projectsAR.toArray(new String[projectsAR.size()]);
    final AutoCompleteTextView actvProject = (AutoCompleteTextView) findViewById(R.id.actvProject);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            projects);
    actvProject.setAdapter(adapter);

    actvProject.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            actvProject.showDropDown();
            return false;
        }
    });

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();

    if (extras != null) {
        taskID = extras.getString("taskID");

        if (taskID != null) {
            datasource = new TaskDataSource(this);
            Task task = datasource.getTask(UUID.fromString(taskID));

            TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
            Spinner spPriority = (Spinner) findViewById(R.id.spPriority);
            TextView etTags = (TextView) findViewById(R.id.etTags);

            etTaskAdd.setText(task.getDescription());
            if (task.getDue() != null && task.getDue().getTime() != 0) {

                tvDueDate.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(task.getDue()));
                if (!DateFormat.getTimeInstance().format(task.getDue()).equals("00:00:00")) {
                    tvDueTime.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(task.getDue()));
                }

                cal.setTime(task.getDue());
                timestamp = cal.getTimeInMillis();

            }
            actvProject.setText(task.getProject());
            Log.i("PriorityID", ":" + task.getPriorityID());
            spPriority.setSelection(task.getPriorityID());
            etTags.setText(task.getTags());
        } else {
            String action = intent.getAction();
            if ((action.equalsIgnoreCase(Intent.ACTION_SEND)
                    || action.equalsIgnoreCase("com.google.android.gm.action.AUTO_SEND"))
                    && intent.hasExtra(Intent.EXTRA_TEXT)) {
                String s = intent.getStringExtra(Intent.EXTRA_TEXT);
                TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
                etTaskAdd.setText(s);
                addingTaskFromOtherApp = true;
            }
        }
    }

}

From source file:org.portlandrobotics.nrfUARTv2.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*  w  w  w  . j a va2 s .c o m*/
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    messageListView = (ListView) findViewById(R.id.listMessage);
    listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    messageListView.setAdapter(listAdapter);
    messageListView.setDivider(null);
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    btnSend = (Button) findViewById(R.id.sendButton);
    btnRotateNinety = (Button) findViewById(R.id.rotateNinetyButton);
    edtMessage = (EditText) findViewById(R.id.sendText);
    mSwv = (ServoWheelView) findViewById(R.id.view);
    motorSwitch = (Switch) findViewById(R.id.switch1);
    service_init();

    mSwv.setAngleUpdate(new MyAngle());

    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mBtAdapter.isEnabled()) {
                Log.i(TAG, "onClick - BT not enabled yet");
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                if (btnConnectDisconnect.getText().equals("Connect")) {

                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                    Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                } else {
                    //Disconnect button pressed
                    if (mDevice != null) {
                        mService.disconnect();

                    }
                }
            }
        }
    });
    // Handler Send button  
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.sendText);
            String message = editText.getText().toString();

            if (message.equals("dump")) {
                readRegister(BTSERVO_REG_TARGET);
                readRegister(BTSERVO_REG_MODE);
                readRegister(BTSERVO_REG_SPEED);
                readRegister(BTSERVO_REG_LOCATION);
                readRegister(BTSERVO_REG_PWM);
            } else {
                //send data to service
                //byte[] value = message.getBytes(uartCharset);
                //mService.writeRXCharacteristic(value);
                queueCommand(message);
            }
            //Update the log with time stamp
            String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
            listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
            messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
            edtMessage.setText("");

        }
    });

    btnRotateNinety.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mServoState.target = (mServoState.target + 45) % 1024;
            writeRegister(0, mServoState.target);
        }
    });

    motorSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                writeRegister(1, 1);
            else
                writeRegister(1, 0);
        }
    });

    // Set initial UI state

}

From source file:org.opendatakit.briefcase.util.WebUtils.java

/**
 * Parse a string into a datetime value. Tries the common Http formats, the
 * iso8601 format (used by Javarosa), the default formatting from
 * Date.toString(), and a time-only format.
 * /*from w  w  w  .j a  v a  2s  .  com*/
 * @param value
 * @return
 */
public static final Date parseDate(String value) {
    if (value == null || value.length() == 0)
        return null;

    String[] iso8601Pattern = new String[] { PATTERN_ISO8601 };

    String[] localizedParsePatterns = new String[] {
            // try the common HTTP date formats that have time zones
            PATTERN_RFC1123, PATTERN_RFC1036, PATTERN_DATE_TOSTRING };

    String[] localizedNoTzParsePatterns = new String[] {
            // ones without timezones... (will assume UTC)
            PATTERN_ASCTIME };

    String[] tzParsePatterns = new String[] { PATTERN_ISO8601, PATTERN_ISO8601_DATE, PATTERN_ISO8601_TIME };

    String[] noTzParsePatterns = new String[] {
            // ones without timezones... (will assume UTC)
            PATTERN_ISO8601_WITHOUT_ZONE, PATTERN_NO_DATE_TIME_ONLY,
            PATTERN_YYYY_MM_DD_DATE_ONLY_NO_TIME_DASH };

    Date d = null;
    // iso8601 parsing is sometimes off-by-one when JR does it...
    d = parseDateSubset(value, iso8601Pattern, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try to parse with the JavaRosa parsers
    d = DateUtils.parseDateTime(value);
    if (d != null)
        return d;
    d = DateUtils.parseDate(value);
    if (d != null)
        return d;
    d = DateUtils.parseTime(value);
    if (d != null)
        return d;
    // try localized and english text parsers (for Web headers and interactive filter spec.)
    d = parseDateSubset(value, localizedParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedNoTzParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedNoTzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try other common patterns that might not quite match JavaRosa parsers
    d = parseDateSubset(value, tzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, noTzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try the locale- and timezone- specific parsers
    {
        DateFormat formatter = DateFormat.getDateTimeInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    {
        DateFormat formatter = DateFormat.getDateInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    {
        DateFormat formatter = DateFormat.getTimeInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    throw new IllegalArgumentException("Unable to parse the date: " + value);
}

From source file:org.svij.taskwarriorapp.activities.TaskAddActivity.java

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task_add);

    final TextView tvDueDate = (TextView) findViewById(R.id.tvDueDate);
    tvDueDate.setOnClickListener(new View.OnClickListener() {

        @Override/* w  w w.  j ava  2  s.c o  m*/
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            CalendarDatePickerDialog calendarDatePickerDialog = CalendarDatePickerDialog.newInstance(
                    TaskAddActivity.this, Calendar.getInstance().get(Calendar.YEAR),
                    Calendar.getInstance().get(Calendar.MONTH),
                    Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
            calendarDatePickerDialog.show(fm, "fragment_date_picker");
        }
    });

    final TextView tvDueTime = (TextView) findViewById(R.id.tvDueTime);
    tvDueTime.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            FragmentManager fm = getSupportFragmentManager();
            RadialTimePickerDialog timePickerDialog = RadialTimePickerDialog.newInstance(TaskAddActivity.this,
                    Calendar.getInstance().get(Calendar.HOUR_OF_DAY),
                    Calendar.getInstance().get(Calendar.MINUTE),
                    android.text.format.DateFormat.is24HourFormat(TaskAddActivity.this));
            timePickerDialog.show(fm, "fragment_time_picker_name");
        }
    });

    tvDueDate.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueTime.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
                cal.set(Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH));
                cal.set(Calendar.DAY_OF_MONTH, Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                timestamp = cal.getTimeInMillis();
            }
            tvDueDate.setText("");
            return true;
        }
    });

    tvDueTime.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueDate.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                timestamp = cal.getTimeInMillis();
            }
            tvDueTime.setText("");
            return true;
        }
    });

    TaskDatabase dataSource = new TaskDatabase(this);
    ArrayList<String> projects = dataSource.getProjects();
    projects.removeAll(Collections.singleton(null));
    final AutoCompleteTextView actvProject = (AutoCompleteTextView) findViewById(R.id.actvProject);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            projects.toArray(new String[projects.size()]));
    actvProject.setAdapter(adapter);
    actvProject.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            actvProject.showDropDown();
            return false;
        }
    });

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();

    if (extras != null) {
        taskID = extras.getString("taskID");

        if (taskID != null) {
            data = new TaskDatabase(this);
            Task task = data.getTask(UUID.fromString(taskID));

            TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
            Spinner spPriority = (Spinner) findViewById(R.id.spPriority);

            etTaskAdd.setText(task.getDescription());
            if (task.getDue() != null && task.getDue().getTime() != 0) {

                tvDueDate.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(task.getDue()));
                if (!DateFormat.getTimeInstance().format(task.getDue()).equals("00:00:00")) {
                    tvDueTime.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(task.getDue()));
                }

                cal.setTime(task.getDue());
                timestamp = cal.getTimeInMillis();

            }
            actvProject.setText(task.getProject());

            Log.i("PriorityID", ":" + task.getPriorityID());
            spPriority.setSelection(task.getPriorityID());

            if (task.getTags() != null) {
                TextView etTags = (TextView) findViewById(R.id.etTags);
                String tagString = "";

                for (String s : task.getTags()) {
                    tagString += s + " ";
                }
                etTags.setText(tagString.trim());
            }
        } else {
            String action = intent.getAction();
            if ((action.equalsIgnoreCase(Intent.ACTION_SEND)
                    || action.equalsIgnoreCase("com.google.android.gm.action.AUTO_SEND"))
                    && intent.hasExtra(Intent.EXTRA_TEXT)) {
                String s = intent.getStringExtra(Intent.EXTRA_TEXT);
                TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
                etTaskAdd.setText(s);
                addingTaskFromOtherApp = true;
            }
        }
    }

}

From source file:org.onebusaway.enterprise.webapp.actions.m.IndexAction.java

public String getLastUpdateTime() {
    return DateFormat.getTimeInstance().format(new Date());
}

From source file:org.sakaiproject.evaluation.logic.scheduling.ConsolidatedNotificationsJobImpl.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    LOG.info("execute()");

    // this server must get lock to do this job
    String serverId = this.externalLogic.getServerId();
    Boolean gotLock = lockManager.obtainLock(LOCK_CONSOLIDATED_EMAIL_JOB, serverId, TWO_HOURS);
    if (gotLock != null && gotLock) {
        try {/*from  w ww .  j  a  v a 2s .c om*/

            Date beginTime = new Date();

            String jobId = this.jobStatusReporter.reportStarted("Email");
            this.jobStatusReporter.reportProgress(jobId, "server-id", serverId);

            Boolean sendAvailableEmails = (Boolean) this.evalSettings
                    .get(EvalSettings.CONSOLIDATED_EMAIL_NOTIFY_AVAILABLE);
            if (sendAvailableEmails == null) {
                sendAvailableEmails = true;
            }

            if (sendAvailableEmails) {
                String[] recipients = this.emailLogic.sendConsolidatedAvailableNotifications(jobStatusReporter,
                        jobId);
                if (recipients == null) {
                    LOG.debug("announcements sent: 0");
                } else {
                    LOG.debug("announcements sent: " + recipients.length);
                }
            }

            int reminderInterval = ((Integer) evalSettings.get(EvalSettings.SINGLE_EMAIL_REMINDER_DAYS));
            // check if reminders are to be sent
            if (reminderInterval > 0) {
                Date nextReminder;
                String nextReminderStr = (String) evalSettings.get(EvalSettings.NEXT_REMINDER_DATE);
                if (nextReminderStr == null || nextReminderStr.trim().equals("")) {
                    nextReminder = new Date();
                } else {
                    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy"); //DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL);
                    try {
                        nextReminder = df.parse(nextReminderStr);
                    } catch (ParseException e) {
                        // Use current date
                        nextReminder = new Date();
                    }
                }
                if (LOG.isInfoEnabled()) {
                    LOG.info("Next reminder date is " + nextReminder + ".");
                }
                //reminder interval unit is a day
                long one_hour = 1000L * 60L * 60L;
                long one_day = one_hour * 24L;
                // see if time is equal to or after reminder date (+/- six hours)
                long rdate = nextReminder.getTime();
                long tdate = System.currentTimeMillis();
                if (tdate >= (rdate - 6L * one_hour)) {

                    String[] recipients = this.emailLogic
                            .sendConsolidatedReminderNotifications(jobStatusReporter, jobId);
                    if (recipients == null) {
                        LOG.debug("reminders sent: 0");
                    } else {
                        LOG.debug("reminders sent: " + recipients.length);
                    }
                    Calendar cal = Calendar.getInstance();
                    cal.setTimeInMillis(tdate + reminderInterval * one_day);
                    Integer startTime = (Integer) this.evalSettings
                            .get(EvalSettings.CONSOLIDATED_EMAIL_DAILY_START_TIME);
                    Integer startMinute = (Integer) this.evalSettings
                            .get(EvalSettings.CONSOLIDATED_EMAIL_DAILY_START_MINUTES);

                    if (startTime != null) {
                        cal.set(Calendar.HOUR_OF_DAY, startTime);
                        cal.set(Calendar.MINUTE, startMinute);
                        cal.set(Calendar.SECOND, 0);
                    }
                    this.evalSettings.set(EvalSettings.NEXT_REMINDER_DATE, cal.getTime());

                    Date endTime = new Date();

                    //"FINISHED" "summary" The email job took <elapsed-time> seconds to run. It kicked off at <begin-time> and ended at <begin-time>.

                    StringBuilder buf = new StringBuilder();
                    DateFormat df = DateFormat.getTimeInstance();
                    long seconds = endTime.getTime() - beginTime.getTime();
                    long milliseconds = seconds % 1000;
                    seconds = seconds / 1000;

                    buf.append("The email job took ");
                    buf.append(seconds);
                    buf.append(".");
                    if (milliseconds < 10) {
                        buf.append("00");
                    } else if (milliseconds < 100) {
                        buf.append("0");
                    }
                    buf.append(milliseconds);
                    buf.append(" seconds to run. It kicked off at ");
                    buf.append(df.format(beginTime));
                    buf.append(" and ended at ");
                    buf.append(df.format(endTime));
                    buf.append(".");

                    jobStatusReporter.reportFinished(jobId, false, "finished", buf.toString());
                }
            }
        } catch (Exception e) {
            LOG.warn("Error processing email job", e);
        } finally {
            // this server must release lock
            lockManager.releaseLock(LOCK_CONSOLIDATED_EMAIL_JOB, serverId);
        }

    }
}

From source file:com.nordicsemi.nrfUARTspoon.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*  www.  j av  a 2s.c om*/
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    messageListView = (ListView) findViewById(R.id.listMessage);
    listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    messageListView.setAdapter(listAdapter);
    messageListView.setDivider(null);
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    btnSend = (Button) findViewById(R.id.sendButton);
    btnStartNewFile = (Button) findViewById(R.id.btn_start_new_file);
    edtMessage = (EditText) findViewById(R.id.sendText);
    fileMessage = (TextView) findViewById(R.id.fileStatusText);
    formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
    buttonGo = (Button) findViewById(R.id.btnGO);

    service_init();

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    // state of spoon buttons
    stateButtons = new Button[6];
    stateButtons[0] = (Button) this.findViewById(R.id.state0_button);
    stateButtons[1] = (Button) this.findViewById(R.id.state1_button);
    stateButtons[2] = (Button) this.findViewById(R.id.state2_button);
    stateButtons[3] = (Button) this.findViewById(R.id.state3_button);
    stateButtons[4] = (Button) this.findViewById(R.id.state4_button);
    stateButtons[5] = (Button) this.findViewById(R.id.state5_button);
    stateButtons[5].setEnabled(false);
    buttonState = 5;

    final CheckBox expert = (CheckBox) findViewById(R.id.ckBoxExpertMode);
    final ListView listViewData = (ListView) findViewById(R.id.listMessage);

    buttonGo.setVisibility(View.INVISIBLE);
    listViewData.setVisibility(ListView.INVISIBLE);

    //Expert Mode Option
    findViewById(R.id.ckBoxExpertMode).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (expert.isChecked()) {
                listViewData.setVisibility(ListView.VISIBLE);
            } else {
                listViewData.setVisibility(ListView.INVISIBLE);
            }
        }

    });
    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //initialize stable sample
            buttonGo.setVisibility(View.INVISIBLE);
            MainActivity.stable_counter = 0;

            if (!mBtAdapter.isEnabled()) {
                Log.i(TAG, "onClick - BT not enabled yet");
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                if (btnConnectDisconnect.getText().equals("Connect")) {

                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                    Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                } else {
                    //Disconnect button pressed
                    if (mDevice != null) {
                        mService.disconnect();

                    }
                }
            }
        }
    });
    // Handler Send button  
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.sendText);
            String message = editText.getText().toString();
            byte[] value;
            try {
                //send data to service
                value = message.getBytes("UTF-8");
                mService.writeRXCharacteristic(value);
                //Update the log with time stamp
                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                edtMessage.setText("");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    // Handler File button  
    btnStartNewFile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Close an open file
            if (isFileOpen) {
                btnStartNewFile.setText("Start new file");
                fileMessage.setText("File closed");
                try {
                    Log.i(TAG, "Closing old file");
                    isFileOpen = false;
                    theWriter.flush();
                    theWriter.close();
                    theWriter = null;
                } catch (IOException ioe) {
                    Log.e(TAG, "Could not close previous file");
                }
            } else {
                // Open a new file               
                btnStartNewFile.setText("End file");

                String currentDateTimeStringFile = formatter.format(new Date());
                currentDateTimeStringFile += ".txt";
                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
                path.mkdirs();
                File theFile = new File(path, currentDateTimeStringFile);
                try {
                    theWriter = new BufferedWriter(new FileWriter(theFile));
                } catch (IOException ioe) {
                    Log.e(TAG, "Buffered writer not created at" + theFile.getPath());
                    return;

                }
                fileMessage.setText("Writing to " + theFile.getPath());
                isFileOpen = true;
                fileTime = 0;
            }
        }
    });

    // Set initial UI state

}

From source file:com.oscarsalguero.solartracker.MainActivity.java

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;//from  w ww. ja v a  2  s. c o  m
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
    if (mLastLocation != null) {
        Log.d(LOG_TAG, "Location changed to (lat,lon): " + mLastLocation.getLatitude() + ","
                + mLastLocation.getLongitude());
        getSunInformation(mLastLocation);
    }
}

From source file:org.portlandrobotics.nrfUARTv2.MainActivity.java

public void log(String msg) {
    //Update the log with time stamp
    String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
    listAdapter.add("[" + currentDateTimeString + "] LOG: " + msg);
    messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
}

From source file:com.nordicsemi.nrfUARTv2.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from w  ww.ja  v a 2  s . c o  m*/
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    messageListView = (ListView) findViewById(R.id.listMessage);
    listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    messageListView.setAdapter(listAdapter);
    messageListView.setDivider(null);
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    btnConnectRight = (Button) findViewById(R.id.button);
    btnSend = (Button) findViewById(R.id.sendButton);
    edtMessage = (EditText) findViewById(R.id.sendText);
    service_init();

    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //should not be here, only for debug
            UploadData();
            //                if (!mBtAdapter.isEnabled()) {
            //                    Log.i(TAG, "onClick - BT not enabled yet");
            //                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            //                }
            //                else {
            //                    if (btnConnectDisconnect.getText().equals("Connect Left")){
            //
            //                        //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices
            //
            //                        Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
            //                        startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
            //                    } else {
            //                        //Disconnect button pressed
            //                        if (mDevice!=null)
            //                        {
            //                            mService.disconnect();
            //
            //                        }
            //                        if (mDevice2!=null)
            //                        {
            //                            mService2.disconnect();
            //
            //                        }
            //                        mCollecting = false;
            //                        UploadData();
            //                    }
            //                }
        }
    });

    btnConnectRight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mBtAdapter.isEnabled()) {
                Log.i(TAG, "onClick - BT not enabled yet");
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                if (btnConnectRight.getText().equals("Connect Right")) {

                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                    Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE2);
                } else {
                    //Disconnect button pressed
                    if (mDevice2 != null) {
                        mService2.disconnect();

                    }
                }
            }
        }
    });

    // Handler Send button  
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.sendText);
            String message = editText.getText().toString();
            byte[] value;
            try {
                //send data to service
                value = message.getBytes("UTF-8");
                mService.writeRXCharacteristic(value);
                //Update the log with time stamp
                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                edtMessage.setText("");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

    // Set initial UI state

}