Android Application Development: Fragment and large data cache, androidfragment

Source: Internet
Author: User

Android Application Development: Fragment and large data cache, androidfragment
Introduction


In Android Application Development: The document setRetaineInstance for non-interrupted Fragment storage has introduced how to save data without destroying the Fragment Activity. In the architecture design of mobile applications, interfaces and data are inseparable and cannot be confused. In most of our development experiences, we use Fragment for interface programming. Even if we save data, it is basically just the data of interface-related controls, and few other data is saved, after all, this is contrary to the development principles. Today, this blog will introduce the alternative usage of Fragment, which is only used to save data without any interface elements.


Implementation background


For the Fragment data storage method, it is not difficult to think of it or it is related to setRetainInstance. In this way, the background needs to be used when the screen is rotated or other configurations are changed. Whether in development, our interface is generated by Activity or Fragment. When the screen is rotated, the control status and necessary data cache work will be performed in the onSaveInstanceState of the life cycle. Bundle is usually used to store data. As the official introduction of Bundle says, Bundle is a map used to store strings and other serialized data types. There is also an exception in Android: http://developer.android.com/intl/zh-cn/reference/android/ OS /TransactionTooLargeException.html


This exception is literally an exception in data transmission. The description shows that the size of data transmitted by applications in the current Android system is limited to 1 MB. Therefore, it is not safe to use Bundle to cache big data during screen rotation. Bitmap is one of the classic representatives of such big data in Android. Even if Bitmap is already serialized data and Bundle can be easily used as the cache medium, I strongly do not recommend this. Below, we provide a simple solution.


Implementation Process


First, create a Fragment to save the data:

public class BitmapDataFragment extends Fragment {    public static final String TAG = "bitmapsaver";    private Bitmap bitmap;    private BitmapDataFragment(Bitmap bitmap) {        this.bitmap = bitmap;    }    public static BitmapDataFragment newInstance(Bitmap bitmap) {        return new BitmapDataFragment(bitmap);    }    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setRetainInstance(true);    }    public Bitmap getData() {        return bitmap;    }}

This Fragment does not have any interface. In the onCreate lifecycle, use setRetainInstance (true) to ensure that data is not destroyed along with the carrier, thus ensuring data security.


After creation, let's take a look at the usage process. Assume that the user is Activity:


@Override    protected void onSaveInstanceState(Bundle outState) {        if (mBitmap != null) {            getSupportFragmentManager().beginTransaction()                    .add(BitmapDataFragment.newInstance(mBitmap), BitmapDataFragment.TAG)                    .commit();            outState.putBoolean(SENSE_IMAGE_KEY, true);        } else {            outState.putBoolean(SENSE_IMAGE_KEY, false);        }        super.onSaveInstanceState(outState);    }

When the device rotates, it detects a Bitmap displayed on the current interface. If there is data, a new Fragment we just created will be generated and the Bitmap data will be placed in, then add the Fragment to the FragmentManager and specify the tag, so that we can conveniently find it after it is restored.


During restoration, the lifecycle of the Activity goes to onCreate (). Here we can check the Bundle parameter to determine whether Bitmap data is available:


if (savedInstanceState.getBoolean(SENSE_IMAGE_KEY)) {     BitmapDataFragment fragment = (BitmapDataFragment) getSupportFragmentManager()         .findFragmentByTag(BitmapDataFragment.TAG);     bitmap = fragment.getData();     getSupportFragmentManager().beginTransaction().remove(fragment).commit();}

PS: do not forget to remove the Fragment used as a data container from the FragmentManager after extracting the required Bitmap data to release the system memory occupied by it.


Summary


The non-mainstream usage of Fragment is quite simple. It is more complicated to use Bundle to save data, but it is still a good thing for applications to transfer data more securely. Recommendation index: Five Stars★★★★★!


In Android development, some data in applications are cached. How do I do this? For example, if my data needs to be retained for about 10 days, what should I do?

As a complete application, data storage operations are essential. Therefore, the Android system provides four data storage methods. They are SharePreference, SQLite, Content Provider, and File. In Android, data is basically private and stored in the "data/package name" directory. Therefore, to share data, use Content Provider.

SQLite: SQLite is a lightweight database that supports basic SQL syntax and is a common data storage method. Android provides a class named SQLiteDatabase for this database, which encapsulates APIs for database operations.

SharedPreference: in addition to the SQLite database, SharedPreference is another common data storage method. In essence, SharedPreference is an xml file, which is often used to store simple parameter settings.

File: A File (I/O) storage method. It is often used to store a large amount of data, but the disadvantage is that updating data will be a difficult task.

ContentProvider: a data storage method that can be shared by all applications in the Android system. Because data is usually private among applications, this storage method is rarely used, however, it is an essential storage method. For example, audio, video, image, and address book can be stored in this way. Each Content Provider provides a public URI (encapsulated as a Uri object). If the application needs to share data, the Content Provider needs to define a URI for the data, then other applications pass in the URI through the Content Provider to operate the data.

How to disable data reload when switching between android fragment

For how to switch, if you use ViewPager to switch, there is a setOffScreenxxx or something.

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.