October 25, 2014 Android learning - batch transfer of data between activities - Implementation of Bundle class

Posted by bcarlson on Mon, 07 Mar 2022 02:12:44 +0100

I study Android in combination with the source code, which is more intuitive and very clear to see the effect. I think it's very good. Today's learning source code is a HealthFood source code found online. Baidu search knows a lot of places to download

This study needs to be combined with the previous articles,

Layout learning (III) address: http://blog.csdn.net/u014737138/article/details/40480291

Layout learning (IV) address: http://blog.csdn.net/u014737138/article/details/40508845

Implementation of SimpleAdapter http://blog.csdn.net/u014737138/article/details/40481965

In short, this article focuses on:

When an application jumps from one activity A to another activity B, how does B accept the data passed from A?

This is equivalent to the data communication between activities and the transmission of information

The method is to use the Bundle class

From the previous study, we can see that in the ListView interface, when we click on the item of each line, the page should jump to another interface, and the image we see happens to be transmitted from the above, and the value should also be dynamically set according to the item selected by the user above, which leads to the data transmission between activities.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wust.healthfood.R;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FoodInfo extends ListActivity {
	
	Button image=null;
	Button back=null;
	TextView foodinfo=null;
	String[] efood={"Coptis chinensis"};
	String [] efoodinfo={"Pork is fatty, sour, cold and greasy. If the traditional Chinese medicine formula is mainly composed of yellow lotus, pork should be avoided, otherwise it will reduce the efficacy and easily cause diarrhea."};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.foodinfo);
		// Get the passed value
		Bundle bundle = getIntent().getExtras();
		// Parsed value
		int drawable=bundle.getInt("drawable");		
		String foodname=bundle.getString("foodname");
		String efoodname=bundle.getString("efoodnema");
		String foodinfos=bundle.getString("foodinfo");
		
		image = (Button) this.findViewById(R.id.Button);
		image.setBackgroundResource(drawable);
		image.setText(foodname);
		
		foodinfo=(TextView)findViewById(R.id.TextView03);
		foodinfo.setText(foodinfos);
		
		back=(Button)findViewById(R.id.backbutton);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Button b=(Button)v;
				b.setBackgroundResource(R.drawable.btn_back_active);
				Intent intent=new Intent(FoodInfo.this, FoodListView.class);
				startActivity(intent);
			}
		});
		
		List<Map<String, Object>> data=new ArrayList<Map<String,Object>>();
		for(int i=0;i<efood.length;i++){
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("TextView04", efood[i]);
			map.put("TextView05", efoodinfo[i]);
			data.add(map);
		}
		
		SimpleAdapter adapter=new SimpleAdapter(this, data, R.layout.ex_foodinfo,new String[]{"TextView04","TextView05"} , new int[]{R.id.TextView04,R.id.TextView05});
		setListAdapter(adapter);
		
		
	}
	
	

}

Profiling code:

When the interface is set, we define a Bundle object:

1. / / get the passed value Bundle bundle = getIntent().getExtras();

//getIntent() can get the object (Intent) passed by activity, and then call getExtras() function. We can get the batch data that is delivered. Note that the data is inherited from Map.

Intent android. app. Activity . getIntent() / / this can help us understand what is the return value of getIntent() and who will call it Bundle android . content . Intent . getExtras() / / this can let us know what the return value of getExtras() is and who will call it Now we need to analyze the Bundle class, Let's see how Bundle is introduced in the document:

It is a map. The definition of this map is to map different Parcelable types from a String. Let's ignore the rest. What we can know is that this object is a map, and the key values in it are of String type This is consistent with the elements of the list < map < string, Object > > lists array we created earlier. Next, let's just take out the value inside. Let's see if there is a get function in the document. We find:

This get(String key) function is used to return an object entity class according to the given key value string, so it is Ok and can be handled in this way. Let's look at the code: //Parsed value int drawable=bundle.getInt("drawable"); String foodname=bundle.getString("foodname"); String efoodname=bundle.getString("efoodnema"); String foodinfos=bundle.getString("foodinfo"); It is clear that we can get the data information we need according to the specified string But we also ignored one point, that is, how to set the data I passed? Let's look at the previous code: @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); for (int j = 0; j < efood.length; j++) { Map<String, Object> map = new HashMap<String, Object>(); map.put(efood[j], efoodinfo[j]); data.add(map); } //The parameter position is the number of rows where the item is located. It is a key parameter Intent intent = new Intent();// Declare an intention intent.setClass(FoodListView.this, FoodInfo.class); intent. putExtra("drawable", resId[position]);// The first data is placed in intent. The key value is String=drawable and the value is resid [position] intent. putExtra("foodname", food[position]);// The second data is placed in intent. The key value is String=foodname and the value is food [position] intent. putExtra("efoodnema", food1[position]);// The third data is placed in intent. The key value is String=efoodname and the value is food1 [] intent. putExtra("foodinfo", foodjianjie[position]);// The fourth data is placed in intent. The key value is String=foodinfo and the value is startActivity(intent);// Activate intention, page Jump } The above code takes out the corresponding value through these key values

The analysis here perfectly solves the problem of data transmission between activities,

Summary:

1. How does a transfer data

First, define an intention, intent = new intent();

Secondly, set the transmitted data: use intent putExtra(Key,Value);, If it is batch data, use the for loop to set

2.B how to obtain data:

First define a bundle object, using getintent() Getextras () to generate a bundle object

Secondly, take data and use bundle Get (string key) to get the passed value

Next, we will analyze other codes:

image = (Button) this.findViewById(R.id.Button);// Find the button control of the sub relative layout in the layout view. This button is set with a picture image.setBackgroundResource(drawable);// Set the background picture of the button control image.setText(foodname);// Set the contents of the button

foodinfo=(TextView)findViewById(R.id.TextView03);// Locate the text display control to the right of the button foodinfo.setText(foodinfos);// Set text content

back=(Button)findViewById(R.id.backbutton);// Return button control found back.setOnClickListener(new OnClickListener() {/ / returns the listening event of the button @Override public void onClick(View v) { // TODO Auto-generated method stub Button b=(Button)v;// Note the parameters here. In Android system, all widget s can be regarded as a View object b.setBackgroundResource(R.drawable.btn_back_active);// Set the background picture of the button Intent intent=new Intent(FoodInfo.this, FoodListView.class);// Returning to the previous interface is also intended with intent startActivity(intent); } });

So far, all the codes have been completely solved. Next, there is a manifest file that has not been learned:

To execute these activities, they must be defined in the manifest file, otherwise the program cannot be found:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wust.healthfood"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.wust.healthfood.activity.MainApp"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.wust.healthfood.activity.FoodListView"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.wust.healthfood.activity.About"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.wust.healthfood.activity.FoodInfo"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>

The next article will continue to introduce the list file