- Android Bundle Tutorial
- Bundle class definition
- Creating a Bundle
- Adding Simple Types to BaseBundle
- Adding Arrays into a BaseBundle
- Checking For Existing Items in a BaseBundle
- Getting the Size of a Bundle
- Retrieving Simple Types from a BaseBundle
- Retrieving Arrays and Objects From a BaseBundle
- Retrieving Keys from a BaseBundle
- Removing a given item from a BaseBundle
- Clearing a BaseBundle
- Android PersistableBundle
- PersistableBundle definition
- Oclemy
- Android Bundle
- Android Tutorial
- Android Bundle
- Using Android Bundle
- Android Bundle Example Project Structure
- Android Bundle Example Code
- Русские Блоги
- Класс Android Bundle
- Интеллектуальная рекомендация
- Многослойная презентацияViewController Jap
- Распечатать список с конца до головы
- Типы данных и переменные
- Python Daily Practice (4) -идиомы заполняют музыку
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) Добавить данные в класс пакета (в форме ключ-значение, при извлечении данных в другом действии вы должны использовать ключ, чтобы найти соответствующее значение)
- mBundle.putString( «Data», «data from TestBundle»);
(3) Создайте новый объект намерения и добавьте пакет к объекту намерения
- Intent intent = new Intent();
- intent.setClass(TestBundle. this, Target. class);
- intent.putExtras(mBundle);
Полный код выглядит следующим образом:
Android mainfest.xml выглядит следующим образом:
- «1.0» encoding= «utf-8»?>
- «http://schemas.android.com/apk/res/android»
- package= «com.tencent.test»
- android:versionCode= «1»
- android:versionName= «1.0»>
- «@drawable/icon» android:label= «@string/app_name»>
- «.TestBundle»
- android:label= «@string/app_name»>
- «android.intent.action.MAIN»/>
- «android.intent.category.LAUNCHER»/>
- «.Target»>
- «7»/>
Два класса следующие: намерение инициируется из класса TestBundle в класс Target.
Класс 1: класс TestBundle:
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class TestBundle extends Activity <
- private Button button1;
- private OnClickListener cl;
- public void onCreate(Bundle savedInstanceState) <
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- button1 = (Button) findViewById(R.id.button1);
- cl = new OnClickListener() <
- @Override
- public void onClick(View arg0) <
- // TODO Auto-generated method stub
- Intent intent = new Intent();
- intent.setClass(TestBundle. this, Target. class);
- Bundle mBundle = new Bundle();
- mBundle.putString( «Data», «data from TestBundle»); // Нажмите в данных
- intent.putExtras(mBundle);
- startActivity(intent);
- >
- >;
- button1.setOnClickListener(cl);
- >
- >
- import android.app.Activity;
- import android.os.Bundle;
- public class Target extends Activity <
- public void onCreate(Bundle savedInstanceState) <
- super.onCreate(savedInstanceState);
- setContentView(R.layout.target);
- «color: rgb(255, 102, 0);»>Bundle bundle = getIntent().getExtras(); // Получить передаваемый пакет
- String data = bundle.getString( «Data»); // Чтение данных
- setTitle(data);
- >
- >
- «1.0» encoding= «utf-8»?>
- «http://schemas.android.com/apk/res/android»
- android:orientation= «vertical»
- android:layout_width= «fill_parent»
- android:layout_height= «fill_parent»
- >
«fill_parent»
- «1.0» encoding= «utf-8»?>
- «http://schemas.android.com/apk/res/android»
- android:orientation= «vertical»
- android:layout_width= «fill_parent»
- android:layout_height= «fill_parent»
- >
«fill_parent»
- «1.0» encoding= «utf-8»?>
- «hello»>Hello World, TestBundle!
- «app_name»> Использование комплекта тестов
- «кнопка»> нажмите, чтобы перейти
- «цель»> перейти к целевой деятельности
Заявление об авторском праве: эта статья является оригинальной статьей блоггеров и не может быть воспроизведена без разрешения блоггера.
Перепечатано по адресу: 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. Одно место Н.
Источник