java - android无法解析日期异常?

标签 java android date

我正在制作一个使用日期功能的应用程序,但是查看几个现有的帖子,我仍然无法让我的 SimpleDateFormat 解析器工作。

这是代码:

public class GPSDemo extends Activity {

public static String TAG = "Abhi's Log";

public static String IMEII = "imei";
public static String START_TIME = "startTime";
public static String WORKING_STATUS = "workingStatus";
public static String ADDRESS = "address";
public static int level = 0;

Button stop, hide;

SharedPreferences pref;
Editor edit;

Date d1 = null;
Date d2 = null;

String startingTime;
String currentTime;

Context ctx = this;

TextView txt_start_time, txt_total_time, txt_total_distance, txt_address;

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demoooo);

    pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    edit = pref.edit();

    ConnectivityManager connectivityManager =  (ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
    this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    txt_start_time = (TextView) findViewById(R.id.txt_start_time);
    txt_total_time = (TextView) findViewById(R.id.txt_total_time);
    txt_total_distance = (TextView) findViewById(R.id.txt_total_distance);
    txt_address = (TextView) findViewById(R.id.txt_address);

    try {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);


        Editor edit = PreferenceManager
                .getDefaultSharedPreferences(
                        getApplicationContext()).edit();
        edit.putString(IMEII, mTelephonyMgr.getDeviceId());
        edit.commit();
        Log.i(TAG, "IMEI Stored Sucessfully : "
                + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString(IMEII, ""));
    } catch (Exception e) {

        Log.d(TAG, "Exception While Storin Data : " + e);
    }

   //       turnGPSOn(this);
   //   turnGPSOn();


    if(!isInternetOn()) {
        try {
        Method method = connectivityManager.getClass().getMethod("setMobileDataEnabled", boolean.class);
        method.invoke(connectivityManager, true);
        } catch (NoSuchMethodException e) {
        e.printStackTrace();
        } catch (Exception e) {
        e.printStackTrace();
        }
    }


    stop = (Button) findViewById(R.id.btn_stop);
    hide = (Button) findViewById(R.id.btn_hide);

    try {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        if(pref.getString(WORKING_STATUS, "").equals("NO")) {
            Intent intent = new Intent(GPSDemo.this, NetworkTrackerService.class);

            startService(intent);
            edit.putString(WORKING_STATUS, "YES");
            edit.putString(START_TIME, sdf.format(new Date()));
            edit.commit();
            txt_start_time.setText(sdf.format(new Date()));
        } else if(pref.getString(WORKING_STATUS, "").equals("YES")) {
            txt_start_time.setText(pref.getString(START_TIME, ""));
        }
        updateInof();
        startInfoUpdater();
        Log.i("Abhi's Log", "Values Stored :: " +pref.getString(WORKING_STATUS, "") +" " + pref.getString(START_TIME, "") );
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    stop.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(GPSDemo.this, NetworkTrackerService.class);
            edit.putString(WORKING_STATUS, "NO");
            edit.putString(START_TIME, "");
            edit.putString(ADDRESS, "");
            edit.commit();
            stopService(intent);

            System.exit(0);
        }
    });

    hide.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            GPSDemo.this.finish();
        }
    });



}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public  void turnGPSOn(Context context)
{
    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
    intent.putExtra("enabled", true);
    context.sendBroadcast(intent);

    String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (! provider.contains("gps"))
    { //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.tracking.gps", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        context.sendBroadcast(poke);
    }
}

public void turnGPSOn()
{
     Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
     intent.putExtra("enabled", true);
     this.ctx.sendBroadcast(intent);

    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(!provider.contains("gps"))
        { 
        //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        this.ctx.sendBroadcast(poke);
    }
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public static void turnGPSOff(Context context)
{
    String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (provider.contains("gps"))
    { //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        context.sendBroadcast(poke);
    }
}
private void startInfoUpdater() {
    // TODO Auto-generated method stub
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do something after 100ms

          Log.v("Abhi's Tag", "Inside Schedulat ... !!!");

         updateInof();


          startInfoUpdater();
      }
    }, 60000);
}
protected void updateInof() {
    // TODO Auto-generated method stub
     long diffSeconds, diffMinutes = 0, diffHours = 0, diffDays = 0;

      SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
      currentTime = sdf1.format(new Date());

      try {
          d1 = sdf1.parse(pref.getString(START_TIME, ""));
          d2 = sdf1.parse(currentTime);

          long diff = d2.getTime() - d1.getTime();

            diffSeconds = diff / (1000);
            diffMinutes = diff / (60 * 1000);
            diffHours = diff / (60 * 60 * 1000);
            diffDays = diff / (24 * 60 * 60 * 1000);

            Log.i("Abhi's Tag", "Days : " + diffDays);
            Log.i("Abhi's Tag", "Hours : " + diffHours);
            Log.i("Abhi's Tag", "Minutes : " + diffMinutes);
            Log.i("Abhi's Tag", "Seconds : " + diffSeconds);

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


      txt_start_time.setText(pref.getString(START_TIME, ""));
      txt_total_time.setText(diffDays+" D, " + diffHours + " H, " + diffMinutes + " M");
      txt_address.setText(pref.getString(ADDRESS, ""));
}
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

         level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);

        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        Editor edit = pref.edit();
        edit.putInt("batteryStatus", level);
        edit.commit();


    }
};

public final boolean isInternetOn() {

    ConnectivityManager connec =  (ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

        if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
             connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
             connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
             connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {

            return true;

        } else if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||  
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {

            return false;
        }
      return false;
    }
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

}


}

我收到此错误

java.text.ParseException: Unparseable date:""

最佳答案

你有这个

 sdf1.parse(pref.getString(START_TIME, ""));

如果返回默认值,则为空字符串。所以很自然地你会得到java.text.ParseException: Unparseable date:""。您正在解析空字符串

public abstract String getString (String key, String defValue)

Added in API level 1
Retrieve a String value from the preferences.

Returns the preference value if it exists, or defValue

关于java - android无法解析日期异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23055332/

相关文章:

java - Linux 错误代码 24 是什么意思?

java - 无法通过蓝牙写入十六进制字节

android - 从 'byte*' 到 'byte' 的无效转换

android - isChecked() 行为在 2.3.6 和 4.2 android 版本中完全相反

java - 获取java sql时间并将其插入到表中

java - Spark : launch from single JVM jobs with different memory/cores configs simultaneously

java - Kafka java消费者SSL握手错误: java. security.cert.CertificateException:不存在主题替代名称

javascript - 重命名 React Native 示例应用程序

固定日期范围之间的 MySQL 记录

ios - 日期到毫秒并在 Swift 中返回日期