get String from Bundle with or without default value - Android android.os

Android examples for android.os:Bundle

Description

get String from Bundle with or without default value

Demo Code

import android.os.Bundle;
import android.text.TextUtils;

public class Main {

  public static String getString(Bundle bundle, String key) {
    return getString(bundle, key, "");
  }// w w w .  j a va2  s . com

  private static String getString(Bundle bundle, String key, String df) {
    if (df == null) {
      df = "";
    }
    return getValue(bundle, key, df);
  }
  
  @SuppressWarnings("unchecked")
  public static <T> T getValue(Bundle bundle, String key, T df) {
    if (bundle == null || TextUtils.isEmpty(key)) {
      return df;
    }

    if (df == null) {
      return df;
    }

    if (!bundle.containsKey(key)) {
      return df;
    }
    T value = df;
    Object obj = bundle.get(key);
    if (obj != null && value.getClass().isAssignableFrom(obj.getClass())) {
      value = (T) obj;
    }
    return value;
  }

}

Related Tutorials