Android bundle to string

Android Bundle Tutorial

A Bundle is a data structure that provides mapping from String values to Parceable types.

Bundle class definition

Bundle belongs to android.os package.

Bundle is a final class so you cannot derive from it:

It derives from a android.os.BaseBundle class:

Bundle implements two interfaces:

Interface Description
Cloneable So that it supports cloning.
Parcelable So that it supports writing to and restoration from a parcel.

Creating a Bundle

A Bundle is like all Java classes is an Object. Objects do have constructors.

A constructor is a method that gets called when the object is created. When an object is instantiated. Basically the constructors create or construct objects.

Well the Bundle class has 5 of these constructors that we can use to create a Bundle object. They only differ in the parameters we pass to the object.

Constructor Description
Bundle() This will create a new empty Bundle object
Bundle(int capacity) Create a new Bundle object with the total capacity specified in the parameter.
Bundle(Bundle b) Creates a bundle object with a copy of entries from the passed Bundle.
Bundle(PersitableBundle b) This will create a Bundle with a copy of entires from the passed PersistableBundle.

A BaseBundle is a class that provides mapping from String values to various data types in android.

This ability to map simple strings to many more data types, some of them complex, is dear to us especially when we want to transfer data among components like activities.

BaseBundle is a rather new class since it was added in android API level 1.

This class provides the basis for other Bundle classes. These classes derive from it:

Class Description
Bundle Maps Strings to Parcelable types.
PersistableBundle Maps Strings to various types that can be saved and later restored for use.

The BaseBundle class is a concrete class and contains several methods for manipulating the data in the Bundle. In fact the other classes do derive some of these methods.

Let’s have a look at some of these (public) methods we can use to manipulate a BaseBundle:

Adding Simple Types to BaseBundle

There are put. methods for easily inserting data of various types into a basebundle:

Method Description
void putString(String key,String value) This will insert a string value into the String replacing any existing value for the passed key.
void putInt(String key, int value) This will insert an int value into the Bunlde mapping replacing any existing value for the passed key..
void putLong(String key, long value) This will insert a long value into the Bunlde mapping replacing any existing value for the passed key..
void putDouble(String key, double value) This will insert a double value into the Bunlde mapping replacing any existing value for the passed key..
void putBoolean(String key, boolean value) This will insert a double value into the Bunlde mapping replacing any existing value for the passed key..

Adding Arrays into a BaseBundle

There are built-in methods for adding arrays of simple types into a BaseBundle as well:

Method Description
void putStringArray(String key,String[] value) This will insert an array of strings into the Bundle replacing any existing value for the passed key.
void putIntArray(String key,int[] value) This will insert an array of integers into the Bundle replacing any existing value for the passed key.
void putDoubleArray(String key,double[] value) This will insert an array of doubles into the Bundle replacing any existing value for the passed key.
void putBooleanArray(String key,boolean[] value) This will insert an array of booleans into the Bundle replacing any existing value for the passed key.
void putLongArray(String key,long[] value) This will insert an array of longs into the Bundle replacing any existing value for the passed key.

Checking For Existing Items in a BaseBundle

First you may want to check for emptiness in a Bundle:

Method Description
bolean isEmpty() Will check if the Bundle mapping is empty, if so it returns true. If its is not empty it returns false.

Then you may want to check if the Bundle has a given key:

Method Description
boolean containsKey(String key) Will check if the Bundle mapping has the passed key, if so it returns true. If it doesn’t have the key it returns false.

Getting the Size of a Bundle

We can know the number of mappings contained in a Bundle as well.

Method Description
int size() This will return the number of mappings contained in this Bundle.

Retrieving Simple Types from a BaseBundle

If you inserted items into a Bundle, then probably you’ll want to retrieve those items.

This is easy as the framework provides us with methods to retrieve bundle items. All we need is pass in the key of the bundle.

Method Description
String getString(String key) This will return a string value mappped from passed the key.Or null if no mapping with this key exists.
int getInt(String key,int defaultValue) This will return an int value mappped from the passed key.Or defaultvalue if no mapping with this key exists.
int getInt(String key) This will return an int value mappped from the passed key.Or 0 if no mapping with this key exists.
long getLong(String key,long defaultValue) This will return a long value mappped from the passed key.Or defaultValue if no mapping with this key exists.
long getLong(String key) This will return a long value mappped from the passed key.Or 0L if no mapping with this key exists.
double getDouble(String key,double defaultValue) This will return a double value mappped from the passed key.Or defaultValue if no mapping with this key exists.
double getDouble(String key) This will return a double value mappped from the passed key.Or 0.0 if no mapping with this key exists.
boolean getBoolean(String key,boolean defaultValue) This will return a boolean value mappped from the passed key.Or defaultValue if no mapping with this key exists.
boolean getBoolean(String key) This will return a boolean value mappped from the passed key.Or false if no mapping with this key exists.

Retrieving Arrays and Objects From a BaseBundle

