Udacity android Practice Notes: lesson 4 part B, udacityandroid

Source: Internet
Author: User

Udacity android Practice Notes: lesson 4 part B, udacityandroid
Udacity android Practice Notes: lesson 4 part B

Prepared by: Taobao stores/titer1/Archimedes
Source: https://code.csdn.net/titer1
Contact: September 1307316 (best SMS)
Statement: This article uses the following agreement for authorization: Free Reprint-non commercial-Non derivative-keep the signature | Creative Commons BY-NC-ND 3.0, reprint please indicate the author and the source.
Tips: https://code.csdn.net/titer1/pat_aha/blob/master/Markdown/android/

Summary

  • Fully demonstrate the process of adding content providers
  • Dynamically display the android unit test process
    Animation farming! O (^) o, animation at the end
Overviw Diagram

Old graph, (create/insert/query)

Next, let's start learning content providers.

Review four main components: content providerservicebroadcast provideractvity
Overview

4.07 init code for content provider


-Testing piling functions accounts for more than half
-WeatherContrace is modified in the traditional function.
-Added weatherProvider.
-Modified the fetchweatherTask function. The source of the Code is
Removed from the forececastFragment code.
-In addition to modifying weatherContrace, other files are newly added.

Keyword uri

The maximum number added to weatherContract is the uri generation function.

    /* Inner class that defines the table contents of the location table */    public static final class LocationEntry implements BaseColumns {    ...        public static Uri buildLocationUri(long id) {            return ContentUris.withAppendedId(CONTENT_URI, id);        }    }    ===
    /* Inner class that defines the table contents of the weather table */    public static final class WeatherEntry implements BaseColumns {        ...        public static Uri buildWeatherLocation(String locationSetting) {            return null;        }        public static Uri buildWeatherLocationWithStartDate(                String locationSetting, long startDate) {            long normalizedDate = normalizeDate(startDate);            return CONTENT_URI.buildUpon().appendPath(locationSetting)                    .appendQueryParameter(COLUMN_DATE, Long.toString(normalizedDate)).build();        }        public static Uri buildWeatherLocationWithDate(String locationSetting, long date) {            return CONTENT_URI.buildUpon().appendPath(locationSetting)                    .appendPath(Long.toString(normalizeDate(date))).build();        }        public static String getLocationSettingFromUri(Uri uri) {            return uri.getPathSegments().get(1);        }        public static long getDateFromUri(Uri uri) {            return Long.parseLong(uri.getPathSegments().get(2));        }        public static long getStartDateFromUri(Uri uri) {            String dateString = uri.getQueryParameter(COLUMN_DATE);            if (null != dateString && dateString.length() > 0)                return Long.parseLong(dateString);            else                return 0;        }    }}
4.08 uri location with weather

Only 2 updates

