PHP background-based Android News browser client, PHP background Android News _php Tutorial

Source: Internet
Author: User

PHP background-based Android News browser client, PHP background Android News


The example of this article for everyone to share the Android news browsing client, based on the PHP background, for your reference, the specific content as follows

1, the use of Hbuilder for the PHP environment configuration, test whether you can query MySQL statements, have been described in detail before.

2, here PHP background implementation of MySQL query function, and in the JSON data format to return a client

Create a mysql_connect.php file here in PHP that implements the database connection and sets the character set format.

<?php$con = mysql_connect ("localhost", "root", "123456");//Setting the character set to UTF-8 can solve the Chinese garbled 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);? >

Then create a new getnewsjson.php file to convert the query results into a JSON string format. You just need to json_encode this method.

<?php/* get JSON Data * return value: Title desc time content_url pic_url*/   require ' mysql_connect.php '; $n = 0; $result = mysql_que Ry ("SELECT * FROM News") and while ($row = Mysql_fetch_array ($result)) {$arr [$n + +] = Array ("title" + + $row [' title '], "desc" = = $row [' desc '], "time" and "time" = $row [' Time '], "Content_url" and "$row [' Content_url ']," pic_url "+ $row [' Pic_url ']) ;} Array into JSON string echo json_encode ($arr);? >

The focus is on the development of Android-side design

1. Design interface

Because it is necessary to set the same format in each item in the ListView, the form of listview+adapter is used here

Add a ListView control to the main interface LinearLayout

2. The mainactivity procedure is as follows:

public class Mainactivity extends Activity implements onitemclicklistener{private ListView lvnews;  Private Newsadapter adapter; Define Collection Private List
 
  Newslist;  Gets the URL address of the JSON string public static final String get_news_url = "http://211.87.234.20/NewsDemo/getNewsJSON.php";  How to handle the private Handler Getnewshandler = new Handler () {public void Handlemessage (Android.os.Message msg) {String) after getting msg  Jsondata = (String) msg.obj;  System.out.println (Jsondata); try {jsonarray Jsonarray = new Jsonarray (jsondata); for (int i=0;i
  
   

A tool class Httputils and a custom newsadapter are required here to implement the view display for item.

The Httputils code is as follows:

Package com. Mr.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 The Android.widget.imageview;public class Httputils {//tool class is defined directly as a static method to be/*url for internal classes, so to set it to the final type *//* read completion requires the main thread to be notified. You need to use handler*/public static void Getnewsjson (final String url,final Handler Handler) {//access the network for a long time, open new thread  Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubhttpurlconnection conn; InputStream is; try {conn = (httpurlconnection) new URL (URL). OpenConnection ();//get method gets Conn.setrequestmethod ("get");//Get input stream is= Conn.getinputstream ();//Read data with buffer, inside to pass in a readerbufferedreader reader = new BufferedReader (new InputStreamReader (IS)) ;//One row reads the data string line = "";//do not read a line for stitching, efficient StringBuilder result = new StringBuilder (); while ((line = Reader.readline ())! = NULL) {Result.appenD (line);} Message msg = new Message ();//msg.obj can be placed in any object msg.obj = Result.tostring (); Handler.sendmessage (msg);} catch (Exception e) {e.printstacktrace ();}}}). Start ();} public static void Setpicbitmap (final ImageView ivpic,final String pic_url) {new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtry {HttpURLConnection conn = (httpurlconnection) new URL (Pic_url). Openconne Ction (); Conn.connect (); InputStream is = Conn.getinputstream (),//bitmap is the desired picture resource/* from the resource file to the picture */bitmap Bitmap = Bitmapfactory.decodestream (IS); Ivpic.setimagebitmap (bitmap); Is.close (); catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start ();}}

The Newsadapter code is as follows:

Package com. Mr.news.adapter;import java.util.list;import com. Mr.news.r;import com. Mr.news.model.news;import com. Mr.news.utils.httputils;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;public class Newsadapter extends Baseadapter {//Declaration context object, subsequent GetView method requires private context Context;private List
    
     Newslist;public Newsadapter (Context context, List
     
      
 newslist) {this.context = context; this.newslist = newslist;} @Overridepublic int GetCount () {//TODO auto-generated method Stubreturn newslist.size ();} @Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn newslist.get (position);} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup arg2) {//TODO auto-generated method stubif (convert View = = null) {Convertview = Layoutinflater.from (context). Inflate (r.layout.news_item,null);} 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;}}
     
    

News_item used to set the display format for each item

<?xml version= "1.0" encoding= "Utf-8"?>
    
      
       
       
       
       
     
    

Note: You need to display a single picture in this item, so use the bitmap class. Because of the use of network transmission, so need to use the concept of threading!!

The key to understanding the relationship between handler message and the three loops.

The above is the whole content of this article, I hope you learn Android software programming to help.

http://www.bkjia.com/PHPjc/1133098.html www.bkjia.com true http://www.bkjia.com/PHPjc/1133098.html techarticle based on the PHP background Android News browser client, PHP background Android News example for everyone to share the Android news browsing client, based on the PHP background, for your reference, specific content such as ...

  • 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.