- 浏览: 5781824 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (890)
- WindowsPhone (0)
- android (88)
- android快速迭代 (17)
- android基础 (34)
- android进阶 (172)
- android高级 (0)
- android拾遗 (85)
- android动画&效果 (68)
- Material Design (13)
- LUA (5)
- j2me (32)
- jQuery (39)
- spring (26)
- hibernate (20)
- struts (26)
- tomcat (9)
- javascript+css+html (62)
- jsp+servlet+javabean (14)
- java (37)
- velocity+FCKeditor (13)
- linux+批处理 (9)
- mysql (19)
- MyEclipse (9)
- ajax (7)
- wap (8)
- j2ee+apache (24)
- 其他 (13)
- phonegap (35)
最新评论
-
Memories_NC:
本地lua脚本终于执行成功了,虽然不是通过redis
java中调用lua脚本语言1 -
ZHOU452840622:
大神://处理返回的接收状态 这个好像没有监听到 遇 ...
android 发送短信的两种方式 -
PXY:
拦截部分地址,怎么写的for(int i=0;i<lis ...
判断是否登录的拦截器SessionFilter -
maotou1988:
Android控件之带清空按钮(功能)的AutoComplet ...
自定义AutoCompleteTextView -
yangmaolinpl:
希望有表例子更好。。。,不过也看明白了。
浅谈onInterceptTouchEvent、onTouchEvent与onTouch
来自Google官方的有关Android平台的JSON解析示例,如果远程服务器使用了json而不是xml的数据提供,在Android平台上已经内置的org.json包可以很方便的实现手机客户端的解析处理。下面Android123一起分析下这个例子,帮助Android开发者需要有关 HTTP通讯、正则表达式、JSON解析、appWidget开发的一些知识。
public class WordWidget extends AppWidgetProvider { //appWidget
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
context.startService(new Intent(context, UpdateService.class)); //避免ANR,所以Widget中开了个服务
}
public static class UpdateService extends Service {
@Override
public void onStart(Intent intent, int startId) {
// Build the widget update for today
RemoteViews updateViews = buildUpdate(this);
ComponentName thisWidget = new ComponentName(this, WordWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, updateViews);
}
public RemoteViews buildUpdate(Context context) {
// Pick out month names from resources
Resources res = 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);
RemoteViews updateViews = null;
String pageContent = "";
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); //正则表达式处理,有关定义见下面的SimpleWikiHelper类
Matcher matcher = 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)); //这里是打开相应的网页,所以Uri是http的url,action是view即打开web浏览器
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0 /* no requestCode */, defineIntent, 0 /* no flags */);
updateViews.setOnClickPendingIntent(R.id.widget, pendingIntent); //单击Widget打开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);
}
return updateViews;
}
@Override
public IBinder onBind(Intent intent) {
// We don't need to bind to this service
return null;
}
}
}
有关网络通讯的实体类,以及一些常量定义如下:
public class SimpleWikiHelper {
private static final String TAG = "SimpleWikiHelper";
public static final String WORD_OF_DAY_REGEX =
"(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\}";
private static final String WIKTIONARY_PAGE =
"http://en.wiktionary.org/w/api.php?action=query&prop=revisions&titles=%s&" +
"rvprop=content&format=json%s";
private static final String WIKTIONARY_EXPAND_TEMPLATES =
"&rvexpandtemplates=true";
private static final int HTTP_STATUS_OK = 200;
private static byte[] sBuffer = new byte[512];
private static String sUserAgent = null;
public static class ApiException extends Exception {
public ApiException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public ApiException(String detailMessage) {
super(detailMessage);
}
}
public static class ParseException extends Exception {
public ParseException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}
public static void prepareUserAgent(Context context) {
try {
// Read package name and version number from manifest
PackageManager manager = context.getPackageManager();
PackageInfo info = 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 String getPageContent(String title, boolean expandTemplates)
throws ApiException, ParseException {
String encodedTitle = Uri.encode(title);
String expandClause = expandTemplates ? WIKTIONARY_EXPAND_TEMPLATES : "";
String content = getUrlContent(String.format(WIKTIONARY_PAGE, encodedTitle, expandClause));
try {
JSONObject response = new JSONObject(content);
JSONObject query = response.getJSONObject("query");
JSONObject pages = query.getJSONObject("pages");
JSONObject page = pages.getJSONObject((String) pages.keys().next());
JSONArray revisions = page.getJSONArray("revisions");
JSONObject revision = revisions.getJSONObject(0);
return revision.getString("*");
} catch (JSONException e) {
throw new ParseException("Problem parsing API response", e);
}
}
protected static synchronized String getUrlContent(String url) throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("User-Agent", sUserAgent); //设置客户端标识
try {
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
throw new ApiException("Invalid response from server: " +
status.toString());
}
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent(); //获取HTTP返回的数据流
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readBytes = 0;
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes); //转化为字节数组流
}
return new String(content.toByteArray()); //从字节数组构建String
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}
}
有关整个每日维基的widget例子比较简单,主要是帮助大家积累常用代码,了解Android平台 JSON的处理方式,毕竟很多Server还是Java的。
http://www.android123.com.cn/androidkaifa/664.html
public class WordWidget extends AppWidgetProvider { //appWidget
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
context.startService(new Intent(context, UpdateService.class)); //避免ANR,所以Widget中开了个服务
}
public static class UpdateService extends Service {
@Override
public void onStart(Intent intent, int startId) {
// Build the widget update for today
RemoteViews updateViews = buildUpdate(this);
ComponentName thisWidget = new ComponentName(this, WordWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, updateViews);
}
public RemoteViews buildUpdate(Context context) {
// Pick out month names from resources
Resources res = 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);
RemoteViews updateViews = null;
String pageContent = "";
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); //正则表达式处理,有关定义见下面的SimpleWikiHelper类
Matcher matcher = 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)); //这里是打开相应的网页,所以Uri是http的url,action是view即打开web浏览器
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0 /* no requestCode */, defineIntent, 0 /* no flags */);
updateViews.setOnClickPendingIntent(R.id.widget, pendingIntent); //单击Widget打开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);
}
return updateViews;
}
@Override
public IBinder onBind(Intent intent) {
// We don't need to bind to this service
return null;
}
}
}
有关网络通讯的实体类,以及一些常量定义如下:
public class SimpleWikiHelper {
private static final String TAG = "SimpleWikiHelper";
public static final String WORD_OF_DAY_REGEX =
"(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\}";
private static final String WIKTIONARY_PAGE =
"http://en.wiktionary.org/w/api.php?action=query&prop=revisions&titles=%s&" +
"rvprop=content&format=json%s";
private static final String WIKTIONARY_EXPAND_TEMPLATES =
"&rvexpandtemplates=true";
private static final int HTTP_STATUS_OK = 200;
private static byte[] sBuffer = new byte[512];
private static String sUserAgent = null;
public static class ApiException extends Exception {
public ApiException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public ApiException(String detailMessage) {
super(detailMessage);
}
}
public static class ParseException extends Exception {
public ParseException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}
public static void prepareUserAgent(Context context) {
try {
// Read package name and version number from manifest
PackageManager manager = context.getPackageManager();
PackageInfo info = 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 String getPageContent(String title, boolean expandTemplates)
throws ApiException, ParseException {
String encodedTitle = Uri.encode(title);
String expandClause = expandTemplates ? WIKTIONARY_EXPAND_TEMPLATES : "";
String content = getUrlContent(String.format(WIKTIONARY_PAGE, encodedTitle, expandClause));
try {
JSONObject response = new JSONObject(content);
JSONObject query = response.getJSONObject("query");
JSONObject pages = query.getJSONObject("pages");
JSONObject page = pages.getJSONObject((String) pages.keys().next());
JSONArray revisions = page.getJSONArray("revisions");
JSONObject revision = revisions.getJSONObject(0);
return revision.getString("*");
} catch (JSONException e) {
throw new ParseException("Problem parsing API response", e);
}
}
protected static synchronized String getUrlContent(String url) throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("User-Agent", sUserAgent); //设置客户端标识
try {
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
throw new ApiException("Invalid response from server: " +
status.toString());
}
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent(); //获取HTTP返回的数据流
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readBytes = 0;
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes); //转化为字节数组流
}
return new String(content.toByteArray()); //从字节数组构建String
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}
}
有关整个每日维基的widget例子比较简单,主要是帮助大家积累常用代码,了解Android平台 JSON的处理方式,毕竟很多Server还是Java的。
http://www.android123.com.cn/androidkaifa/664.html
发表评论
-
http://www.android-studio.org/
2018-08-06 09:25 0http://www.android-studio.org/ ... -
SlidingDrawer源码
2012-03-14 10:13 3777我把SlidingDrawer源码提了出来,希望对1.5的朋友 ... -
简单拖动效果(带Cache,需要完善)
2011-10-13 15:10 4187如何去实现一个具有幻象的拖拽效果? 所谓”幻象“就是当你按下去 ... -
Android Activity中启动另一应用程序的方法,无需得到类名
2011-08-02 14:46 17206在网上搜索了一会相关的实现代码,发现所有的文章都说是需要包名和 ... -
java-universal-tween-engine,一个动画系统库
2011-06-29 09:21 6706http://code.google.com/p/java-u ... -
网上发现的一个android UI包
2011-05-24 12:21 4054里面有些UI和效果 -
android中使用代码启动其他程序
2011-04-29 23:15 5228你要訪問其他的程序,那麼這個程序要先裝載到模擬器或真機上面,因 ... -
listView背景问题以及限制editText字数以及如果想通知别人已经不能在写
2011-04-29 22:44 31651.在listView设置好背景之后 你如果点击空白出 你会发 ... -
Android键盘和触摸事件处理
2011-04-29 22:32 6967activity和VIEW都能接收触摸和按键,如果响应事件只需 ... -
Android的绘制文本对象FontMetrics的介绍及绘制文本
2011-04-29 22:29 11464一。Android绘制文本对象FontMetrics介绍 ... -
Android View 拖动&插入
2011-04-29 22:20 3511View 拖动&插入 即: 支持 拖动图标 然后 ... -
使TextView文本可以水平和垂直滚动
2011-04-29 21:59 14345在做一个小的电子书程序,要求电子书具有放大缩小的功能,所以肯定 ... -
ArrayAdapter源码
2011-04-29 12:29 6266看看人家怎么写的。 /* * Copyright (C ... -
Android下获取开机时间
2011-04-02 21:51 6188找了一圈没发现能得到开机启动时间资料,于是乎突发奇想,得到了解 ... -
AutoCompleteTextView连接到数据库
2011-03-30 20:49 4659AutoCompleteTextView可以根据输入 ... -
改变屏幕Brightness(亮度)
2011-03-30 12:48 4568http://www.eoeandroid.com/forum ... -
android 拖拽图片&拖动浮动按钮到处跑
2011-02-24 20:55 31710来自老外: import android.app.Acti ... -
拖动一个控件在另一个控件(layout)上,并固定位置在几个位置显示
2011-02-24 20:51 5860实现效果: 鼠标拖动btn SSS,SSS在水平的layo ... -
Handler与Message类,实现n秒后无操作自动消失功能
2011-02-24 20:45 4602实现功能:某控件不操作10秒后,自动消失。如照相机变焦条出现后 ... -
带删除按钮的ListView
2011-02-24 10:33 6117不用说了,上图先: import java.util.A ...
相关推荐
Android JSON解析示例代码.txt
android之json和gson数据解析最完整的代码例子(包括各种样式的json数据) 本人在2.3.3模拟器上已亲测可以运行。最适合学习json 或gson数据解析的初学者。
Android JSON 解析库的使用 里面包括详细的文档和代码 其中fastjson和gson的对比以及示例代码
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。...易于人阅读和编写,同时也易于机器解析和生成。 如果曾经使用过Json,就会清楚Json可以分为两个部分: 1. Json Object(A collection
本篇文章主要介绍了Android解析json数据示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
json解析的代码示例,以及android 实用Gson解析json的步骤与代码
json生成与解析示例,里面包含java和android的相关代码
解决当内存资源不充足时大数据量的JSON文本解析为JSON对象会导致内存溢出的问题。 基于org.json的部分源代码,以及新增的JsonLazyer...使用方法可以查看jar包中的Sample.java示例代码。 大容量JSON文本解析为JSON对象。
android google gson json解析
本篇文章主要介绍了Android之解析JSON数据示例,主要使用android原生态代码解析,FastJson,Gson三种方法,有兴趣的可以了解一下。
文章:【JSON解析】JSON解析的示例代码,下载导入eclipse运行测试,丰富的JSON解析方式。
$jsonstr =json_encode($value); $url=”http://127.0.0.1:8080/get.php?id=100&value=$jsonstr”; $html = file_get_contents($url); echo $html; ?> get.php文件如下: 复制代码 代码如下: <?php $...
与此同时,js主动调用android的对象方式,android也无法返回给js一个jsonobject,需要js做一下转换,例如: Android 代码: 代码如下: WebView mWebView = (WebView) this.findViewById(R.id.webview); WebSettings
主要给大家介绍了关于Android中WebView交互传递json字符串并解析的相关资料,文中通过示例代码介绍的非常详细,对各位Android开发者具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
Android-Json解析代码示例JSON是将XML存储在文件中的XML的最佳替代方法。 解析和访问以JSON格式存储的数据很容易。 您可以在此处找到有关如何使用代码库的完整教程: 本教程由The App Guruz提出-最好的
阿里云官方网站给的接入Android sdk示例,是一整套功能都具备了,程序复杂,对于入门级的小白来说,简直就是天书。本例给出了最基本的设备接入、订阅、发布三个功能的示例。设备接入给出了旧版公共实例(新版的可以...
非常实用的安卓代码学习资源,通过这些代码,让你在短时间内掌握Android的一些基础玩法! Android工程: 1.json数据传输 2.listview带翻页 3.radio和checkbox 4.RelativeLayout 5.ROM文件读写 6.SD卡读写 7.spinner...
第1章 Android应用与开发环境 1 1.1 Android的发展和历史 2 1.1.1 Android的发展和简介 2 1.1.2 Android平台架构及特性 3 1.2 搭建Android开发环境 5 1.2.1 下载和安装Android SDK 5 1.2.2 安装...