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:com.nordicsemi.ImageTransferDemo.MainActivity.java

private void writeToLog(String message, AppLogFontType msgType) {
    String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
    String newMessage = currentDateTimeString + " - " + message;
    String fontHtmlTag;/*from  ww w .  jav  a 2  s  .c om*/
    switch (msgType) {
    case APP_NORMAL:
        fontHtmlTag = "<font color='#000000'>";
        break;
    case APP_ERROR:
        fontHtmlTag = "<font color='#AA0000'>";
        break;
    case PEER_NORMAL:
        fontHtmlTag = "<font color='#0000AA'>";
        break;
    case PEER_ERROR:
        fontHtmlTag = "<font color='#FF00AA'>";
        break;
    default:
        fontHtmlTag = "<font>";
        break;
    }
    mLogMessage = fontHtmlTag + newMessage + "</font>" + "<br>" + mLogMessage;
    mTextViewLog.setText(Html.fromHtml(mLogMessage));
}

From source file:com.example.lilach.alsweekathon_new.MainActivity.java

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

    ///////////////////////////////////////////
    try {//  w w  w  . j  a v a 2 s.c  om
        String yourFilePath = Environment.getExternalStorageDirectory() + "/"
                + "spiralStairs_CalInertialAndMag.csv";
        CSVReader reader = new CSVReader(new FileReader(yourFilePath));

        String[] nextLine;
        //skip the first line - headers
        reader.readNext();
        LinkedList<Signal> signals = new LinkedList<Signal>();

        for (int i = 0; i < 3; i++) {
            nextLine = reader.readNext();
            // while ((nextLine = reader.readNext()) != null) {
            // nextLine[] is an array of values from the line
            System.out.println(nextLine[0] + nextLine[1] + "etc...");
            Signal signal = new Signal();
            signal.setTimestamp(new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date()));
            signal.setPacketId(Integer.parseInt(nextLine[PACKET_NUMBER_INDEX]));
            signal.setAccelerometer(new XYZValues(Float.parseFloat(nextLine[ACCELEROMETER_X_INDEX]),
                    Float.parseFloat(nextLine[ACCELEROMETER_Y_INDEX]),
                    Float.parseFloat(nextLine[ACCELEROMETER_Z_INDEX])));
            signal.setGyro(new XYZValues(Float.parseFloat(nextLine[GYROSCOPE_X_INDEX]),
                    Float.parseFloat(nextLine[GYROSCOPE_Y_INDEX]),
                    Float.parseFloat(nextLine[GYROSCOPE_Z_INDEX])));

            signals.add(signal);

        }

        serverRequest sr = new serverRequest();
        sr.setSignals(signals);
        sr.setUserid("user");
        sr.setTimestamp("111111");

        //send the data to the server: Json, Post
        Gson gson = new Gson();
        String json = gson.toJson(sr);
        Log.d("aa", json);
        makeRequest("http://alsvm.cloudapp.net:8080/signals/user", json);
        // HttpResponse a = makeRequest("http://alsvm.cloudapp.net:8080/signals/user", json);
        // Log.d("httpResponse", a.toString());

        //            List myEntries = reader.readAll();
        //            System.out.println("size: " +myEntries.size());
        //            System.out.println("first item: "+myEntries.get(0));

    } catch (IOException e) {
        Log.d("exception: ", e.getMessage());
    }

    //////////////////////////////////////////////

    setContentView(R.layout.main);
    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);
    edtMessage = (EditText) findViewById(R.id.sendText);
    /// service_init();

    // 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();
            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

}

From source file:nz.co.wholemeal.christchurchmetro.PlatformActivity.java

/**
 * Fires a notification when the arrival is the given number of minutes
 * away from arriving at this stop.//from w w w .j a v a  2  s  . c  o m
 *
 * @param arrival The arrival that this alarm is set for
 * @param minutes The number of minutes before arrival the alert should be raised
 */
protected void createNotificationForArrival(Arrival arrival, int minutes) {
    Intent intent = new Intent(this, ArrivalNotificationReceiver.class);
    intent.putExtra("routeNumber", arrival.routeNumber);
    intent.putExtra("destination", arrival.destination);
    intent.putExtra("tripNumber", arrival.tripNumber);
    intent.putExtra("platformTag", current_stop.platformTag);
    intent.putExtra("minutes", minutes);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    /**
     * Calculate the time delay for this alarm.  We add 2 minutes to the
     * requested time in case the bus makes up time on it's journey from
     * when the user set the alarm.  In that case, the
     * ArrivalNotificationReceiver will take care of resetting itself if the
     * bus ETA is still greater than the requested number of minutes.
     */
    int delay = arrival.eta - (minutes + 2);

    Calendar calendar = Calendar.getInstance();

    /**
     * Set the time for comparison from the time the arrival was fetched,
     * not the current time.  The user may have had the screen loaded
     * for some time without refresh, so the arrival eta may no longer be
     * accurate.
     */
    long timestamp = current_stop.lastArrivalFetch;
    // Safety net
    if (timestamp == 0) {
        timestamp = System.currentTimeMillis();
    }

    calendar.setTimeInMillis(timestamp);
    calendar.add(Calendar.MINUTE, delay);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
    String alarmTime = DateFormat.getTimeInstance().format(calendar.getTime());
    Toast.makeText(this, String.format(getResources().getString(R.string.set_alarm_for_eta), minutes),
            Toast.LENGTH_LONG).show();
    Log.d(TAG, "Set alarm for " + minutes + " minutes - " + alarmTime);
}

From source file:com.shenqu.jlplayer.nRFUARTv2.MainActivity.java

