【问题标题】:SharedPreferences Value Continues to Return as Zero - Cannot Retrieve Value of 'Data' StringSharedPreferences 值继续返回为零 - 无法检索“数据”字符串的值
【发布时间】:2013-06-27 17:29:52
【问题描述】:

我试图从 SharedPreferences 中提取字节交换的 MDN 值,但它继续返回零值 - 当它应该返回字节交换的 MDN 时。

我使用以下格式保存它:

editor.putString(new String("data"), Integer.toString(0));

并使用以下格式获取它:

 String info = String.format("USI%sCN%s,WN%s", tag + status
                        + tag + settings.getString("data", Integer.toString(0)) + tag + DToDevice + tag, mobileStr,
                        totalStr + settings.getString("last_month", "0"));

但是,值继续返回为零,而不是我预期的字节交换 MDN。

如何通过 SharedPreferences 保存和检索 byteswapped MDN 值的值?

来源:

public class DataCountService extends Service {
String text = "USR;1";
String ERROR = Constants.PREFS_NAME;
private Timer timer = new Timer();
private long period;
private long delay_interval;

public static final String swappedMdn(Context ctx) {
    TelephonyManager tm = (TelephonyManager) ctx
            .getSystemService(Context.TELEPHONY_SERVICE);
    // Extract the phone number from the TelephonyManager instance
    String mdn = tm.getLine1Number();
    // Insure MDN is 10 characters
    if (mdn.length() < 10 || mdn == null)
        mdn = "0000000000";
    // Extract last 10 digits of MDN
    if (mdn.length() > 10)
        mdn = mdn.substring(mdn.length() - 10, mdn.length());
    char data[] = mdn.toCharArray();
    char digit;
    for (int index = 0; index < mdn.length() - (mdn.length()) % 2; index += 2) {
        digit = data[index];
        data[index] = data[index + 1];
        data[index + 1] = digit;

         Intent i = new Intent(ctx, DataCountService.class);


            SharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);
            Editor editor = settings.edit();
            editor.putString(new String("data"), Integer.toString(0));
            editor.commit();

    }

    return String.valueOf(data);

}


private Intent getIntent() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(Constants.TAG, "Logging Service Started");
    // super.onStartCommand(intent, flags, startId);

    Bundle extras = intent.getExtras();

    if (intent == null) {
        // Exit gracefully is service not started by intent
        Log.d(Constants.TAG, "Error: Null Intent");
    } else {

        if (extras != null) {
            text = extras.getString(Constants.DM_SMS_CONTENT);
            // check for Enable or Disable Value - if set to enable
            // check for Enable or Disable Value - if set to enable
            if (extras.getString(Constants.DM_SMS_CONTENT).contains(
                    "//USR;1")) {

                // get Wifi and Mobile traffic info
                double totalBytes = (double) TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes();
                double mobileBytes = TrafficStats.getMobileRxBytes()
                        + TrafficStats.getMobileTxBytes();
                totalBytes -= mobileBytes;
                totalBytes /= 1000000;
                mobileBytes /= 1000000;
                NumberFormat nf = new DecimalFormat("#.###");

                Intent i = new Intent(this, DataCountService.class);

                StartActivity(i);

                Intent MDN = new Intent(this, MDNByteswapService.class);

                StartActivity(MDN);

                // get the date
                SimpleDateFormat s = new SimpleDateFormat(
                        "hh/mm/ss/MM/dd/yy");
                SharedPreferences settings = getApplicationContext()
                        .getSharedPreferences(Constants.PREFS_NAME, 0);
                String tag = ";";


                //String mdn = extras.getString(DataCountUtilities.swappedMdn(this));
                String mobileStr = nf.format(mobileBytes);
                String totalStr = nf.format(totalBytes);
                String DToDevice = s.format(new Date());
                String status = (settings.getString("status", "0"));
                String info = String.format("USI%sCN%s,WN%s", tag + status
                        + tag + settings.getString("data", Integer.toString(0)) + tag + DToDevice + tag, mobileStr,
                        totalStr + settings.getString("last_month", "0"));

                info = "USI" + info.replace("USI", "");
                // info = (info.replace("CN", "CO")).replace("WN", "WO");
                StringBuilder b = new StringBuilder(info);
                b.replace(info.lastIndexOf("CN") - 1,
                        info.lastIndexOf("CN") + 2, "CO");
                b.replace(info.lastIndexOf("WN") - 1,
                        info.lastIndexOf("WN") + 2, "WO");
                info = b.toString();

                // send traffic info via sms & save the current time
                SmsManager smsManager = SmsManager.getDefault();
                if (Config.DEVELOPMENT) {
                    String shortCode = settings.getString(
                            Constants.PREFS_KEY_SHORT_CODE,
                            Constants.DEFAULT_SHORT_CODE);
                    smsManager.sendTextMessage(shortCode, null, info, null,
                            null);
                    // set status to enabled

                    Editor editor = settings.edit();
                    editor.putString("status", "1");
                    editor.commit();
                    editor.putLong("smstimestamp",
                            System.currentTimeMillis());
                    editor.commit();

                } else {
                    SmsManager ackSMS = SmsManager.getDefault();
                    smsManager.sendTextMessage(
                            Constants.DEFAULT_SHORT_CODE, null, info, null,
                            null);
                }

                // check for Enable or Disable Value - if set to disable
            }
        } else if (extras.getString(Constants.DM_SMS_CONTENT).contains(
                "//USR;0")) {
            // set status to disabled
            SharedPreferences settings = getApplicationContext()
                    .getSharedPreferences(Constants.PREFS_NAME, 0);
            Editor editor = settings.edit();
            editor.putString("status", "0");
            editor.commit();
            stopSelf();

            // check for Enable or Disable Value - if set to any other
            // character
        }

        return START_STICKY;
    }
    return startId;
}