We saw how to pass relatively complex types like arrays and objects.

Well they are equally easy to retrieve from a bundle:

Method Description
Object get(String key) This will return an object entry mappped from passed the key.

Then the arrays as well:

Method Description
String[] getStringArray(String key) This will return an array of strings mappped from passed the key.Or null if no mapping with this key exists.
int[] getIntArray(String key) This will return an array of ints mappped from passed the key.Or null if no mapping with this key exists.
long[] getLongArray(String key) This will return an array of longs mappped from passed the key.Or null if no mapping with this key exists.

Retrieving Keys from a BaseBundle

The mappings in our Bundle will have unique keys.

We can then retrieve those keys and hold them in a Set data structure:

Method Description
Set keySet() This will return a Set of strings used as keys.

Removing a given item from a BaseBundle

We’ve seen how to add and read items from a Bundle.

Well we can also remove items

Method Description
void remove(String key) This will remove an entry with the specified key.

Clearing a BaseBundle

A BaseBundle instance can be cleared as well. This removes all entries from the Bundle instance.

Method Description
void clear() This will remove all entries from the bundle.

Android PersistableBundle

A PersistableBundle is a type of Bundle that maps Strings to types types that can be saved and later restored.

PersistableBundle definition

PersistableBundle, like Bundle resides in the android.os package:

It was added back in android API level 21.

Persistable class is a final class:

so you cannot derive from it.

Like the Bundle class it derives from BaseBundle:

So it inherits a whole bunch of methods for inserting, retrieving, removing entries into the PersistableBundle.

PersistableBundle implements two interfaces:

Interface Description
Cloneable So that it supports cloning.
Parcelable So that it supports writing to and restoration from a parcel.

report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Android Bundle

Android Tutorial

In this tutorial, we’ll be discuss about android bundle to pass data between activities.

Android Bundle

Android Bundle is used to pass data between activities. The values that are to be passed are mapped to String keys which are later used in the next activity to retrieve the values.

Following are the major types that are passed/retrieved to/from a Bundle.

  • putInt(String key, int value) , getInt(String key, int value)
  • putIntArray(String key, int[] value) , getStringArray(String key, int[] value)
  • putIntegerArrayList(String key, ArrayList value) , getIntegerArrayList(String key, ArrayList value value)
  • putString(String key, String value) , getString(String key, String value)
  • putStringArray(String key, String[] value) , getStringArray(String key, String[] value)
  • putStringArrayList(String key, ArrayList value) , getStringArrayList(String key, ArrayList value value)
  • putLong(String key, long value) , getLong(String key, long value)
  • putLongArray(String key, long[] value) , getLongArray(String key, long[] value)
  • putBoolean(String key, boolean value) , getBoolean(String key, boolean value)
  • putBooleanArray(String key, boolean[] value) , getBooleanArray(String key, boolean[] value)
  • putChar(String key, char value) , getChar(String key, char value)
  • putCharArray(String key, char[] value) , getBooleanArray(String key, char[] value)
  • putCharSequence(String key, CharSequence value) , getCharSequence(String key, CharSequence value)
  • putCharSequenceArray(String key, CharSequence[] value) , getCharSequenceArray(String key, CharSequence[] value)
  • putCharSequenceArrayList(String key, ArrayList value) , getCharSequenceArrayList(String key, ArrayList value value)

Using Android Bundle

A Bundle is passed in the following way.

Data from a Bundle is retrieved in the SecondActivity.java in the following manner.

If the key doesn’t map to any value, it may lead to NullPointerException. Hence it’s recommended to add null checks for the Bundle as well as the retrieved values.

Alternatively, we can set a default value too in case the mapped key doesn’t have any value.

To remove a value from the bundle the remove() method is passed with the relevant key as shown below.

To remove all data from the Bundle, the method clear() is called on the Bundle instance.

Android Bundle Example Project Structure

Android Bundle Example Code

The code for the activity_main.xml layout is given below.

The first button would pass a bundle with data into the SecondActivity.java while the second button would pass an empty bundle

The code for the activity_second.xml layout is given below.

The code for the MainActivity.java is given below.

The code for the SecondActivity.java is given below.

The output of the above application in action is given below.

Try passing in an ArrayList of any data type in the bundle and display them in a ListView in the next Activity!

This brings an end to android bundle tutorial. You can download the final Android Bundle Project from the link below.

Источник

Русские Блоги

Класс Android Bundle

Сегодня я обнаружил, что я даже не понимаю класс Bundle, поэтому я нашел время, чтобы изучить его.

Класс Bundle — это пара ключ-значение » A mapping from String values to various Parcelable types.”

java.lang.Object android.os.Bundle
Класс Bundle является финальным классом: публичный финальный класс Bundle расширяет Objectimplements Parcelable Cloneable

Связь между этими двумя действиями может быть достигнута через класс связки, подход:

(1) Создать новый класс комплектов

