一、建设新闻资料库
例如,下面的脚本代码:(正在使用mysql5.0 数据库)
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
-- Database: `newsdemo`
-- 表的结构 `news`
CREATE TABLE IF NOT EXISTS `news` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` text NOT NULL,
`desc` text NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`content_url` text NOT NULL,
`pic_url` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- 转存表中的数据 `news`
--
INSERT INTO `news` (`id`, `title`, `desc`, `time`, `content_url`, `pic_url`) VALUES
(1, 'Oracle解锁封锁的账号', '我们在安装Oracle的时候最后一步有一个管理账户的,里边能够解锁所所需的账户', '2015-03-15 11:50:03', 'http://blog.csdn.net/xlgen157387/article/details/41595709', 'http://img.blog.csdn.net/20141129144613046?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGxnZW4xNTczODc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center'
),
(2, 'Android程序之全国天气预报查询(聚合数据开发)', '项目演示效果例如以下: 项目源码下载地址: 訪问password 2eac二、使用 聚合数据SDK:', '2015-03-15 11:50:13', 'http://blog.csdn.net/xlgen157387/article/details/44246119', 'http://img.blog.csdn.net/20150314095028546');
运行结果例如以下:(因为这是使用的appserv。所以在phpMyAdmin中看到的这样的效果1)
二、将数据库中的数据转化为json数据
因为使用的是php语言,所以要安装appserv(这个东西百度一下就知道怎么使用。不在研究。)
(1)在appserv文件夹下的www文件夹下创建一个文件夹NewsDemo。文件夹中创建两个php文件例如以下:
连接数据库的文件mysql_connect.php
<?php
$con = mysql_connect("localhost", "root", "your password!");
//设置字符集为utf8
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET CHARACTER_SET_RESULT=utf8");
if (!$con){
die(mysql_error());
}
mysql_select_db("newsdemo", $con);
?>
详细用于创建json数据的getNewsJSON.php
<?php
/*
* 获得JSON数据
* 返回值:title desc time content_url pic_url
*/
require 'mysql_connect.php';
$n = 0;
$result = mysql_query("select * from news");
while ($row = mysql_fetch_array($result)){
$arr[$n++] = array("title" => $row['title'],
"desc" => $row['desc'],
"time" => $row['time'],
"content_url" => $row['content_url'],
"pic_url" => $row['pic_url']
);
}
//数组转换为JSON字符串
echo json_encode($arr);
?>
然后訪问地址:http://localhost:8080/NewsDemo/getNewsJSON.php
假设出现下面“乱码”表示成功!
另外给大家一个在线查看json数据的网址:http://json.parser.online.fr/
到此数据库的准备完毕,開始做client!
三、client的实现
项目结构:
MainActivity.java例如以下:
package com.xuliugen.news;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.xuliugen.news.adapter.NewsAdapter;
import com.xuliugen.news.model.News;
import com.xuliugen.news.utils.HttpUtils;
public class MainActivity extends Activity implements OnItemClickListener{
private ListView lvNews;
private NewsAdapter adapter;
private List<News> newsList;
//此处须要改动为自己的server地址:也就是详细的server地址:这里不要写你的localhost或者127.0.0.1因为这是要在手机上运行的!
public static final String GET_NEWS_URL = "http://172.23.252.89:8080/NewsDemo/getNewsJSON.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvNews = (ListView) findViewById(R.id.lvNews); //一条一条的消息展示消息
newsList = new ArrayList<News>(); //初始化
adapter = new NewsAdapter(this, newsList); //也是初始化。会在后期运行getNewsJSON()方法之后更新
lvNews.setAdapter(adapter); //设置构造器
lvNews.setOnItemClickListener(this);
//这里运行了网络的的请求操作
HttpUtils.getNewsJSON(GET_NEWS_URL, getNewsHandler); //传入的一个handler对象
}
// 这里是訪问网络数据的时候。返回的handler
private Handler getNewsHandler = new Handler(){
/**
* 这种方法是Handler自带的方法。用于接受返回的数据
*/
public void handleMessage(android.os.Message msg) {
String jsonData = (String) msg.obj;
System.out.println(jsonData);
try {
//下边是解析json
JSONArray jsonArray = new JSONArray(jsonData);
for (int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("desc");
String time = object.getString("time");
String content_url = object.getString("content_url");
String pic_url = object.getString("pic_url");
newsList.add(new News(title, desc, time, content_url, pic_url));
}
adapter.notifyDataSetChanged();//通知适配器数据发生变化
} catch (Exception e) {
e.printStackTrace();
}
};
};
/**
* 每个条目的点击事件
*/
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
//获取被点击的对象
News news = newsList.get(position);
Intent intent = new Intent(this, BrowseNewsActivity.class);
intent.putExtra("content_url", news.getContent_url()); //依据被点击的对象。获取其url
startActivity(intent);
}
}
HttpUtils.java例如以下:
package com.xuliugen.news.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
/**
* 訪问网络的工具类
*
* @author xuliugen
*
*/
public class HttpUtils {
public static void getNewsJSON(final String url, final Handler handler) {
//要訪问网络,开启一个线程
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection conn;
InputStream inputStream;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
StringBuilder result = new StringBuilder(); //StringBuilder初始化不能够null
while ((line = reader.readLine()) != null) {
result.append(line);
}
//使用handler的话要使用Message
Message msg = new Message();
msg.obj = result.toString();
// 通知主线程handler
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 设置图片的信息
*
* 在适配器里边调用
*
* @param ivPic 须要设置的view组件
* @param pic_url 图片的地址
*/
public static void setPicBitmap(final ImageView ivPic, final String pic_url) {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(pic_url).openConnection();
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
ivPic.setImageBitmap(bitmap);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
用于保存json数据的bean–》News.java
package com.xuliugen.news.model;
/**
* 与json数据相相应的bean
*
* @author xuliugen
*
*/
public class News {
private String title;
private String desc;
private String time;
private String content_url;
private String pic_url;
/**
* 全參的构造函数
*
* @param title
* @param desc
* @param time
* @param content_url
* @param pic_url
*/
public News(String title, String desc, String time, String content_url,
String pic_url) {
setTitle(title);
setDesc(desc);
setTime(time);
setContent_url(content_url);
setPic_url(pic_url);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getContent_url() {
return content_url;
}
public void setContent_url(String content_url) {
this.content_url = content_url;
}
public String getPic_url() {
return pic_url;
}
public void setPic_url(String pic_url) {
this.pic_url = pic_url;
}
}
NewsAdapter.java例如以下:
package com.xuliugen.news.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.xuliugen.news.R;
import com.xuliugen.news.model.News;
import com.xuliugen.news.utils.HttpUtils;
/**
* 用于显示在界面上的item
*
* @author piaodangdehun
*
*/
public class NewsAdapter extends BaseAdapter {
private Context context;
private List<News> newsList;
/**
* 构造方法的时候传入newsList
*
* @param context
* @param newsList 须要填入的news信息
*/
public NewsAdapter(Context context, List<News> newsList) {
this.context = context;
this.newsList = newsList;
}
@Override
public int getCount() {
return newsList.size();
}
@Override
public News getItem(int position) {
return newsList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/**
* 为news-item中的布局赋值
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) { //假设为空则又一次创建
convertView = LayoutInflater.from(context).inflate(R.layout.news_item, null);
}
// 获得news-item中的控件
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
TextView tvDesc = (TextView) convertView.findViewById(R.id.tvDesc);
TextView tvTime = (TextView) convertView.findViewById(R.id.tvTime);
ImageView ivPic = (ImageView) convertView.findViewById(R.id.ivPic);
News news = newsList.get(position);
tvTitle.setText(news.getTitle());
tvDesc.setText(news.getDesc());
tvTime.setText(news.getTime());
String pic_url = news.getPic_url();
HttpUtils.setPicBitmap(ivPic, pic_url);
return convertView;
}
}
详细的布局文件省略。看一下清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xuliugen.news"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.xuliugen.news.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="BrowseNewsActivity"></activity>
</application>
</manifest>
好啦!详细项目源码资源例如以下:
http://yunpan.cn/cZcInR3UUH5LV 訪问password 0a8e
项目演示效果:
知识点总结:数据库数据到json数据格式的转换、訪问json数据的方法及解析json的方法、适配器等。
到此结束。喜欢的请默默点赞!
版权声明:本文博主原创文章,博客,未经同意不得转载。