- Bundle in Android with Example
- Using the Bundle in the Android App
- What is the use of import Android OS bundle?
- What is bundle used for?
- What is the difference between intent and bundle in Android?
- How pass data from one activity to another activity in Android using bundle?
- What is savedInstanceState in Android?
- What is bundle Android example?
- What bundle means?
- What are the two types of intent in android?
- What does bundle View mean?
- How pass data to another activity in Android?
- How can use variable in another activity in Android?
- What way is used to pass data between activities in android?
- What is the use of setContentView in Android?
- When onPause method is called in Android?
- What is onCreate method in Android?
- Android Bundle
- Android Tutorial
- Android Bundle
- Using Android Bundle
- Android Bundle Example Project Structure
- Android Bundle Example Code
- Настройки и состояние приложения
- Сохранение состояния приложения
Bundle in Android with Example
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically here concept of key-value pair is used where the data that one wants to pass is the value of the map, which can be later retrieved by using the key. Bundles are used with intent and values are sent and retrieved in the same fashion, as it is done in the case of Intent. It depends on the user what type of values the user wants to pass, but bundles can hold all types of values (int, String, boolean, char) and pass them to the new activity.
The following are the major types that are passed/retrieved to/from a Bundle:
putInt(String key, int value), getInt(String key, int value)
putString(String key, String value), getString(String key, String value)
putStringArray(String key, String[] value), getStringArray(String key, String[] value)
putChar(String key, char value), getChar(String key, char value)
putBoolean(String key, boolean value), getBoolean(String key, boolean value)
Using the Bundle in the Android App
The bundle is always used with Intent in Android. Now to use Bundle writes the below code in the MainActivity.
Источник
What is the use of import Android OS 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.
What is bundle used for?
Android Bundles are generally used for passing data from one activity to another. Basically here concept of key-value pair is used where the data that one wants to pass is the value of the map, which can be later retrieved by using the key.
What is the difference between intent and bundle in Android?
Bundle can operate on objects, but Intent can’t. Bundle has more interfaces than Intent and is more flexible to use, but using Bundle also needs Intent to complete data transfer. In a word, Bundle aims to store data, while Intent aims to transfer value.
How pass data from one activity to another activity in Android using bundle?
//Create the bundle Bundle bundle = new Bundle(); //Add your data from getFactualResults method to bundle bundle. putString(“VENUE_NAME”, venueName); //Add the bundle to the intent i. putExtras(bundle); startActivity(i); In you code (second Activity) however, you are referring to the key in the Bundle as MainActivity.
What is savedInstanceState in Android?
The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.
What is bundle Android example?
Bundle is used to pass data between Activities. You can create a bundle, pass it to Intent that starts the activity which then can be used from the destination activity. Bundle:- A mapping from String values to various Parcelable types. Bundle is generally used for passing data between various activities of android.
What bundle means?
an item, group, or quantity wrapped for carrying; package. a number of things considered together: a bundle of ideas. Slang. a great deal of money: He made a bundle in the market.
What are the two types of intent in android?
There are two intents available in android as Implicit Intents and Explicit Intents.
What does bundle View mean?
a Bundle is a collection of data. When an Activity starts (via onCreate), the Android OS (or you!) can pass off some extra data to this activity via this bundle. … This data from the intent will be included in this onCreate bundle, and you can access it through there.
How pass data to another activity in Android?
The easiest way to do this would be to pass the session id to the signout activity in the Intent you’re using to start the activity: Intent intent = new Intent(getBaseContext(), SignoutActivity. class); intent. putExtra(“EXTRA_SESSION_ID”, sessionId); startActivity(intent);
How can use variable in another activity in Android?
3 Answers. You can declare them as static variables and then in your other class you may access them like Activity1. stringName. Then, in all the other Activities, you can access them as YourMainActivty.
What way is used to pass data between activities in android?
We can send the data using putExtra() method from one activity and get the data from the second activity using getStringExtra() methods. Example: In this Example, one EditText is used to input the text. This text is sent to the second activity when the “Send” button is clicked.
What is the use of setContentView in Android?
SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R. layout. somae_file). Here layoutfile is inflated to view and added to the Activity context(Window).
When onPause method is called in Android?
onPause. Called when the Activity is still partially visible, but the user is probably navigating away from your Activity entirely (in which case onStop will be called next). For example, when the user taps the Home button, the system calls onPause and onStop in quick succession on your Activity .
What is onCreate method in Android?
onCreate is used to start an activity. super is used to call the parent class constructor. setContentView is used to set the xml.
Источник
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.
Источник
Настройки и состояние приложения
Сохранение состояния приложения
В одной из предыдущих тем был рассмотрен жизненный цикл Activity в приложении на Android, где после создания Activity вызывался метод onRestoreInstanceState , который восстанавливал ее состояние, а перед завершением работы вызывался метод onSaveInstanceState , который сохранял состояние Actiity. Оба этих метода в качестве параметра принимают объект Bundle , который как раз и хранит состояние activity:
В какой ситуации могут быть уместно использование подобных методов? Банальная ситуация — переворот экрана и переход от портретной ориентации к альбомной и наоборот. Если, к примеру, графический интерфейс содержит текстовое поле для вывода TextView, и мы программно изменяем его текст, то после изменения ориентации экрана его текст может исчезнуть. Или если у нас глобальные переменные, то при изменении ориентации экрана их значения могут быть сброшены до значений по умолчанию.
Чтобы точнее понять проблему, с которой мы можем столкнуться, рассмотрим пример. Изменим файл activity_main следующим образом:
Здесь определено поле EditText, в которое вводим имя. И также определена кнопка для его сохранения.
Далее для вывода сохраненного имени предназначено поле TextView, а для получения сохраненного имени — вторая кнопка.
Теперь изменим класс MainActivity :
Для хранения имени в программе определена переменная name. При нажатии на первую кнопку сохраняем текст из EditText в переменную name, а при нажатии на вторую кнопку — обратно получаем текст из переменной name в поле TextView.
Запустим приложение введем какое-нибудь имя, сохраним и получим его в TextView:
Но если мы перейдем к альбомному режиму, то TextView окажется пустым, несмотря на то, что в него вроде бы уже получили нужное значение:
И даже если мы попробуем заново получить значение из переменной name, то мы увидим, что она обнулилась:
Чтобы избежать подобных ситуаций как раз и следует сохранять и восстанавливать состояние activity. Для этого изменим код MainActivity:
В методе onSaveInstanceState() сохраняем состояние. Для этого вызываем у параметра Bundle метод putString(key, value) , первый параметр которого — ключ, а второй — значение сохраняемых данных. В данном случае мы сохраняем строку, поэтому вызываем метод putString() . Для сохранения объектов других типов данных мы можем вызвать соответствующий метод:
put() : универсальный метод, который добавляет значение типа Object. Соответственно поле получения данное значение необходимо преобразовать к нужному типу
putString() : добавляет объект типа String
putInt() : добавляет значение типа int
putByte() : добавляет значение типа byte
putChar() : добавляет значение типа char
putShort() : добавляет значение типа short
putLong() : добавляет значение типа long
putFloat() : добавляет значение типа float
putDouble() : добавляет значение типа double
putBoolean() : добавляет значение типа boolean
putCharArray() : добавляет массив объектов char
putIntArray() : добавляет массив объектов int
putFloatArray() : добавляет массив объектов float
putSerializable() : добавляет объект интерфейса Serializable
putParcelable() : добавляет объект Parcelable
Каждый такой метод также в качестве первого параметра принимает ключа, а в качестве второго — значение.
В методе onRestoreInstanceState происходит обратный процесс — с помощью метода getString(key) по ключу получаем из сохраненного состояния строку по ключу. Соответственно для получения данных других типов мы можем использовать аналогичные методы:
get() : универсальный метод, который возвращает значение типа Object. Соответственно поле получения данное значение необходимо преобразовать к нужному типу
getString() : возвращает объект типа String
getInt() : возвращает значение типа int
getByte() : возвращает значение типа byte
getChar() : возвращает значение типа char
getShort() : возвращает значение типа short
getLong() : возвращает значение типа long
getFloat() : возвращает значение типа float
getDouble() : возвращает значение типа double
getBoolean() : возвращает значение типа boolean
getCharArray() : возвращает массив объектов char
getIntArray() : возвращает массив объектов int
getFloatArray() : возвращает массив объектов float
getSerializable() : возвращает объект интерфейса Serializable
getParcelable() : возвращает объект Parcelable
Для примера рассмотрим сохранение-получение более сложных данных. Например, объектов определенного класса. Пусть у нас есть класс User :
Класс User реализует интерфейс Serializable , поэтому мы можем сохранить его объекты с помощью метода putSerializable() , а получить с помощью метода getSerializable() .
Пусть у нас будет следующий интерфейс в activity_main.xml :
Здесь определены два поля ввода для имени и возраста соответственно.
В классе MainActivity пропишем логику сохранения и получения данных:
Здесь также сохраняем данные в переменную User, которая предварительно инициализированна некоторыми данными по умолчанию. А при нажатии на кнопку получения получем данные из переменной и передаем их для вывода в текстовое поле.
Источник