Example usage for android.content SharedPreferences getLong

List of usage examples for android.content SharedPreferences getLong

Introduction

In this page you can find the example usage for android.content SharedPreferences getLong.

Prototype

long getLong(String key, long defValue);

Source Link

Document

Retrieve a long value from the preferences.

Usage

From source file:org.alfresco.mobile.android.application.operations.sync.SynchroManager.java

public static long getStartSyncPrepareTimestamp(Context context, Account account) {
    if (account == null) {
        return -1;
    }//from w w  w  .j  av a 2  s .co  m
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    return sharedPref.getLong(LAST_START_SYNC_PREPARE + account.getId(), new Date().getTime());
}

From source file:foam.zizim.android.BoskoiService.java

public static void loadSettings(Context context) {
    final SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
    savePath = "/data/data/foam.zizim.android/files/";// settings.getString("savePath","/data/data/com.boskoi.android.app/files/");
    // domain = settings.getString("Domain", "");
    domain = "http://borrowed-scenery.org/zizim";
    firstname = settings.getString("Firstname", "");
    lastname = settings.getString("Lastname", "");
    lastUpdate = settings.getString("LastUpdate", "");
    lastId = settings.getLong("LastId", 0);
    email = settings.getString("Email", "");
    countries = settings.getInt("Countries", 0);
    AutoUpdateDelay = settings.getInt("AutoUpdateDelay", 5);
    // AutoFetch = settings.getBoolean("AutoFetch", false);
    AutoFetch = true;// ww w. j  a  v a2s .  com
    totalReports = settings.getString("TotalReports", "");
    smsUpdate = settings.getBoolean("SmsUpdate", false);
    username = settings.getString("Username", "");
    password = settings.getString("Password", "");
    language = settings.getString("Language", "");
    lastVersion = settings.getString("LastVersion", "");
    blogLastUpdate = settings.getLong("BlogLastUpdate", 0);

    // make sure folder exists
    final File dir = new File(BoskoiService.savePath);
    dir.mkdirs();
    if (!dir.exists()) {
        // Log.i("SavePath ","does not exist");
        try {
            dir.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.sindzinski.wetter.util.Utility.java

public static long getLastSync(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String lastSyncKey = context.getString(R.string.pref_last_sync);
    return prefs.getLong(lastSyncKey, 0);
}

From source file:gxu.software_engineering.market.android.activity.UserServiceActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.new_item:
        Intent intent = new Intent(this, NewItemActivity.class);
        startActivity(intent);//from   w  w  w.  j  a  va 2 s  .com
        break;
    case R.id.edit_ccontact:
        EditUserInfoBoxFragment contact = new EditUserInfoBoxFragment();
        Bundle contactArgs = new Bundle();
        contactArgs.putInt(C.USER_INFO_MODIFY_TYPE, C.CONTACT);
        contact.setArguments(contactArgs);
        contact.show(getSupportFragmentManager(), "contact");
        break;
    case R.id.edit_password:
        EditUserInfoBoxFragment pwd = new EditUserInfoBoxFragment();
        Bundle pwdArgs = new Bundle();
        pwdArgs.putInt(C.USER_INFO_MODIFY_TYPE, C.PASSWORD);
        pwd.setArguments(pwdArgs);
        pwd.show(getSupportFragmentManager(), "password");
        break;
    case R.id.logout:
        SharedPreferences prefs = app.getPrefs();
        long mills = prefs.getLong(C.LAST_SYNC, 0L);
        Editor edit = prefs.edit();
        edit.clear();
        edit.putLong(C.LAST_SYNC, mills);
        edit.commit();
        finish();
        break;
    default:
        break;
    }
    return false;
}

From source file:uk.org.rivernile.edinburghbustracker.android.Application.java

/**
 * Check for updates to the bus stop database. This may happen automatically
 * if 24 hours have elapsed since the last check, or if the user has forced
 * the action. If a database update is found, then the new database is
 * downloaded and placed in the correct location.
 * //from   w  ww  .j a  v  a  2 s .  c  o m
 * @param context The context.
 * @param force True if the user forced the check, false if not.
 */
public static void checkForDBUpdates(final Context context, final boolean force) {
    // Check to see if the user wants their database automatically updated.
    final SharedPreferences sp = context.getSharedPreferences(PreferencesActivity.PREF_FILE, 0);
    final boolean autoUpdate = sp.getBoolean(PREF_DATABASE_AUTO_UPDATE, true);
    final SharedPreferences.Editor edit = sp.edit();

    // Continue to check if the user has enabled it, or a check has been
    // forced (from the Preferences).
    if (autoUpdate || force) {
        if (!force) {
            // If it has not been forced, check the last update time. It is
            // only checked once per day. Abort if it is too soon.
            long lastCheck = sp.getLong("lastUpdateCheck", 0);
            if ((System.currentTimeMillis() - lastCheck) < 86400000)
                return;
        }

        // Construct the checking URL.
        final StringBuilder sb = new StringBuilder();
        sb.append(DB_API_CHECK_URL);
        sb.append(ApiKey.getHashedKey());
        sb.append("&random=");
        // A random number is used so networks don't cache the HTTP
        // response.
        sb.append(random.nextInt());
        try {
            // Do connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                // Read the incoming data.
                int data;
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String topoId;
        try {
            // Parse the JSON and get the topoId from it.
            final JSONObject jo = new JSONObject(sb.toString());
            topoId = jo.getString("topoId");
        } catch (JSONException e) {
            return;
        }

        // If there's topoId then it cannot continue.
        if (topoId == null || topoId.length() == 0)
            return;

        // Get the current topoId from the database.
        final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext());
        final String dbTopoId = bsd.getTopoId();

        // If the topoIds match, write our check time to SharedPreferences.
        if (topoId.equals(dbTopoId)) {
            edit.putLong("lastUpdateCheck", System.currentTimeMillis());
            edit.commit();
            if (force) {
                // It was forced, alert the user there is no update
                // available.
                Looper.prepare();
                Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
                Looper.loop();
            }
            return;
        }

        // There is an update available. Empty the StringBuilder then create
        // the URL to get the new database information.
        sb.setLength(0);
        sb.append(DB_UPDATE_CHECK_URL);
        sb.append(random.nextInt());
        sb.append("&key=");
        sb.append(ApiKey.getHashedKey());

        try {
            // Connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                int data;
                // Read the incoming data.
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String dbUrl, schemaVersion, checksum;
        try {
            // Get the data from tje returned JSON.
            final JSONObject jo = new JSONObject(sb.toString());
            dbUrl = jo.getString("db_url");
            schemaVersion = jo.getString("db_schema_version");
            topoId = jo.getString("topo_id");
            checksum = jo.getString("checksum");
        } catch (JSONException e) {
            // There was an error parsing the JSON, it cannot continue.
            return;
        }

        // Make sure the returned schema name is compatible with the one
        // the app uses.
        if (!BusStopDatabase.SCHEMA_NAME.equals(schemaVersion))
            return;
        // Some basic sanity checking on the parameters.
        if (topoId == null || topoId.length() == 0)
            return;
        if (dbUrl == null || dbUrl.length() == 0)
            return;
        if (checksum == null || checksum.length() == 0)
            return;

        // Make sure an update really is available.
        if (!topoId.equals(dbTopoId)) {
            // Update the database.
            updateStopsDB(context, dbUrl, checksum);
        } else if (force) {
            // Tell the user there is no update available.
            Looper.prepare();
            Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
            Looper.loop();
        }

        // Write to the SharedPreferences the last update time.
        edit.putLong("lastUpdateCheck", System.currentTimeMillis());
        edit.commit();
    }
}

From source file:com.Candy.ota.settings.Settings.java

private int getUpdateInterval() {
    SharedPreferences prefs = getSharedPreferences(LAST_INTERVAL, 0);
    long value = prefs.getLong(LAST_INTERVAL, 0);
    int settingsValue;
    if (value == AlarmManager.INTERVAL_DAY) {
        settingsValue = 0;// ww  w  .ja  va 2s .c  o m
    } else if (value == AlarmManager.INTERVAL_HALF_DAY || value == 0) {
        settingsValue = 1;
    } else if (value == AlarmManager.INTERVAL_HOUR) {
        settingsValue = 2;
    } else {
        settingsValue = 3;
    }
    return settingsValue;
}

From source file:net.eledge.android.europeana.service.task.BlogDownloadTask.java

public void execute() {
    DateTime lastViewed = DateTime.now();

    SharedPreferences settings = mContext.getSharedPreferences(Preferences.BLOG, 0);
    long time = settings.getLong(Preferences.BLOG_LAST_VIEW, -1);
    if (time != -1) {
        lastViewed = new DateTime(new Date(time));
    }/*from w w w  .j  ava2s.co m*/
    mRssReaderTask = new RssReader(lastViewed, this);
    mRssReaderTask.execute(UriHelper.URL_BLOGFEED);
}

From source file:it.geosolutions.geocollect.android.core.mission.utils.MissionUtils.java

/**
 * get "created" {@link MissionFeature} from the database, adding the distance property if possible
 * @param tableName/*from   www  . j  a v a 2s  .c om*/
 * @param db
 * @return a list of created {@link MissionFeature}
 */
public static ArrayList<MissionFeature> getMissionFeatures(final String mTableName, final Database db,
        Context ctx) {

    ArrayList<MissionFeature> mFeaturesList = new ArrayList<MissionFeature>();

    String tableName = mTableName;

    // Reader for the Geometry field
    WKBReader wkbReader = new WKBReader();

    //create query
    ////////////////////////////////////////////////////////////////
    // SQLite Geometry cannot be read with direct wkbreader
    // We must do a double conversion with ST_AsBinary and CastToXY 
    ////////////////////////////////////////////////////////////////

    // Cycle all the columns to find the "Point" type one
    HashMap<String, String> columns = SpatialiteUtils.getPropertiesFields(db, tableName);
    if (columns == null) {
        if (BuildConfig.DEBUG) {
            Log.w(TAG, "Cannot retrieve columns from database");
        }
        return mFeaturesList;
    }

    List<String> selectFields = new ArrayList<String>();
    for (String columnName : columns.keySet()) {
        //Spatialite custom field point
        if ("point".equalsIgnoreCase(columns.get(columnName))) {
            selectFields.add("ST_AsBinary(CastToXY(" + columnName + ")) AS GEOMETRY");
        } else {
            selectFields.add(columnName);
        }
    }

    // Merge all the column names
    String selectString = TextUtils.join(",", selectFields);

    if (ctx != null) {

        SharedPreferences prefs = ctx.getSharedPreferences(SQLiteCascadeFeatureLoader.PREF_NAME,
                Context.MODE_PRIVATE);

        boolean useDistance = prefs.getBoolean(SQLiteCascadeFeatureLoader.ORDER_BY_DISTANCE, false);
        double posX = Double.longBitsToDouble(
                prefs.getLong(SQLiteCascadeFeatureLoader.LOCATION_X, Double.doubleToLongBits(0)));
        double posY = Double.longBitsToDouble(
                prefs.getLong(SQLiteCascadeFeatureLoader.LOCATION_Y, Double.doubleToLongBits(0)));

        if (useDistance) {
            selectString = selectString + ", Distance(ST_Transform(GEOMETRY,4326), MakePoint(" + posX + ","
                    + posY + ", 4326)) * 111195 AS '" + MissionFeature.DISTANCE_VALUE_ALIAS + "'";
        }

        //Add Spatial filtering
        int filterSrid = prefs.getInt(SQLiteCascadeFeatureLoader.FILTER_SRID, -1);
        // If the SRID is not defined, skip the filter
        if (filterSrid != -1) {
            double filterN = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_N, Double.doubleToLongBits(0)));
            double filterS = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_S, Double.doubleToLongBits(0)));
            double filterW = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_W, Double.doubleToLongBits(0)));
            double filterE = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_E, Double.doubleToLongBits(0)));

            tableName += " WHERE MbrIntersects(GEOMETRY, BuildMbr(" + filterW + ", " + filterN + ", " + filterE
                    + ", " + filterS + ")) ";
        }

    }

    // Build the query
    StringWriter queryWriter = new StringWriter();
    queryWriter.append("SELECT ").append(selectString).append(" FROM ").append(tableName).append(";");

    // The resulting query
    String query = queryWriter.toString();

    Stmt stmt;
    //do the query
    if (jsqlite.Database.complete(query)) {
        try {
            if (BuildConfig.DEBUG) {
                Log.i("getCreatedMissionFeatures", "Loading from query: " + query);
            }
            stmt = db.prepare(query);
            MissionFeature f;
            while (stmt.step()) {
                f = new MissionFeature();

                SpatialiteUtils.populateFeatureFromStmt(wkbReader, stmt, f);

                if (f.geometry == null) {
                    //workaround for a bug which does not read out the "Point" geometry in WKBreader
                    //read single x and y coordinates instead and create the geometry by hand
                    double[] xy = PersistenceUtils.getXYCoord(db, tableName, f.id);
                    if (xy != null) {
                        GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326);
                        f.geometry = geometryFactory.createPoint(new Coordinate(xy[0], xy[1]));
                    }
                }
                f.typeName = mTableName;
                mFeaturesList.add(f);
            }
            stmt.close();
        } catch (Exception e) {
            Log.d(TAG, "Error getCreatedMissions", e);
        }
    } else {
        if (BuildConfig.DEBUG) {
            Log.w(TAG, "Query is not complete: " + query);
        }
    }

    return mFeaturesList;
}

