您的位置:首页 > 理论基础 > 计算机网络

高仿新闻教程——请求网络数据加入新闻内容页(11)

2014-11-05 23:53 330 查看
还记得我在学校做第一个做的APP,外卖APP,我身边的大牛,跟我说一句,你把你的那个页面的数据,传给我。

那个时候我才学安卓2个月,对于Intent的用法或者对于他的认识不是很深刻最后在百度《安卓,怎么传递数据》

结果Intent出现了。

Intent为啥出现?

当一个activity跳转的到另一个activity要考谁呢,新手都知道Intent,但是其实传递数据还真不是Intent的专利。这时候我就换下背景。

你要去你亲戚家过节,看完亲人,你妈说你顺便把礼物带过去,帮我带个平安................

其实在某个时候,安卓学完UI还真是又回到了java,还记的

埃克尔在java编程思想中说道 万物皆对象 你以为真是你自己浅薄的理解那样么,计算机因为是一个最接近科学的一门课程,就代表着你很难用人话来描述。

我所能理解的解释,用生活中的实例去理解安卓所有知识点,对象是用来服务生活的,而不是将他无限接近科学的。

所以Intent在跳转的时候,也能传递数据。

1.值由A.class传递到B.class

A.class中:

Intent intent = new Intent();
 //设置传递方向 
intent.setClass(A.this,B.class); 
//绑定数据 
intent.putExtra("username1",username); <a target=_blank href="http://download.csdn.net/detail/jack_king007/8126471">点击下载源码</a>
intent.putExtra("userpwd1"userpwd);
 /*或者绑定成一捆数据 
Bundle data = new Bundle(); 
data.putString("username1",username); 
data.putString("userpwd1",userpwd);
intent.putExtras(data); 
*/ 
//启动activity 
this.startActivity(intent);
对于Bundle 和Intent传递数据呢,我似乎记得有人这么形象的描述 Intent的是 你去超市买东西,超市没给你袋子

Boundle 就是给了你一个袋子,你可以一起带走。

B.class中:

Intent intent = getIntent();

//获取数据

String username = intent.getStringExtra("username1");

String userpwd = intent.getStringExtra("userpwd1");

/* Bundle data = intent.getExtras();

String username = intent.getString("username1");

String userpwd = intent.getString("userpwd1"); */

所以呢 看得出 我去超市买东西 是想拿袋子打包一起拿走的 所以我用的是bundle

好了回到教程中 ,我们要获取

跟帖数 commentcount

新闻标题 mCatName

position

而新闻体标题需要用一个全局变量String 来储存 private String mCatName; 然后再gridview里面获取到

mCatName = categories.get(position).get("category_title").getTitle();

跟帖数 需要在 解析数据的时候 解析出来

hashMap.put("newslist_item_comments", newsObject.getString("commentcount"));

然后开始传递

//把需要的信息放到Intent中
				intent.putExtra("newsDate", mNewsData);
				intent.putExtra("position", position);
				intent.putExtra("categoryName", mCatName);
				startActivity(intent);


好啦 现在应该传值到了 新闻内容类了 然后后面基本上就是复制给UI 然后进行JSON解析新闻内容到本地

/**
	 * 获取新闻详细信息
	 * @return
	 */
	private String getNewsBody()
	{
		String retStr = "网络连接失败,请稍后再试";
		String url="http://192.168.1.12:8080/web/getNews?nid="+mNid;
		try
		{
			String json = HttpUtils.getData(url);
			JSONObject jsonObject = new JSONObject(json);
			//获取返回码,0表示成功
			int retCode = jsonObject.getInt("ret");
			if (0 == retCode)
			{
				JSONObject dataObject = jsonObject.getJSONObject("data");
				JSONObject newsObject = dataObject.getJSONObject("news");
				retStr = newsObject.getString("body");
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return retStr;
	}


点击下载源码

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