Android to build its own news platform (client + server) _android

Source: Internet
Author: User
Tags php language

Completely belong to their own news display platform, show to everyone, hope you like.

I. The construction of the news database

The script code is as follows: (mysql5.0 database used)

SET Sql_mode = "No_auto_value_on_zero";

SET time_zone = "+00:00"; --Database: ' Newsdemo '--table's structure ' news ' CREATE table IF not EXISTS ' news ' (' id ' int (a) not NULL auto_increment, ' title ' Text not NULL, ' desc ' text is 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; ----the data in the table is ' news '-INSERT into ' news ' (' id ', ' title ', ' desc ', ' time ', ' content_url ', ' Pic_url ') VALUES (1, ' Oracle unlock Blocked account ', ' We have a management account in the last step of installing Oracle, which can unlock the required account ', ' 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 National Weather Forecast query (aggregated data development) ', ' project demo effect as follows: Project source code download address: Access password 2EAC II, using aggregated data SDK: ', ' 2015-03-15 11:50:13 ', ' http ://blog.csdn.net/xlgen157387/article/details/44246119 ', ' http://img.blog.csdn.net/20150314095028546 ');
 

The results are as follows: (since this is the use of appserv, so the effect seen in phpMyAdmin 1)

converting data from a database to JSON data

Because the use of PHP language, so to install Appserv (this thing Baidu will know how to use, not research!) )

(1) Create a folder Newsdemo in the WWW directory under the Appserv directory, and create two PHP files in the folder as follows:

Connecting files to a database mysql_connect.php

<?php

  $con = mysql_connect ("localhost", "root", "your password!");
  Set the character set to 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);
? >

Getnewsjson.php specifically used to create JSON data

<?php
 /* Get JSON data
 * return value: 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 ']
          );

 Array into the JSON string
 echo Json_encode ($arr);

? >

Then visit the address:http://localhost:8080/NewsDemo/getNewsJSON.php

If the following "garbled" to show success!
Here to write a picture description

Also give everyone an online view of the JSON data URL:http://json.parser.online.fr/

To this database ready to complete, start to do the client!

Third, the implementation of the client

Mainactivity.java is as follows:

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;
  Here you need to modify your own server address: that is, the specific server address: Do not write your localhost or 127.0.0.1 here because this is to run on the phone!

  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); A piece of message shows the message newslist = new arraylist<news> (); Initialize adapter = new Newsadapter (this, newslist); is also initialized, and the Lvnews.setadapter (adapter) is updated after the Getnewsjson () method is executed later;

    Set constructor Lvnews.setonitemclicklistener (this); Here executes the request operation of the network Httputils.getnewsjson (Get_news_url, Getnewshandler); Incoming a Handler object}//Here is the time to access the network data, the returned Handler private Handler Getnewshandler = new Handler () {/** * this A method is a handler method used to accept the returned data */public void Handlemessage (Android.os.Message msg) {String Jsondata = (
        String) Msg.obj;
        System.out.println (Jsondata);
          try {//Below is parsing 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 ()//notification adapter data changes} catch (Exception e) {e.printstacktrace ();
    }
      };

  }; /** * Click event for each entry/@Override public void Onitemclick (adapterview<?> adapter, view view, int position, Lon 
    G Arg3) {//Get the object being clicked News = Newslist.get (position);
    Intent Intent = new Intent (this, browsenewsactivity.class); Intent.putextra ("Content_url", News.getcontent_url ());
  Gets its URL startactivity (intent) According to the object being clicked;

 }

}

The

Httputils.java is as follows:

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; /** * Access Network Tool class * * @author xuliugen * */public class Httputils {public static void Getnewsjson (final String ur
        L, final Handler Handler) {//To access the network, open a thread new threads (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 initialization cannot be null while (line = Reader.readline ())!= null) {result.append (line);
          ////Use handler to use message msg = new ();

          Msg.obj = Result.tostring ();
        Notify main thread Handler handler.sendmessage (msg);
        catch (Exception e) {e.printstacktrace ();
  }}). Start (); /** * Set Picture information * * In the adapter inside call * * @param ivpic The view component that needs to be set * @param pic_url image address/public STA
      TIC 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 ();

 }

}

bean– for saving JSON data News.java

Package Com.xuliugen.news.model;
  /** * * * @author Xuliugen * */public class News {private String title, corresponding to JSON data;
  Private String desc;
  Private String time;
  Private String Content_url;

  Private String Pic_url;
   /** * Full Parameter constructor * @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 is as follows:

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; /** * For display on the interface of item * * * @author Piaodangdehun * */public class Newsadapter extends Baseadapter {private Contex
  t context;

  Private list<news> newslist; /** * When constructing method newslist * * * @param context * @param newslist need to fill in news information/public newsadapter (context C
    Ontext, 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; 
    /** * Assign value to layout in News-item/@Override public View getview (int position, View Convertview, ViewGroup parent) { if (Convertview = null) {//If empty then recreate Convertview = Layoutinflater.from (context). Inflate (R.layout.news_item, n
    ULL);
    //Get the control in 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;

 }

}

The specific layout file is omitted, look at the manifest file:

<?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 Andr oid:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android.permission.INTERNET "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launche R "android:label=" @string/app_name "android:theme=" @style/apptheme "> <activity android:name=" com. Xuliugen.news.MainActivity "android:label=" @string/app_name "> <intent-filter> <action and
      Roid:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/>
  </intent-filter> </activity> <activity android:name= "Browsenewsactivity" ></activity>

 </application> </manifest>

All right! Specific project source code resources are as follows: Http://xiazai.jb51.net/201606/yuanma/Androidnews (jb51.net). rar

Summary of Knowledge Points: Conversion of database data to JSON data format, methods of accessing JSON data, methods of parsing JSON, adapters, etc.

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.