Example usage for android.content SharedPreferences getInt

List of usage examples for android.content SharedPreferences getInt

Introduction

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

Prototype

int getInt(String key, int defValue);

Source Link

Document

Retrieve an int value from the preferences.

Usage

From source file:com.dwdesign.tweetings.util.Utils.java

public static HttpClientWrapper getImageLoaderHttpClient(final Context context) {
    if (context == null)
        return null;
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int timeout_millis = prefs.getInt(PREFERENCE_KEY_CONNECTION_TIMEOUT, 10000) * 1000;
    final Proxy proxy = getProxy(context);
    final String user_agent = getBrowserUserAgent(context);
    // final HostAddressResolver resolver =
    // TwidereApplication.getInstance(context).getHostAddressResolver();
    final HostAddressResolver resolver = null;
    return getHttpClient(timeout_millis, true, proxy, resolver, user_agent);
}

From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java

/**
 * /*from ww  w. j a v  a2s  . com*/
 */
private void preferencesUpdate() {
    final SharedPreferences preferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

    //remove control server version on start
    ConfigHelper.setControlServerVersion(this, null);

    final Context context = getApplicationContext();
    final PackageInfo pInfo;
    final int clientVersion;
    try {
        pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        clientVersion = pInfo.versionCode;

        final int lastVersion = preferences.getInt("LAST_VERSION_CODE", -1);
        if (lastVersion == -1 || lastVersion <= 17) {
            preferences.edit().clear().commit();
            Log.d(DEBUG_TAG, "preferences cleared");
        }

        if (lastVersion != clientVersion)
            preferences.edit().putInt("LAST_VERSION_CODE", clientVersion).commit();
    } catch (final NameNotFoundException e) {
        Log.e(DEBUG_TAG, "version of the application cannot be found", e);
    }
}

From source file:me.piebridge.bible.Bible.java

