Android development skills 3

Source: Internet
Author: User

10. Android Theme and Styles internal definition Parsing

We talked about AndroidManifest yesterday. the theme method of the Activity is defined in xml to implement the Untitled method. As mentioned in the article about how to use xml to make your Activity untitled, many netizens do not understand why this is done, in fact, the styles style definition method has been mentioned many times in previous articles of Android123. Today, Android Development Network review some netizens to learn about the internal definition of android styles. In a project's res/values/theme. in xml, we can easily define our own style themes. For example, in the following cwjTheme, we use the background Theme based on the white tone inside android. light: If windowsNoTitle is set to true, there is no question. The background color is transparent defined in android, and the style of the listView control is set to cwjListView. The xml style code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>
<Style name = "cwjTheme" parent = "android: Theme. Light">
<Itemname = "android: windowNoTitle"> true </item>
<Itemname = "android: windowBackground"> @ android: color/transparent </item>
<Item name = "android: listViewStyle"> @ style/cwjListView </item>
</Style>

The custom style of the ListView control is to modify the delimiter style of each row of the system listview control. Here we place an image named list_selector In the res/drawable folder of the project, in this way, the code of our cwjListView can be written in this way.

<Style name = "cwjListView" parent = "@ android: style/Widget. ListView">
<Item name = "android: listSelector"> @ drawable/list_selector </item>
</Style>
</Resources>

You can set more settings by defining the style. For example, you can add the font color of cwjListView to the textAppearance attribute, for example, <itemname = "textAppearance"> @ android: style/TextAppearance </item>.

11. Android JSON parsing sample code

For example, if the remote server uses JSON instead of xml data. the json package can be used to conveniently parse the mobile client. The following Android123 analyzes this example to help Android Developers learn about HTTP Communication, regular expressions, JSON parsing, and appWidget development.