private void onSendMsg() {
    EditText editText = (EditText) findViewById(R.id.sendText);
    String message = editText.getText().toString();
    try {/* w  ww. jav  a2 s  . c  o m*/
        byte[] value = message.getBytes("UTF-8");
        //send data to service
        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();
    }
}

From source file:com.google.android.gms.location.sample.locationupdates.MainActivity.java

/**
 * Updates the latitude, the longitude, and the last location time in the UI.
 *//*from ww  w. j a v a 2 s . c  o  m*/
private void updateUI() {
    try {
        mLatitudeTextView.setText(String.format("%s: %f", mLatitudeLabel, mCurrentLocation.getLatitude()));
        mLongitudeTextView.setText(String.format("%s: %f", mLongitudeLabel, mCurrentLocation.getLongitude()));

        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        mLastUpdateTimeTextView.setText(String.format("%s: %s", mLastUpdateTimeLabel, mLastUpdateTime));

        PostInformation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(),
                String.format("%s", mLastUpdateTime));
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:elbauldelprogramador.com.gpsqr.LocationUpdaterService.java

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "Connected to GoogleApiClient");
    }//  w  ww  .j  av  a2s  . com

    // If the initial location was never previously requested, we use
    // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
    // its value in the Bundle and check for it in onCreate(). We
    // do not request it again unless the user specifically requests location updates by pressing
    // the Start Updates button.
    //
    // Because we cache the value of the initial location in the Bundle, it means that if the
    // user launches the activity,
    // moves to a new location, and then changes the device orientation, the original location
    // is displayed as the activity is re-created.
    if (mCurrentLocation == null) {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        if (mCurrentLocation != null) {
            sendResult(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
            if (BuildConfig.DEBUG) {
                Log.d(TAG, mCurrentLocation.getLatitude() + ", " + mCurrentLocation.getLongitude());
            }
        }
    }

    // If the user presses the Start Updates button before GoogleApiClient connects, we set
    // mRequestingLocationUpdates to true (see startUpdatesButtonHandler()). Here, we check
    // the value of mRequestingLocationUpdates and if it is true, we start location updates.
    //        if (mRequestingLocationUpdates) {
    startLocationUpdates();
    //        }
}

From source file:elbauldelprogramador.com.gpsqr.LocationUpdaterService.java

@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;//from   ww w  .  j  a v a2 s. c om
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
    sendResult(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));

    if (BuildConfig.DEBUG) {
        Log.d(TAG, mCurrentLocation.getLatitude() + ", " + mCurrentLocation.getLongitude());
    }
}

From source file:com.mobileappsandroid.training.locationinclass.MainActivity.java

/**
 * Runs when a GoogleApiClient object successfully connects.
 *//*from   ww w  . j ava2s.  c om*/
@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");

    // If the initial location was never previously requested, we use
    // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
    // its value in the Bundle and check for it in onCreate(). We
    // do not request it again unless the user specifically requests location updates by pressing
    // the Start Updates button.
    //
    // Because we cache the value of the initial location in the Bundle, it means that if the
    // user launches the activity,
    // moves to a new location, and then changes the device orientation, the original location
    // is displayed as the activity is re-created.
    if (mCurrentLocation == null) {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    // If the user presses the Start Updates button before GoogleApiClient connects, we set
    // mRequestingLocationUpdates to true (see startUpdatesButtonHandler()). Here, we check
    // the value of mRequestingLocationUpdates and if it is true, we start location updates.
    if (mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}

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

public void logAction(String from, String to, byte[] data) {
    this.m_data = data;
    this.m_to = to;
    this.m_from = from;
    this.runOnUiThread(new Runnable() {
        public void run() {
            try {
                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                String text = new String(m_data, "UTF-8");
                String fmt_text = "(" + m_from + "->" + m_to + ") data: {" + text + "} len: " + text.length()
                        + " bytes";
                Log.d(TAG, "UART_UDP_PROXY[" + currentDateTimeString + "]: " + fmt_text);

                // simplify for the UI...
                fmt_text = "[" + currentDateTimeString + "]: (" + m_from + "->" + m_to + ") length: "
                        + text.length() + " bytes";

                // post to the UI
                listAdapter.add(fmt_text);
                messageListView.setAdapter(listAdapter);
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                listAdapter.notifyDataSetChanged();
                messageListView.invalidateViews();
            } catch (Exception ex) {
                Log.d(TAG, "Exception caught in logAction: " + ex.getMessage());
            }//  ww  w  .j a v  a2  s  . co  m
        }
    });
}

From source file:ro.tudorluca.gpstracks.android.MainActivity.java

/**
 * Runs when a GoogleApiClient object successfully connects.
 *//*from w  ww  . j  ava  2 s  .  c  o m*/
@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");

    //        if (DEBUG_MODE) {
    //            LocationServices.FusedLocationApi.setMockMode(mGoogleApiClient, true);
    //        }

    // If the initial location was never previously requested, we use
    // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
    // its value in the Bundle and check for it in onCreate(). We
    // do not request it again unless the user specifically requests location updates by pressing
    // the Start Updates button.
    //
    // Because we cache the value of the initial location in the Bundle, it means that if the
    // user launches the activity,
    // moves to a new location, and then changes the device orientation, the original location
    // is displayed as the activity is re-created.
    if (mCurrentLocation == null) {
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    // If the user presses the Start Updates button before GoogleApiClient connects, we set
    // mRequestingLocationUpdates to true (see startUpdatesButtonHandler()). Here, we check
    // the value of mRequestingLocationUpdates and if it is true, we start location updates.
    if (mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}