private void checkApkData() {
    Log.d(TAG, "checking apkdata");
    try {/*from   w  w  w .j a va 2  s.  c  om*/
        String packageName = mContext.getPackageName();
        PackageManager pm = mContext.getPackageManager();
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(mContext);
        ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
        for (String applicationName : pm.getPackagesForUid(ai.uid)) {
            if (packageName.equals(applicationName)) {
                continue;
            }

            // version
            String version = applicationName.replace(packageName + ".", "");

            // resources
            Resources resources = mContext
                    .createPackageContext(applicationName, Context.CONTEXT_IGNORE_SECURITY).getResources();

            // newVersion
            int versionCode = pm.getPackageInfo(applicationName, 0).versionCode;
            boolean newVersion = (preference.getInt(version, 0) != versionCode);

            // resid
            int resid = resources.getIdentifier("a", "raw", applicationName);
            if (resid == 0) {
                resid = resources.getIdentifier("xa", "raw", applicationName);
            }
            if (resid == 0) {
                Log.d(TAG, "package " + applicationName + " has no R.raw.a nor R.raw.xa");
                continue;
            }

            // file
            File file;
            if (versionpaths.containsKey(version)) {
                file = new File(versionpaths.get(version));
            } else {
                file = new File(getExternalFilesDirWrapper(), version + ".sqlite3");
            }
            if (file.exists() && !file.isFile()) {
                file.delete();
            }

            boolean unpack = unpackRaw(resources, newVersion, resid, file);
            if (newVersion && unpack) {
                preference.edit().putInt(version, versionCode).commit();
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "", e);
    }
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static int getUserColor(final Context context, final long user_id) {
    if (context == null)
        return Color.TRANSPARENT;
    Integer color = sUserColors.get(user_id);
    if (color == null) {
        final SharedPreferences prefs = context.getSharedPreferences(USER_COLOR_PREFERENCES_NAME,
                Context.MODE_PRIVATE);
        color = prefs.getInt(Long.toString(user_id), Color.TRANSPARENT);
        sUserColors.put(user_id, color);
    }/* ww  w  .ja  v  a 2  s.co  m*/
    return color != null ? color : Color.TRANSPARENT;
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().setBackgroundDrawableResource(R.drawable.chat_bg);
    // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    recipientStkid = getIntent().getExtras().getString("recipientStkid");
    chatRecipient = getIntent().getExtras().getString("chatRecipient");
    chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
    senderToken = getIntent().getExtras().getString("senderToken");
    recipientToken = getIntent().getExtras().getString("recipientToken");
    noti = getIntent().getExtras().getBoolean("noti");
    message = getIntent().getExtras().getString("message");
    rows = getIntent().getExtras().getInt("rows");
    flagChatting = true;/* w w w.  j a v  a2s .  c om*/
    pref = PreferenceManager.getDefaultSharedPreferences(this);
    offerId = 0;
    offerStatus = 0;
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);
    dialog = new ProgressDialog(this);
    listChatContact = new ArrayList<>();
    listChatContact = dbHelper.getChatContact();
    Log.i(" Chat Contact ", " " + listChatContact.size());
    metrics = this.getResources().getDisplayMetrics();
    //to change font
    faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
    Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
    faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

    imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited()) {
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }

    start = new Date();
    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
    timeSend = oFormat.format(start);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    layoutTalk = (LinearLayout) findViewById(R.id.layoutTalk);
    txtUserName = (TextView) findViewById(R.id.txtChatName);
    edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
    imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
    imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
    lv = (ListView) findViewById(R.id.listView1);
    layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
    txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
    txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
    txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
    txtLabel2.setText(" " + chatRecipient + " ");
    txtLabel1.setTypeface(faceLight);
    txtLabel2.setTypeface(faceRegular);
    txtLabel3.setTypeface(faceLight);

    for (ChatContact contact : listChatContact) {
        if (contact.getContactId().equals(recipientStkid)) {
            imgViewAddCon.setVisibility(View.INVISIBLE);
            layoutLabel.setVisibility(View.GONE);
            break;
        }
    }
    Log.i(TAG, " come back again");
    adapter = new ChatArrayAdapter(this, R.layout.chatting_listview, faceSemi_bold, faceRegular, recipientStkid,
            senderToken, recipientToken);
    lv.setAdapter(adapter);
    // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    // BEGIN_INCLUDE (change_colors)
    // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
    swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
            R.color.swipe_color_4);
    limitMsg = 7;
    // END_INCLUDE (change_colors)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
            if (limitMsg < rows) {
                Log.i("Limit Message ", " " + limitMsg);
                limitMsg *= 2;
                fetchRecords();
            } else if ((!(rows <= 7)) && limitMsg > rows && (limitMsg - rows < 7)) {
                fetchRecords();
            } else {
                Log.i("No data ", "to refresh");
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
            }
            // initiateRefresh();
        }
    });

    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
    View header = inflator.inflate(R.layout.header, null);

    TextView textView = (TextView) header.findViewById(R.id.textView1);
    textView.setText("StikyChat");
    textView.setTypeface(faceSemi_bold);
    textView.setVisibility(View.VISIBLE);
    headerLayout.addView(header);
    LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
    layoutRight.setVisibility(View.GONE);

    txtUserName.setText(chatRecipient);
    Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
    txtUserName.setTypeface(faceSemi_bold);

    String url = "";

    Log.i(TAG, " ^^^ " + chatRecipientUrl + " ");
    if (chatRecipientUrl != null) {
        if (chatRecipientUrl.contains("http")) {
            url = chatRecipientUrl;
        } else if (chatRecipientUrl != "null") {
            url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
        }
    }
    addAndroidUniversalImageLoader(imgViewProfile, url);
    //        if (noti && (!message.equals(""))) {
    //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
    //            lv.smoothScrollToPosition(adapter.getCount() - 1);
    //        }

    //to show history chats between two users(sender & recipient)
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
    listHistory = dbHelper.getStikyChat();
    if (listHistory.size() > 0) {
        Collections.reverse(listHistory);
        for (final StikyChatTb chatTb : listHistory) {
            String getDate = chatTb.getSendDate();
            String durationStr = null;
            String fromStikyBee = chatTb.getSender();
            try {
                final String createDate = dateFormat2.format(dateFormat.parse(getDate));
                if (chatTb.getFileName().contains("voice")) {
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);

                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    // Log.i(TAG, "Duration Srt " + durationStr);
                }
                if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                    //String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    // Log.i(TAG, " Offer Id " + chatTb.getOfferId() + " Price " + chatTb.getPrice() + " Name " + chatTb.getName());
                    //first false = right, second false = Offer
                    //  Log.i(TAG, " Duration " + chatTb.getRate() + " File Name " + chatTb.getFileName());
                    if (!chatTb.getFileName().contains("voice")) {
                        Log.i(TAG, " Voice is not ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        Log.i(TAG, " Voice is ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                } else {
                    /* Bitmap bmImg = BitmapFactory.decodeFile(getResources().getString(R.string.url) + "/" + chatTb.getFileName());
                     Bitmap resBm = getResizedBitmap(bmImg, 500);*/
                    // String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    if (!chatTb.getFileName().contains("voice")) {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                }
                lv.smoothScrollToPosition(adapter.getCount() - 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            fileNameGCM = sharedPreferences.getString("fileName", "");
            messageGCM = sharedPreferences.getString("message", "");
            offerIdGCM = sharedPreferences.getInt("offerId", 0);
            offerStatusGCM = sharedPreferences.getInt("offerStatus", 0);
            priceGCM = sharedPreferences.getString("price", "");
            rateGCM = sharedPreferences.getString("rate", "");
            nameGCM = sharedPreferences.getString("name", "");
            recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
            recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
            recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
            recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
            senderTokenGCM = sharedPreferences.getString("senderToken", "");

            Log.i(TAG, " FileName GCM " + fileNameGCM + " " + " Name Rate Price &&&&& *** " + messageGCM + " "
                    + priceGCM + " " + rateGCM);
            if (firstConnect) {
                if (recipientStkidGCM.trim() == recipientStkid.trim()
                        || recipientStkidGCM.equals(recipientStkid)) {
                    MyGcmListenerService.flagSendNoti = false;
                    Log.i(TAG, " " + message);
                    // (1) get today's date
                    start = new Date();
                    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                    timeSend = oFormat.format(start);

                    Log.i(TAG, "First connect " + firstConnect);
                    Log.i(TAG, " File Name GCMMMMMM " + fileNameGCM);
                    /*if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    oriFName = saveFileAndImage(fileNameGCM);
                    }*/
                    /*if (fileNameGCM.contains("voice")) {
                    String durationStr;
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + fileNameGCM;
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                            
                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);
                            
                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, durationStr, null, oriFName);
                    adapter.add(stikyChat);
                    } else {*/
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend,
                            fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, nameGCM, null,
                            oriFName);
                    adapter.add(stikyChat);
                    //  }
                    Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                    Log.i(TAG, "User " + txtUserName.getText().toString());

                    adapter.notifyDataSetChanged();
                    lv.setSelection(adapter.getCount() - 1);
                    new regTask2().execute("Obj ");
                } else {
                    /* if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    saveFileAndImage(fileNameGCM);
                     }*/
                    Log.i(TAG, "..." + recipientStkidGCM.trim());
                    Log.i(TAG, "&&&" + recipientStkid.trim());
                    Log.i(TAG, "else casee");
                    //notificaton send
                    flagNotifi = true;
                    new regTask2().execute("Notification");
                }
                firstConnect = false;
            }
            lv.setSelection(adapter.getCount() - 1);
        }
    };

    /*edTxtMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
      Toast.makeText(getBaseContext(),
                ((EditText) v).getId() + " has focus - " + hasFocus,
                Toast.LENGTH_LONG).show();
    }
    });*/
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    edTxtMsg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutTalk.setLayoutParams(params);
            layoutTalk.setGravity(Gravity.CENTER);
            flagRecord = false;
            /*getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
            );*/
            Toast.makeText(getBaseContext(), "Touch ...", Toast.LENGTH_LONG).show();
            return false;
        }
    });
}