private void StartActivity(android.content.Intent i) {
    // TODO Auto-generated method stub

}

private Intent Intent() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {

    if (Config.DEVELOPMENT) {

        period = Constants.PERIOD;
        delay_interval = Constants.DELAY_INTERVAL;

    } else {
        Bundle extras = getIntent().getExtras();
        period = Constants.DEBUG_PERIOD;
        delay_interval = Constants.DEBUG_DELAY_INTERVAL;
    }
    startServiceTimer();
}

private void startServiceTimer() {
    timer.schedule(new TimerTask() {
        public void run() {

            SharedPreferences settings = getApplicationContext()
                    .getSharedPreferences(Constants.PREFS_NAME, 0);
            if (settings.getString("status", "0").equals(1)) {

                // get Wifi and Mobile traffic info
                double totalBytes = (double) TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes();
                double mobileBytes = TrafficStats.getMobileRxBytes()
                        + TrafficStats.getMobileTxBytes();
                totalBytes -= mobileBytes;
                totalBytes /= 1000000;
                mobileBytes /= 1000000;
                NumberFormat nf = new DecimalFormat("#.###");
                String tag = ";";
                String mobileStr = nf.format(mobileBytes);
                String totalStr = nf.format(totalBytes);
                String info = String.format("CO%s,WO%s", tag, mobileStr,
                        totalStr);
                // save Network and Wifi data in sharedPreferences

                SharedPreferences cnwn = getApplicationContext()
                        .getSharedPreferences(Constants.PREFS_NAME, 0);
                Editor editor = cnwn.edit();
                editor.putString("last_month", info);
                editor.commit();

                //

                // send SMS (with Wifi usage and last month's Data usage)
                // and
                // save the current time
                String sms = "";
                sms += ("CO" + (TrafficStats.getMobileRxBytes() + TrafficStats
                        .getMobileTxBytes()) / 1000000);
                sms += ("WO" + (TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes() - (TrafficStats
                        .getMobileRxBytes() + TrafficStats
                        .getMobileTxBytes())) / 1000000);

                SmsManager smsManager = SmsManager.getDefault();
                if (Config.DEVELOPMENT) {
                    String shortCode = settings.getString(
                            Constants.PREFS_KEY_SHORT_CODE,
                            Constants.DEFAULT_SHORT_CODE);
                    smsManager.sendTextMessage(shortCode, null,
                            sms + cnwn.getString("last_month", ""), null,
                            null);
                    editor.putLong("smstimestamp",
                            System.currentTimeMillis());
                    editor.commit();
                } else {
                    SmsManager ackSMS = SmsManager.getDefault();
                    smsManager.sendTextMessage(
                            Constants.DEFAULT_SHORT_CODE, null,
                            sms + cnwn.getString("last_month", ""), null,
                            null);
                }

            }
        }
    }, delay_interval, period);

}

@Override
public IBinder onBind(Intent intent) {

    // TODO Auto-generated method stub

    return null;

}

@Override
public boolean onUnbind(Intent intent) {

    // TODO Auto-generated method stub

    return super.onUnbind(intent);

}

}

【问题讨论】:

    标签: java android sharedpreferences swap


    【解决方案1】:

    如果你总是用

    输入数据
    editor.putString(new String("data"), Integer.toString(0)) 
    

    那么你只会得到零(因为你只是输入了Integer.toString(0)...)

    【讨论】:

    • 我正在尝试保存我认为是数据的 mdn 的值 - 所以除了颠倒这两个值的顺序之外 - 还有什么我应该做的吗?
    • 我试过 editor.putString(Integer.toString(0), Integer.toString(data));但我得到 Integer 类型的方法 toString(int) 不适用于参数和 editor.putString(Integer.toString(0), ("data"));我又归零了
    • 我只是想获取字节交换 MDN 的值(我相信应该可以通过字符串引用它:数据)
    • 你可以试试editor.putString(new String("data"), new String(data))。您可能需要阅读文档以了解所有这些方法的作用。
    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2013-10-24
    • 2020-09-04
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多