1/2 weatherContract
/* Student: This is the buildWeatherLocation function you filled in. */public static Uri buildWeatherLocation (String locationSetting) {return CONTENT_URI.buildUpon (). appendPath (locationSetting ). build (); // the previous version returns a null value}

### 2/2 test

Just open the comment here
"'Java
/*
Students: This is NOT a complete test for the WeatherContract-just for the functions
That we recommend CT you to write.
*/
Public class TestWeatherContract extends AndroidTestCase {

// intentionally includes a slash to make sure Uri is getting quoted correctlyprivate static final String TEST_WEATHER_LOCATION = "/North Pole";private static final long TEST_WEATHER_DATE = 1419033600L;  // December 20th, 2014/*    Students: Uncomment this out to test your weather location function. */public void testBuildWeatherLocation() {    Uri locationUri = WeatherContract.WeatherEntry.buildWeatherLocation(TEST_WEATHER_LOCATION);    assertNotNull("Error: Null Uri returned.  You must fill-in buildWeatherLocation in " +                    "WeatherContract.",            locationUri);    assertEquals("Error: Weather location not properly appended to the end of the Uri",            TEST_WEATHER_LOCATION, locationUri.getLastPathSegment());    assertEquals("Error: Weather location Uri doesn't match our expected result",            locationUri.toString(),            "content://com.example.android.sunshine.app/weather/%2FNorth%20Pole");}

}
''

4.09 write uri matcher1/2 weatherProvider

This is the code in the framework, updating one

    /*        Students: Here is where you need to create the UriMatcher. This UriMatcher will        match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE,        and LOCATION integer constants defined above.  You can test this by uncommenting the        testUriMatcher test within TestUriMatcher.     */    static UriMatcher buildUriMatcher() {        // I know what you're thinking.  Why create a UriMatcher when you can use regular        // expressions instead?  Because you're not crazy, that's why.        // All paths added to the UriMatcher have a corresponding code to return when a match is        // found.  The code passed into the constructor represents the code to return for the root        // URI.  It's common to use NO_MATCH as the code for this case.        final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);        final String authority = WeatherContract.CONTENT_AUTHORITY;        // For each type of URI you want to add, create a corresponding code.        matcher.addURI(authority, WeatherContract.PATH_WEATHER, WEATHER);        matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION);        matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*/#", WEATHER_WITH_LOCATION_AND_DATE);        matcher.addURI(authority, WeatherContract.PATH_LOCATION, LOCATION);        return matcher;    }
2/2 test

It is still a tested code framework that has been written. Only comments are opened here.

public class TestUriMatcher extends AndroidTestCase {...    /*        Students: This function tests that your UriMatcher returns the correct integer value        for each of the Uri types that our ContentProvider can handle.  Uncomment this when you are        ready to test your UriMatcher.     */    public void testUriMatcher() {        UriMatcher testMatcher = WeatherProvider.buildUriMatcher();        assertEquals("Error: The WEATHER URI was matched incorrectly.",                testMatcher.match(TEST_WEATHER_DIR), WeatherProvider.WEATHER);        assertEquals("Error: The WEATHER WITH LOCATION URI was matched incorrectly.",                testMatcher.match(TEST_WEATHER_WITH_LOCATION_DIR), WeatherProvider.WEATHER_WITH_LOCATION);        assertEquals("Error: The WEATHER WITH LOCATION AND DATE URI was matched incorrectly.",                testMatcher.match(TEST_WEATHER_WITH_LOCATION_AND_DATE_DIR), WeatherProvider.WEATHER_WITH_LOCATION_AND_DATE);        assertEquals("Error: The LOCATION URI was matched incorrectly.",                testMatcher.match(TEST_LOCATION_DIR), WeatherProvider.LOCATION);    }

···

4.10 register content provider1/2

Here only enable (open comments) testProviderRegistry

public class TestProvider extends AndroidTestCase {    ...    /*        This test checks to make sure that the content provider is registered correctly.        Students: Uncomment this test to make sure you've correctly registered the WeatherProvider.     */    public void testProviderRegistry() {        PackageManager pm = mContext.getPackageManager();        // We define the component name based on the package name from the context and the        // WeatherProvider class.        ComponentName componentName = new ComponentName(mContext.getPackageName(),                WeatherProvider.class.getName());        try {            // Fetch the provider info using the component name from the PackageManager            // This throws an exception if the provider isn't registered.            ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);            // Make sure that the registered authority matches the authority from the Contract.            assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority +                    " instead of authority: " + WeatherContract.CONTENT_AUTHORITY,                    providerInfo.authority, WeatherContract.CONTENT_AUTHORITY);        } catch (PackageManager.NameNotFoundException e) {            // I guess the provider isn't registered correctly.            assertTrue("Error: WeatherProvider not registered at " + mContext.getPackageName(),                    false);        }    }    }
AndroidManifest update
        <provider            android:authorities="com.example.android.sunshine.app"            android:name=".data.WeatherProvider" />
Nap

Add provider deployment
-It is estimated that the comparison between the first-generation version code and the second-generation code is required.

Smart Compiler

Smart notification
Android has interesting topics in debug mode, such as variable value prompts.
When there are also search characters, take the initiative to filter the characters in the comments

Test OK unit test method & testPractise


In addition, I did not select the right-click trigger, but directly run (shift f10)
(4a-28) The unit test method can be completely reproduced.


-Display running configurations
-Demonstrate how to locate an error
-Display normal conditions

The code is sunshine version2's 4.02, code: testPractise
After todo practices, what is the blank android test project? In section 4.02, there are only three effective testcase names. How can I display six testcase names?
TestCreateDb of testDb

4.04 (git version) delete the testPractise,

Actual running record: I have set a breakpoint for all assertTrue, assertFalse, and assertEqual locations, but only testCreateDb in testDb is triggered and displayed in numbers, the run window shows "6 of 6" OK, but four of the six are triggered. I suspect this 6 is outdated.
TestLocationTable of testdb

The test is complete.

  • This function completely calls the db operation function
    • Insert
    • Query

It is also interesting to call TestUtilities. validateCurrentRecord.
(Two assert instances exist, and the assert is triggered)

This is under my observation.
The first call of a function in the testUtilities class,
In the last round, I set a breakpoint in the static function of this class,
Are not called.

TestUtilities also provides the sample data inserted by the database.

After todo practices, I think: Since unit testing uses AndroidTestCase, why is testDb called every time, while testUtilities of other AndroidTestCase inheritance classes are not directly called.
TestWeatherTable and refactoring testLocationTable

4.06 lesson,
What's interesting is that the former calls
LocationTable content

All tests have passed.

In-depth todo Content Analysis // th Step: Validate the location Query TestUtilities. validateCurrentRecord ("testInsertReadDb weatherEntry failed to validate", weatherCursor, weatherValues );
Nap

The first six sections of github are unit testing.

Unit Testing is amazing.

Follow-up

From 4.06-4.10 (github)
Test functions:
-Test weatherContract
-Test uri matcher
-Test Provider
-Test providerRegistery

Construct a content provider. Every module cannot be sloppy.

Good night nap

At least the direction is bright

Next day review

Explain why not all Uris have been hit

Let's look at the demonstration of weather provider and testProvider.
The authors test the enable functions one by one. In-depth Development

Functions of almost every testProvider (query/getType/insert/updat)
Uri matcher Filtering

You can view the content of each test as follows:

Video 4b-24 is a summary of Stages

Bulkinsert actually uses transactions. Only endtrancsation can perform operations.

Section

Section: the whole chapter is the use of uri.
-Define uri
-Update uri (feflect to number)
-Uri matcher (I think, here addmatch)
-Implement (I think, sUriMatcher. match (uri );)

Speaking of this, many open-source products encapsulate content providers? Toco
How to Understand notification oserver... here

Integration

So far, our content provider has not been combined with the database.
The operation is neither test *. java nor weatherprovider.

We will focus on FetchweatherTask
-Addlocation
-GetWeatherDataFromJson insert + query part
(Processing routine after network receiving and reporting)

We can see that all the places where getContentResolver is used use contentprovider,

Last

To make the ui theread smoother, the Loader
So far, our video comes to the 4b borrow book, code
The Code scope is:

Todo code

Hello android
Goodbye to android
Haha, this blog suspends the android update. If you are interested, contact us via SMS.

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.