From source file:eu.istvank.apps.lenslog.receivers.NotifyAlarmReceiver.java

/**
 * Sets a repeating alarm that runs once a day at approximately 8:30 a.m. When the
 * alarm fires, the app broadcasts an Intent to this WakefulBroadcastReceiver.
 * @param context//  w  w  w  .  ja v  a 2 s  .c  o m
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public void setAlarm(Context context) {
    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, NotifyAlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    // get notification time from preferences
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    long notificationTime = sp.getLong(SettingsFragment.KEY_PREF_NOTIFICATION_TIME, 50400000);

    Calendar calendar = Calendar.getInstance();
    //TODO: if the time has passed already, set it to tomorrow.
    calendar.setTimeInMillis(notificationTime);

    // The following line is for debug only
    //alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);

    // Set the alarm to fire according to the device's clock, and to repeat once a day.
    alarmMgr.setInexactRepeating(AlarmManager.RTC, notificationTime, AlarmManager.INTERVAL_DAY, alarmIntent);

    // Enable {@code SampleBootReceiver} to automatically restart the alarm when the
    // device is rebooted.
    ComponentName receiver = new ComponentName(context, NotifyAlarmReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:it.polimi.spf.demo.couponing.provider.WelcomeMessageFragment.java

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

    mTitleInput = (EditText) root.findViewById(R.id.welcome_message_title_input);
    mTextInput = (EditText) root.findViewById(R.id.welcome_message_text_input);
    mActive = (CheckBox) root.findViewById(R.id.welcome_message_active);

    SharedPreferences prefs = getSharedPreferences();
    if (prefs.getLong(KEY_TRIGGER_ID, -1) != -1) {
        mActive.setChecked(true);//from w  w w  . ja  v  a2s .c om
        mTitleInput.setText(prefs.getString(KEY_MESSAGE_TITLE, null));
        mTextInput.setText(prefs.getString(KEY_MESSAGE_TEXT, null));
    }

    mActive.setOnCheckedChangeListener(mActiveToggleListener);
    return root;
}