Public class WordWidget extends AppWidgetProvider {// appWidget
@ Override
Public void onUpdate (Context context, AppWidgetManagerappWidgetManager,
Int [] appWidgetIds ){
Context. startService (newIntent (context, UpdateService. class); // avoid ANR, so a service is enabled in the Widget.
}

Public static class UpdateServiceextends Service {
@ Override
Public void onStart (Intent intent, int startId ){
// Build thewidget update for today
RemoteViewsupdateViews = buildUpdate (this );

ComponentName thisWidget = new ComponentName (this, WordWidget. class );
AppWidgetManagermanager = AppWidgetManager. getInstance (this );
Manager. updateAppWidget (thisWidget, updateViews );
}

PublicRemoteViews buildUpdate (Context context ){
// Pick outmonth names from resources
Resourcesres = context. getResources ();
String [] monthNames = res. getStringArray (R. array. month_names );

Time today = new Time ();
Today. setToNow ();

String pageName = res. getString (R. string. template_wotd_title,
MonthNames [today. month], today. monthDay );
RemoteViewsupdateViews = null;
StringpageContent = "";

Try {
SimpleWikiHelper. prepareUserAgent (context );
PageContent = SimpleWikiHelper. getPageContent (pageName, false );
} Catch (ApiException e ){
Log. e ("WordWidget", "Couldn't contact API", e );
} Catch (ParseException e ){
Log. e ("WordWidget", "Couldn't parse API response", e );
}

Pattern pattern = Pattern. compile (SimpleWikiHelper. WORD_OF_DAY_REGEX); // Regular Expression Processing. For the definition, see the SimpleWikiHelper class below.
Matchermatcher = pattern. matcher (pageContent );
If (matcher. find ()){
UpdateViews = new RemoteViews (context. getPackageName (), R. layout. widget_word );

String wordTitle = matcher. group (1 );
UpdateViews. setTextViewText (R. id. word_title, wordTitle );
UpdateViews. setTextViewText (R. id. word_type, matcher. group (2 ));
UpdateViews. setTextViewText (R. id. definition, matcher. group (3). trim ());

String definePage = res. getString (R. string. template_define_url,
Uri. encode (wordTitle ));
Intent defineIntent = new Intent (Intent. ACTION_VIEW, Uri. parse (definePage); // the corresponding webpage is opened here, so the Uri is the http url, and the action is the view to open the web browser
PendingIntent pendingIntent = PendingIntent. getActivity (context,
0/* no requestCode */, defineIntent, 0/* no flags */);
UpdateViews. setOnClickPendingIntent (R. id. widget, pendingIntent); // click the Widget to open the Activity

} Else {
UpdateViews = new RemoteViews (context. getPackageName (), R. layout. widget_message );
CharSequence errorMessage = context. getText (R. string. widget_error );
UpdateViews. setTextViewText (R. id. message, errorMessage );
}
ReturnupdateViews;
}

@ Override
Public IBinder onBind (Intent intent ){
// We don't Need to bind to this service
Return null;
}
}
}

Entity classes related to network communication and some constants are defined as follows:

Public class SimpleWikiHelper {
Private static final String TAG = "SimpleWikiHelper ";

Public static final StringWORD_OF_DAY_REGEX =
"(? S) \\{\{ wotd \\| (. + ?) \\| (. + ?) \\| ([^ # \\|] + ).*? \\}\\}";

Private static final StringWIKTIONARY_PAGE =
"Http://en.wiktionary.org/w/api.php? Action = query & prop = revisions & titles = % s & "+
"Rvprop = content & format = json % s ";

Private static final StringWIKTIONARY_EXPAND_TEMPLATES =
"& Rvexpandtemplates = true ";

Private static final int HTTP_STATUS_ OK = 200;

Private static byte [] sBuffer = newbyte [1, 512];

Private static String sUserAgent = null;

Public static class ApiExceptionextends Exception {
Public ApiException (StringdetailMessage, Throwable throwable ){
Super (detailMessage, throwable );
}

PublicApiException (String detailMessage ){
Super (detailMessage );
}
}

Public static class ParseExceptionextends Exception {
Public ParseException (StringdetailMessage, Throwable throwable ){
Super (detailMessage, throwable );
}
}

Public static voidprepareUserAgent (Context context ){
Try {
// Readpackage name and version number from manifest
PackageManager manager = context. getPackageManager ();
PackageInfoinfo = manager. getPackageInfo (context. getPackageName (), 0 );
SUserAgent = String. format (context. getString (R. string. template_user_agent ),
Info. packageName, info. versionName );

} Catch (NameNotFoundException e ){
Log. e (TAG, "Couldn't find package information in PackageManager", e );
}
}

Public static StringgetPageContent (String title, boolean expandTemplates)
ThrowsApiException, ParseException {
String encodedTitle = Uri. encode (title );
String expandClause = expandTemplates? WIKTIONARY_EXPAND_TEMPLATES :"";

String content = getUrlContent (String. format (WIKTIONARY_PAGE, encodedTitle, expandClause ));
Try {
JSONObjectresponse = new JSONObject (content );
JSONObjectquery = response. getJSONObject ("query ");
JSONObjectpages = query. getJSONObject ("pages ");
JSONObjectpage = pages. getJSONObject (String) pages. keys (). next ());
JSONArrayrevisions = page. getJSONArray ("revisions ");
JSONObjectrevision = revisions. getJSONObject (0 );
Returnrevision. getString ("*");
} Catch (JSONException e ){
Throw new ParseException ("Problemparsing API response", e );
}
}

Protected static synchronized StringgetUrlContent (String url) throws ApiException {
If (sUserAgent = null ){
Throw newApiException ("User-Agent string must be prepared ");
}

HttpClientclient = new DefaultHttpClient ();
HttpGet request = new HttpGet (url );
Request. setHeader ("User-Agent", sUserAgent); // set the Client ID

Try {
HttpResponseresponse = client.exe cute (request );

StatusLine status = response. getStatusLine ();
If (status. getStatusCode ()! = HTTP_STATUS_ OK ){
Throw new ApiException ("Invalid response from server:" +
Status. toString ());
}

HttpEntity entity = response. getEntity ();
InputStreaminputStream = entity. getContent (); // gets the data stream returned by HTTP

ByteArrayOutputStream content = new ByteArrayOutputStream ();

Int readBytes = 0;
While (readBytes = inputStream. read (sBuffer ))! =-1 ){
Content. write (sBuffer, 0, readBytes); // convert to a byte array stream
}

Return new String (content. toByteArray (); // construct a String from a byte array
} Catch (IOException e ){
Throw newApiException ("Problem communicating with API", e );
}
}
}

The example of widgets for the entire daily wiki is relatively simple, mainly to help you accumulate common code and understand the JSON Processing Method of the Android platform. After all, many servers are still Java.

From LuoXianXiong, your partner

Related Article

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.