Passing data between activity android. Transferring data between activities

Passing data between activity android. Transferring data between activities

18.10.2020

Hello.

It is necessary to transfer data received via UART to Activity. This can be done by creating a thread in Activity, in which to organize a while (! IsInterrupted ()) loop and read data from the UART buffer. After that, by calling the UI thread of the Activity - MainActivity.this.runOnUiThread (new Runnable (), perform the necessary actions with this Activity. But if we call other Activities from the main Activity, then the organized thread does not allow transferring data to the newly created Activity. If I I understand correctly that in order for the data from the stream to be transferred to any Activity, the stream must be created not in the Activity, but in the Service.

Question: data came via UART, in a stream (which is created in Servce) it is necessary to transfer data to the Activity, which is now active, how can this be done and is this actually done?

1 answer

Create a Handler in each Activity. In the onResume () method of this Activity does bindService (). There one of the parameters is interface ServiceConnection. Implement it at least with the same Activity. Implement the onServiceConnected () method in it. In this callback, the Service itself comes as one of the parameters. So call this Service your own setHandler () method. Pass the Handler that is in the current Activity there. But send the incoming data via UART to Service on this Handler. By the way, Handler traditionally runs on the main thread, so you won't need to runOnUiThread to execute.

The application does not always consist of a single screen. For example, we have created a very useful program and the user wants to know who the author is. He clicks on the button "About the program" and gets to a new screen, where there is useful information about the version of the program, author, site address, how many cats the author has, etc. Think of an activity screen as a web page with a link to another page. If you look at the code in the file MainActivity.java from the previous lessons, you will see that our class MainActivity also applies to Activity (or his heirs) or, more precisely, inherited from him.

Public class MainActivity extends AppCompatActivity

As you might guess, we should create a new class, which may look like MainActivity and then somehow switch to it when the button is pressed.

For the experiment, we will take the program from the first lesson and use a button for experiments (or create a new project with one button on the screen). Next, let's create a new form to display useful information. For example, let's show the user what the cat does when he walks left and right. Agree, this is very important information that gives a clue to the Universe.

We will create a new activity manually, although the studio has ready-made templates. But there is nothing complicated and for better understanding it is useful to do everything by hand.

Create a new XML markup file activity_about.xml in folder res / layout... Right click on the folder layout and select from the context menu New | Layout resource file... A dialog box will appear. In the first field, enter the file name activity_about... In the second, you need to enter the root element. By default there is ConstraintLayout... Erase the text and enter ScrollView... Entering a few characters is enough for the studio to suggest ready-made options, you can immediately press Enter, without waiting for the complete input of the word:

We will get the corresponding blank, into which we will insert the element TextView.

Information will be fetched from resources, namely from a string resource about_text... Now it is highlighted in red, signaling the lack of information. You could press Alt + Enter and enter text in the dialog box. But for our example, this method will not work, since our text will be multi-line, using control characters. So let's do it differently. Let's open the file res / values \u200b\u200b/ strings.xml and enter the following text manually:

A green oak by the seashore; \\ n A golden chain on a tom oak: \\ n Day and night scientist cat\\ n Everything follows the chain in a circle; \\ n Goes right - the song starts, \\ n Left - says a fairy tale.

We used the simplest HTML text formatting tags like , , ... For our example, it is enough to highlight in bold the words that refer to the cat and the direction of movement. To transfer text to a new line, use the symbols \\ n... Let's add one more string resource for the title of the new screen:

About the program

We figured out the markup. Next, you need to create a class for the window AboutActivity.java... Choose from the menu File | New | Java Class and fill in the required fields. At first, it is enough to indicate only the name. Then deal with other fields.

Let's get a blank.

The class is now almost empty. Let's add the code manually. The class must inherit from the abstract class Activity or his relatives like FragmentActivity, AppCompatActivity etc. We add extends Activity... Activity class must have a method onCreate ()... We put the mouse cursor inside the class and select from the menu Code | Override methods (Ctrl + O). In the dialog box, we are looking for the desired class, you can type the first characters on the keyboard for quick search... In the created method, you need to call the method setContentView ()which will load the prepared markup onto the screen. We will get this option.

Package ru.alexanderklimov.helloworld; import android.app.Activity; import android.os.Bundle; / ** * Created by Alexander Klimov on 01.12.2014. * / public class AboutActivity extends Activity (@Override protected void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.activity_about);))

Now the most important thing begins. Our task is to go to a new screen when the button is clicked on the first screen. Go back to class MainActivity... Let's write a button click handler:

Public void onClick (View view) (Intent intent \u003d new Intent (MainActivity.this, AboutActivity.class); startActivity (intent);)

Here I used the method for handling button clicks that I described in the lesson.

To start a new screen, you need to create an instance of the class Intent and specify the current class in the first parameter, and the class for the transition in the second, we have this AboutActivity... After that, the method is called startActivity ()which launches a new screen.

If you now try to test the application in the emulator, you will receive an error message. What did we do wrong? We missed one important step. You need to register a new one Activity in the manifest AndroidManifest.xml... Find this file in your project and double click on it. The file editing window will open. Add a new tag after the closing tag for the first activity. Print yourself and use the prompts actively. The result is the following:

So the string resource came in handy about_title... Run the application, click on the button and get the window About the program... Thus, we learned how to create a new window and call it on the click of a button. And we have at our disposal a mega-convenient program - now there will always be a hint at hand what the cat does when he goes to the left.

Once again, I draw your attention to the fact that the second created activity class must inherit from the class Activity or similar ( ListActivity and others), have an XML markup file (if required) and be written in the manifest.

