Value Transfer in Android

Source: Internet
Author: User

Value Transfer in Android

 

As we all know, according to the mvc design pattern, data is transmitted through the model, from one activity (A) to another activity (B) if you want to pass the value, we can put the model in the intent (or not), and then get the corresponding value after B is created; otherwise, if the value is returned to A from B, it is also feasible, except to receive the corresponding value in onActivityResult of. These methods have their own advantages and disadvantages. You can choose one based on your actual situation.
The central idea of this article has been explained. Let's start to look at the specific code demonstration.
1. Pass values through model

Directly pass values through model

This method is very simple. You can create a data source Singleton DataSource and put all the models in it. You can assign a value to the model directly when passing values.
The core code of DataSource is as follows:

public class DataSource {    public Job job;    private static DataSource instanceDataSource;    public static DataSource shareInstance(){        if (null == instanceDataSource) {            instanceDataSource = new DataSource();        }        return instanceDataSource;    }}

Well, suppose we have a job list page (JobActivity, Figure 1) and a job details page (JobDetailActivity, figure 2). The most common scenario is to select an item on the list page, go to the details page. The core code for passing values is as follows:

// In JobActivity, click an item on the list page, corresponding to the listview onItemClick method public void onItemClick (AdapterView
  Parent, View view, int position, long id) {Intent intent = new Intent (); // The member variable of mJobs is the data source of Listview, assign a value to a model (job) of the data source. Since datasource is a Singleton, once all the member variables are assigned a value, they will stay in the memory and will not change, therefore, the passed value is a DataSource that will not change. your instance (). job = JobActivity. this. mJobs. get (position); intent. setClass (this, JobDetailActivity. class); this. startActivity (intent );}

The following is the core code for accepting values:

// In JobDetailActivity, protected void oncreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_job_detail); // obtain the corresponding model Job = DataSource. your instance (). job; // Let's make a judgment, haha! If (null! = Job) {titleTextView = (TextView) findViewById (R. id. jobdetail_title_textview); titleTextView. setText (null! = Job. jobName? Job. jobName:); areaTextView = (TextView) findViewById (R. id. jobdetail_area_textview); areaTextView. setText (null! = Job. workArea? Job. workArea:); salaryTextViearw = (TextView) findViewById (R. id. jobdetail_salary_textview); salaryTextViearw. setText (null! = Job. workSalary? Job. workSalary:); companyTextView = (TextView) findViewById (R. id. jobdetail_company_textview); companyTextView. setText (null! = Job. workCompany? Job. workCompany:); contactTextView = (TextView) findViewById (R. id. jobdetail_contact_textview); contactTextView. setText (null! = Job. workContact? Job. workContact :);}}

The biggest advantage of this method is that it is easy to understand, simple and crude. In addition, the mvc design pattern is used. The most important thing is that values can be transmitted from A to B and from B to A, which is quite convenient, it is an essential method for advanced and excellent programmers, and has some disadvantages:
(1) The object is resident in the memory. If a large model is encountered, the memory is consumed. (Of course, you can also set the model to null in time to solve this problem .)
(2) Because DataSource is a Singleton, multithreading must be considered. This article does not consider concurrency for ease of demonstration. But it must be considered during development. Imagine that after the main thread obtains the job object, a thread we start in the background is changing the value of the job object, then ..... There must be something wrong with the data! All in all, this is the best value transfer method to test your technology.

Set the value in the model to Intent.

The names of Android designers are a bit confusing. For example, a page is called a controller or a page rather than an Activity, unlike ios. The classes of the two values passed by the Activity are named intent, which means "intention". I really don't know what their "intention" is.
To put it bluntly, go directly to the core code:
The core method for intent to pass the model is:

Intent  putExtra(String name, Bundle value)

This bundle is the object to be passed.
First, we need to serialize our Job object:

// The two keywords implements Serializable after the job class are serialization! Public class Job implements Serializable {public String jobName; public String jobId; public String workArea; public String workTime; public String workSalary; public String workDescription; public String workCompany; public String workContact; public String poster ;}

Next we will start to pass the value!

Intent intent = new Intent (this, JobDetailActivity. class); Bundle bundle = new Bundle (); // The job object is the previously serialized object bundle. putParcelable (PAR_KEY, job); intent. putExtras (bundle );

The second method has been demonstrated. I wonder if you have any feelings after reading it. Does it feel no better? But it's okay. Let's take a look. It's even more troublesome to continue. Let's continue to follow our principle of simplicity to difficulty!

2. Return the value through intent

1. the return value is relatively troublesome on ios or Android. It is passed through a proxy in the early stage of ios. If the technology is available in the later stage, you can directly separate the transfer value from the transfer control, great!
Two methods are involved in returning a value in Android.

startActivityForResult() onActivityResult()

Imagine a scenario where to implement area-based filtering in JobActivity, you have to have a region selection page (AreaSelectActivity, see Figure 3 ), select a region and refresh the Listview to load the work of the corresponding region.

Therefore, we need to finish the AreaSelectActivity page after the user selects a region on AreaSelectActivity, and then tell JobActivity that the user has selected a region. We need to filter out all the work in this region.
Now, let's get started.
1. Click the filter button of JobActivity and write the following code:

Public void onClick (View v) {switch (v. getId () {// The button with id job_area_button is a filter button shown in case R. id. job_area_button: {Intent intent = new Intent (); // sets the intent of the activity to jump. setClass (this, AreaSelectActivity. class); // This sentence is very important, that is, the first of the two methods I mentioned earlier. What distinguishes it from the startActivity method is that he told the compiler, on this page, I want to accept the return value of the next page. RESULT_CODE_AREASELECT is a constant written by myself. You can replace startActivityForResult (intent, RESULT_CODE_AREASELECT) with any integer variable;} break ;}}

2. Click an item in the activity AreaSelectActivity and write the following code:

Public void onItemClick (AdapterView
  Parent, View view, int position, long id) {switch (parent. getId () {// This id bit area_all_listview is the listview case R of AreaSelectActivity. id. area_all_listview: {Intent intent = new Intent (this, JobActivity. class); intent. putExtra (position, position); // The key is this sentence. He tells the previous activity (JobActivity) that I have set a tag, RESULT_ OK, it is used to identify which activity is passed over the value (because JobActivity may have to accept the return value of multiple activities) setResult (RESULT_ OK, intent); this. finish () ;}break ;}}

3. Accept the return value in JobActivity:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (JobActivity.RESULT_CODE_AREASELECT == requestCode) {            if (null == data) {                return;            }            int position = data.getIntExtra(position, 0);            System.out.println(postion: + position);        }}

First, explain the meanings of several parameters in onActivityResult,
(1) requestCode: self-evident, that is, the request code, that is, the constant RESULT_CODE_AREASELECT I set earlier.
(2) resultCode: return code, that is, RESULT_ OK.
(3) data: the data is encapsulated with intent.
So, let's first determine whether the request code is
JobActivity. RESULT_CODE_AREASELECT
If yes, it indicates that AreaSelectActivity is returned, and our logic is written in it. You can obtain the position in the intent.

Now, all the value transfer methods have been introduced. It's so tired. You are welcome to talk about it!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.