From source file:com.ichi2.anki.DeckPicker.java

private void upgradePreferences(int previousVersionCode) {
    SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
    // clear all prefs if super old version to prevent any errors
    if (previousVersionCode < 20300130) {
        preferences.edit().clear().commit();
    }/*from   w  w  w  .j av  a2  s .  c o m*/
    // when upgrading from before 2.5alpha35
    if (previousVersionCode < 20500135) {
        // Card zooming behaviour was changed the preferences renamed
        int oldCardZoom = preferences.getInt("relativeDisplayFontSize", 100);
        int oldImageZoom = preferences.getInt("relativeImageSize", 100);
        preferences.edit().putInt("cardZoom", oldCardZoom).commit();
        preferences.edit().putInt("imageZoom", oldImageZoom).commit();
        if (!preferences.getBoolean("useBackup", true)) {
            preferences.edit().putInt("backupMax", 0).commit();
        }
        preferences.edit().remove("useBackup").commit();
        preferences.edit().remove("intentAdditionInstantAdd").commit();
    }

    if (preferences.contains("fullscreenReview")) {
        // clear fullscreen flag as we use a integer
        try {
            boolean old = preferences.getBoolean("fullscreenReview", false);
            preferences.edit().putString("fullscreenMode", old ? "1" : "0").commit();
        } catch (ClassCastException e) {
            // TODO:  can remove this catch as it was only here to fix an error in the betas
            preferences.edit().remove("fullscreenMode").commit();
        }
        preferences.edit().remove("fullscreenReview").commit();
    }
}