After calling the method startActivity () a new activity will start (in this case AboutActivity), it will become visible and move to the top of the stack containing the running components. When calling the method finish () from a new activity (or when a hard return key is pressed) it will be closed and removed from the stack. The developer can also navigate to the previous (or any other) activity using the same method. startActivity ().

How to create a third screen - a way for the lazy

Programmers, like cats, are lazy creatures. Always remember that for activity you need to create markup and a class that inherits from Activity, and then do not forget to register the class in the manifest - well, nafig.

In this case, select from the menu File | New | Activity | Basic Activity (or another template). Next, the familiar window for creating a new activity will appear. We fill in the required fields.

Click on the button Finish and the activity will be ready. To verify this, open your manifest file and check for a new entry. I'm not talking about class and markup files, they themselves will appear in front of you.

Add a new button on the main activity screen yourself and write the code to go to the created activity.

At first, I would advise you to manually create all the necessary components for a new activity in order to understand the relationship between class, markup and manifest. And when you get your hands on it, you can use the activity creation wizard to speed up your work.

Transferring data between activities

We used the simplest example to call another activity screen. Sometimes it is necessary not only to call a new screen, but also to transfer data to it. For example, username. In this case, you need to use a special area extraDatathat the class has Intent.

Region extraData is a list of pairs key / valuethat is passed along with the intent. Strings are used as keys, and for values \u200b\u200byou can use any primitive data types, arrays of primitives, class objects Bundle and etc.

To transfer data to another activity, use the method putExtra ():

Intent.putExtra ("Key", "Value");

The receiving activity should call some suitable method: getIntExtra (), getStringExtra () etc.:

Int count \u003d getIntent (). GetIntExtra ("name", 0);

Let's redo the previous example. We already have three activities. The first activity will have two text fields and a button. The appearance can be as follows:

The second activity SecondActivity install the element TextView, in which we will display the text received from the first activity. Let's write the following code for the method onCreate () the second activity.

@Override protected void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.activity_second); String user \u003d "Live"; String gift \u003d "donut hole"; TextView infoTextView \u003d (TextView) findViewById R.id.textViewInfo); infoTextView.setText (user + ", you were given" + gift);)

If we run the program now and just call the second window, as described in the first part of the article, we will see the default label ZHYVotnoe, you were given a donut hole... Agree, it is rather annoying to receive such messages.

We fix the situation. Add the code for the first activity:

Public void onClick (View view) (EditText userEditText \u003d (EditText) findViewById (R.id.editTextUser); EditText giftEditText \u003d (EditText) findViewById (R.id.editTextGift); Intent intent \u003d new Intent (MainActivity) class); // push the text from the first text field into the username key intent.putExtra ("username", userEditText.getText (). toString ()); // push the text from the second text field into the gift key intent.putExtra ("gift ", giftEditText.getText (). toString ()); startActivity (intent);)

We placed an object in a special container Intent two keys with values \u200b\u200btaken from text fields. When the user enters data into the text fields, they will go to this container and will be transferred to the second activity.

The second activity should be ready to receive messages warm as follows (in bold).

// Default values \u200b\u200bString user \u003d "Live"; String gift \u003d "donut hole"; user \u003d getIntent (). getExtras (). getString ("username"); gift \u003d getIntent (). getExtras (). getString ("gift"); TextView infoTextView \u003d (TextView) findViewById (R.id.textViewInfo); infoTextView.setText (user + ", you were given" + gift);

Now the message looks not so offensive, but even pleasant for some. In complex examples, it is desirable to add validation when processing data. There are situations when you start the second activity with empty data like nullwhich can crash the application.

In our case, we know that we are waiting for a string value, so the code can be rewritten like this:

Intent intent \u003d getIntent (); user \u003d intent.getStringExtra ("username");

User \u003d getIntent (). GetStringExtra ("username");

The program has a drawback - it is not clear from whom we receive greetings. Any well-mannered monkey will not accept a gift from an anonymous source. So as a homework assignment, add another text field to enter the name of the user who is sending the message.

Google recommends using the following format for keys: your package name as a prefix, followed by the key itself. In this case, you can be sure that the key is unique when interacting with other applications. Something like this:

Public final static String USER \u003d "ru.alexanderklimov.myapp.USER";

Who framed the cat Vaska - we get the result back

It is not always sufficient to simply pass data to another activity. Sometimes you want to get information back from another activity when it is closed. If earlier we used the method startActivity (Intent intent), then there is a related method startActivityForResult (Intent intent, int RequestCode)... The difference between the methods is the extra parameter RequestCode... It's basically just an integer that you can make up yourself. It is needed in order to distinguish from whom the result came. Let's say you have five additional screens and you assign them values \u200b\u200bfrom 1 to 5, and from this code you can determine whose result you need to process. You can use the value -1, then it will be the same as calling the method startActivity (), i.e. we get no result.

If you use the method startActivityForResult (), then you need to override the method in the code to receive the result onActivityResult () and process the result. Confused? Let's take an example.

Let's say you're a detective. There was information that two pieces of sausage and other products were stolen from the table of an influential person in a restaurant. Suspicion fell on three suspects - a crow, a fucking doggie and a cat Vaska.

One of the visitors provided a series of photos from his pontoon iPhone:


There is also testimony from another witness: And Vaska listens, but eats.

Create a new project Sherlock with two activities. The first screen will have a button to switch to the second screen and a text label that will display the name of the thief.

© 2021 hecc.ru - News of computer technologies