Android打造屬于自己的新聞平臺(tái)(客戶端+服務(wù)器)
完全屬于自己的新聞?wù)故酒脚_(tái),展示給大家,希望大家喜歡。
一、新聞的數(shù)據(jù)庫(kù)的構(gòu)建
腳本代碼如下:(使用的mysql5.0 數(shù)據(jù)庫(kù))
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- Database: `newsdemo` -- 表的結(jié)構(gòu) `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 ; -- -- 轉(zhuǎn)存表中的數(shù)據(jù) `news` -- INSERT INTO `news` (`id`, `title`, `desc`, `time`, `content_url`, `pic_url`) VALUES (1, 'Oracle解鎖封鎖的賬號(hào)', '我們?cè)诎惭bOracle的時(shí)候最后一步有一個(gè)管理賬戶的,里邊可以解鎖所所需的賬戶', '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程序之全國(guó)天氣預(yù)報(bào)查詢(聚合數(shù)據(jù)開(kāi)發(fā))', '項(xiàng)目演示效果如下: 項(xiàng)目源代碼下載地址: 訪問(wèn)密碼 2eac二、使用 聚合數(shù)據(jù)SDK:', '2015-03-15 11:50:13', 'http://blog.csdn.net/xlgen157387/article/details/44246119', 'http://img.blog.csdn.net/20150314095028546');
執(zhí)行結(jié)果如下:(由于這是使用的appserv,所以在phpMyAdmin中看到的這種效果1)

二、將數(shù)據(jù)庫(kù)中的數(shù)據(jù)轉(zhuǎn)化為json數(shù)據(jù)
由于使用的是php語(yǔ)言,所以要安裝appserv(這個(gè)東西百度一下就知道怎么使用,不在研究!)
(1)在appserv目錄下的www目錄下創(chuàng)建一個(gè)文件夾NewsDemo,文件夾中創(chuàng)建兩個(gè)php文件如下:
連接數(shù)據(jù)庫(kù)的文件mysql_connect.php
<?php
$con = mysql_connect("localhost", "root", "your password!");
//設(shè)置字符集為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);
?>
具體用于創(chuàng)建json數(shù)據(jù)的getNewsJSON.php
<?php
/*
* 獲得JSON數(shù)據(jù)
* 返回值: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']
);
}
//數(shù)組轉(zhuǎn)換為JSON字符串
echo json_encode($arr);
?>
然后訪問(wèn)地址:http://localhost:8080/NewsDemo/getNewsJSON.php
如果出現(xiàn)以下“亂碼”表示成功!
這里寫(xiě)圖片描述
另外給大家一個(gè)在線查看json數(shù)據(jù)的網(wǎng)址:http://json.parser.online.fr/
到此數(shù)據(jù)庫(kù)的準(zhǔn)備完成,開(kāi)始做客戶端!
三、客戶端的實(shí)現(xiàn)
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;
//此處需要修改為自己的服務(wù)器地址:也就是具體的服務(wù)器地址:這里不要寫(xiě)你的localhost或者127.0.0.1因?yàn)檫@是要在手機(jī)上運(yùn)行的!
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); //也是初始化,會(huì)在后期執(zhí)行g(shù)etNewsJSON()方法之后更新
lvNews.setAdapter(adapter); //設(shè)置構(gòu)造器
lvNews.setOnItemClickListener(this);
//這里執(zhí)行了網(wǎng)絡(luò)的的請(qǐng)求操作
HttpUtils.getNewsJSON(GET_NEWS_URL, getNewsHandler); //傳入的一個(gè)handler對(duì)象
}
// 這里是訪問(wèn)網(wǎng)絡(luò)數(shù)據(jù)的時(shí)候,返回的handler
private Handler getNewsHandler = new Handler(){
/**
* 這個(gè)方法是Handler自帶的方法,用于接受返回的數(shù)據(jù)
*/
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();//通知適配器數(shù)據(jù)發(fā)生變化
} catch (Exception e) {
e.printStackTrace();
}
};
};
/**
* 每一個(gè)條目的點(diǎn)擊事件
*/
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
//獲取被點(diǎn)擊的對(duì)象
News news = newsList.get(position);
Intent intent = new Intent(this, BrowseNewsActivity.class);
intent.putExtra("content_url", news.getContent_url()); //根據(jù)被點(diǎn)擊的對(duì)象,獲取其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;
/**
* 訪問(wèn)網(wǎng)絡(luò)的工具類
*
* @author xuliugen
*
*/
public class HttpUtils {
public static void getNewsJSON(final String url, final Handler handler) {
//要訪問(wèn)網(wǎng)絡(luò),開(kāi)啟一個(gè)線程
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();
}
/**
* 設(shè)置圖片的信息
*
* 在適配器里邊調(diào)用
*
* @param ivPic 需要設(shè)置的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數(shù)據(jù)的bean–》News.java
package com.xuliugen.news.model;
/**
* 與json數(shù)據(jù)相對(duì)應(yīng)的bean
*
* @author xuliugen
*
*/
public class News {
private String title;
private String desc;
private String time;
private String content_url;
private String pic_url;
/**
* 全參的構(gòu)造函數(shù)
*
* @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;
/**
* 構(gòu)造方法的時(shí)候傳入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) { //如果為空則重新創(chuàng)建
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>
好啦!具體項(xiàng)目源代碼資源如下: http://xiazai.jb51.net/201606/yuanma/Androidnews(jb51.net).rar
知識(shí)點(diǎn)總結(jié):數(shù)據(jù)庫(kù)數(shù)據(jù)到j(luò)son數(shù)據(jù)格式的轉(zhuǎn)換、訪問(wèn)json數(shù)據(jù)的方法及解析json的方法、適配器等。
相關(guān)文章
Android進(jìn)階NestedScroll嵌套滑動(dòng)機(jī)制實(shí)現(xiàn)吸頂效果詳解
這篇文章主要為大家介紹了Android進(jìn)階NestedScroll嵌套滑動(dòng)機(jī)制實(shí)現(xiàn)吸頂效果詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Flutter中嵌入Android 原生TextView實(shí)例教程
這篇文章主要給大家介紹了關(guān)于Flutter中嵌入Android 原生TextView的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Android如何實(shí)現(xiàn)動(dòng)態(tài)滾動(dòng)波形圖(心電圖)功能
這篇文章主要介紹了Android如何實(shí)現(xiàn)動(dòng)態(tài)滾動(dòng)波形圖(心電圖)功能,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03
Android實(shí)現(xiàn)圖片區(qū)域裁剪功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)圖片區(qū)域裁剪功能,調(diào)用相冊(cè)、拍照實(shí)現(xiàn)縮放、切割圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
淺談Android性能優(yōu)化之內(nèi)存優(yōu)化
Android的內(nèi)存優(yōu)化是性能優(yōu)化中很重要的一部分,本文將詳細(xì)介紹Android性能優(yōu)化之內(nèi)存優(yōu)化。2021-06-06
Android OpenGL ES實(shí)現(xiàn)簡(jiǎn)單綠幕摳圖
這篇文章主要為大家介紹了Android OpenGL ES實(shí)現(xiàn)簡(jiǎn)單綠幕摳圖示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Kotlin超簡(jiǎn)單實(shí)現(xiàn)StepView的方法
這篇文章主要介紹了Kotlin超簡(jiǎn)單實(shí)現(xiàn)StepView的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
Android實(shí)現(xiàn)圖片輪播效果的兩種方法
android圖片輪播效果非常漂亮,在程序開(kāi)發(fā)中也經(jīng)常用到,本文給大家分享android實(shí)現(xiàn)圖片輪播效果的幾種方法,對(duì)android實(shí)現(xiàn)圖片輪播相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2015-12-12
淺談android性能優(yōu)化之啟動(dòng)過(guò)程(冷啟動(dòng)和熱啟動(dòng))
本篇文章主要介紹了淺談android性能優(yōu)化之啟動(dòng)過(guò)程(冷啟動(dòng)和熱啟動(dòng)) ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-08-08