From source file:com.kaytat.simpleprotocolplayer.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);

    mIPAddrList = getListFromPrefs(myPrefs, IP_JSON_PREF, IP_PREF);
    mIPAddrAdapter = new NoFilterArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mIPAddrList);
    mIPAddrText.setAdapter(mIPAddrAdapter);
    mIPAddrText.setThreshold(1);/*w  ww  .  j a  v a2s  .c  om*/
    if (mIPAddrList.size() != 0) {
        mIPAddrText.setText((String) mIPAddrList.get(0));
    }

    mAudioPortList = getListFromPrefs(myPrefs, PORT_JSON_PREF, PORT_PREF);
    mAudioPortAdapter = new NoFilterArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            mAudioPortList);
    mAudioPortText.setAdapter(mAudioPortAdapter);
    mAudioPortText.setThreshold(1);
    if (mAudioPortList.size() != 0) {
        mAudioPortText.setText((String) mAudioPortList.get(0));
    }

    // These hard-coded values should match the defaults in the strings array
    Resources res = getResources();
    /* FIXME broken on Android TV?
    mSampleRate = myPrefs.getInt(RATE_PREF, MusicService.DEFAULT_SAMPLE_RATE);
    String rateString = Integer.toString(mSampleRate);
    String[] sampleRateStrings = res.getStringArray(R.array.sampleRates);
    for (int i = 0; i < sampleRateStrings.length; i++) {
    if (sampleRateStrings[i].contains(rateString)) {
        Spinner sampleRateSpinner = (Spinner) findViewById(R.id.spinnerSampleRate);
        sampleRateSpinner.setSelection(i);
        break;
    }
    }
    */
    /* FIXME broken on Android TV?
    mStereo = myPrefs.getBoolean(STEREO_PREF, MusicService.DEFAULT_STEREO);
    String[] stereoStrings = res.getStringArray(R.array.stereo);
    Spinner stereoSpinner = (Spinner) findViewById(R.id.stereo);
    String stereoKey = getResources().getString(R.string.stereoKey);
    if (stereoStrings[0].contains(stereoKey) == mStereo) {
    stereoSpinner.setSelection(0);
    } else {
    stereoSpinner.setSelection(1);
    }
    */
    mBufferMs = myPrefs.getInt(BUFFER_MS_PREF, 50);
    Log.d(TAG, "mBufferMs:" + mBufferMs);
    EditText e = (EditText) findViewById(R.id.editTextBufferSize);
    //e.setText(Integer.toString(mBufferMs)); // FIXME broken on Android TV?
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

public static Object prefs_readPreference(Context ctx, String prefName, String key, Class<?> valueType) {
    SharedPreferences prefs = ctx.getSharedPreferences(prefName, Context.MODE_PRIVATE);

    if (valueType == Long.class) {
        return prefs.getLong(key, Long.valueOf(-1));
    } else if (valueType == Boolean.class) {
        return prefs.getBoolean(key, Boolean.valueOf(false));
    } else if (valueType == Float.class) {
        return prefs.getFloat(key, Float.valueOf(-1));
    } else if (valueType == Integer.class) {
        return prefs.getInt(key, Integer.valueOf(-1));
    } else if (valueType == String.class) {
        return prefs.getString(key, null);
    } else if (valueType == Set.class) {
        //return prefs.getStringSet(key, null); //Only from 11 API level.
        return getSetListFromCommaSeparatedString(ctx, prefName, key);
    }/*w  ww.  j  a va  2s .  c om*/

    return null;
}