(2) Добавить данные в класс пакета (в форме ключ-значение, при извлечении данных в другом действии вы должны использовать ключ, чтобы найти соответствующее значение)

  1. mBundle.putString( «Data», «data from TestBundle»);

(3) Создайте новый объект намерения и добавьте пакет к объекту намерения

  1. Intent intent = new Intent();
  2. intent.setClass(TestBundle. this, Target. class);
  3. intent.putExtras(mBundle);

Полный код выглядит следующим образом:

Android mainfest.xml выглядит следующим образом:

  1. «1.0» encoding= «utf-8»?>
  2. «http://schemas.android.com/apk/res/android»
  3. package= «com.tencent.test»
  4. android:versionCode= «1»
  5. android:versionName= «1.0»>
  6. «@drawable/icon» android:label= «@string/app_name»>
  7. «.TestBundle»
  8. android:label= «@string/app_name»>
  9. «android.intent.action.MAIN»/>
  10. «android.intent.category.LAUNCHER»/>
  11. «.Target»>
  12. «7»/>

Два класса следующие: намерение инициируется из класса TestBundle в класс Target.

Класс 1: класс TestBundle:

  1. import android.app.Activity;
  2. import android.content.Intent;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.View.OnClickListener;
  6. import android.widget.Button;
  7. public class TestBundle extends Activity <
  8. private Button button1;
  9. private OnClickListener cl;
  10. public void onCreate(Bundle savedInstanceState) <
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.main);
  13. button1 = (Button) findViewById(R.id.button1);
  14. cl = new OnClickListener() <
  15. @Override
  16. public void onClick(View arg0) <
  17. // TODO Auto-generated method stub
  18. Intent intent = new Intent();
  19. intent.setClass(TestBundle. this, Target. class);
  20. Bundle mBundle = new Bundle();
  21. mBundle.putString( «Data», «data from TestBundle»); // Нажмите в данных
  22. intent.putExtras(mBundle);
  23. startActivity(intent);
  24. >
  25. >;
  26. button1.setOnClickListener(cl);
  27. >
  28. >
  1. import android.app.Activity;
  2. import android.os.Bundle;
  3. public class Target extends Activity <
  4. public void onCreate(Bundle savedInstanceState) <
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.target);
  7. «color: rgb(255, 102, 0);»>Bundle bundle = getIntent().getExtras(); // Получить передаваемый пакет
  8. String data = bundle.getString( «Data»); // Чтение данных
  9. setTitle(data);
  10. >
  11. >
  1. «1.0» encoding= «utf-8»?>
  2. «http://schemas.android.com/apk/res/android»
  3. android:orientation= «vertical»
  4. android:layout_width= «fill_parent»
  5. android:layout_height= «fill_parent»
  6. >

«fill_parent»

  • android:layout_height= «wrap_content»
  • android:text= «@string/hello»
  • />
  • «fill_parent»
  • android:layout_height= «wrap_content»
  • android:text= «@string/button»
  • android:id = «@+id/button1»
  • />
    1. «1.0» encoding= «utf-8»?>
    2. «http://schemas.android.com/apk/res/android»
    3. android:orientation= «vertical»
    4. android:layout_width= «fill_parent»
    5. android:layout_height= «fill_parent»
    6. >

    «fill_parent»

  • android:layout_height= «wrap_content»
  • android:text= «@string/target»
  • />
    1. «1.0» encoding= «utf-8»?>
    2. «hello»>Hello World, TestBundle!
    3. «app_name»> Использование комплекта тестов
    4. «кнопка»> нажмите, чтобы перейти
    5. «цель»> перейти к целевой деятельности

    Заявление об авторском праве: эта статья является оригинальной статьей блоггеров и не может быть воспроизведена без разрешения блоггера.

    Перепечатано по адресу: https://www.cnblogs.com/lzjsky/p/4952021.html.

    Интеллектуальная рекомендация

    Многослойная презентацияViewController Jap

    . Недавно, проект использует многоэтажные прыжки [A presentViewController: B animated: YES] [B presentViewController: C animated: YES] . Проблема в том, где: как это идет прямо к? Я не нашел ме.

    Распечатать список с конца до головы

    В случае, когда таблица цепи не может изменять дисплей, данные хранения стека могут рассматриваться с рекурсивным методом. Разрешить модификацию структуры ссылки.

    Типы данных и переменные

    тип данных Компьютерная программа может обрабатывать различные значения. Однако компьютеры могут обрабатывать гораздо больше, чем числовые значения. Они также могут обрабатывать различные данные, таки.

    Python Daily Practice (4) -идиомы заполняют музыку

    оглавление 1. Одно место 2. Случайное расположение 3. Добавьте баллы для оценки 4. Получение файла 5. Установите уровень сложности. 6. Срок завершения 7. Выберите заполнение пропусков. 1. Одно место Н.

    Источник

    Читайте также:  Android webview отключен для пользователя
    Оцените статью