This article examples for you 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 PHP environment configuration, testing whether the MySQL statement can be queried, before have been detailed instructions.
2, here PHP backstage implementation of MySQL query function, and JSON data format to return a client
In PHP, create a mysql_connect.php file, implement the database connection, and set the character set format.
<?php
$con = mysql_connect ("localhost", "root", "123456");
Set the character set to UTF-8 to resolve 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);
? >
A new getnewsjson.php file is then used 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_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);
? >
The focus is on the design and development of the Android side
1. Design interface
Because you need to set the same format for each item in ListView, use the form of listview+adapter 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;
Definition set private list<news> 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 private Handler after getting msg Getnewshandler = new Handler () {public void Handlemessage (Android.os.Message msg) {STR
ing jsondata = (String) msg.obj;
System.out.println (Jsondata); try {jsonarray Jsonarray = new Jsonarray (jsondata); for (int i=0;i<jsonarray.length (); i++) {Jsonobject object = Jsonar
Ray.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");
System.out.println ("title=" +title);
Add a news type of object Newslist.add (new News (Title,desc,time,content_url,pic_url)); }//Notify update ADAPTer.notifydatasetchanged ();
catch (Jsonexception e) {//TODO auto-generated catch block E.printstacktrace ();}
} ;
} ;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Lvnews = (ListView) Findviewbyid (r.id.lvnews);
Initialize newslist = new arraylist<news> ();
adapter = new Newsadapter (this,newslist);
Lvnews.setadapter (adapter);
Lvnews.setonitemclicklistener (this);
Httputils.getnewsjson (Get_news_url,getnewshandler); @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds the items to the action Ba
R if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true; @Override public void Onitemclick (adapterview<?> arg0, View arg1, int position, long Arg3) {//TODO Auto-generat
ed Method Stub news = Newslist.get (position); Intent Intent = new Intent (thiS,browsenewsactivity.class);
Intent.putextra ("Content_url", News.getcontent_url ());
StartActivity (Intent);
}
}
Here you need a tool class Httputils and a custom newsadapter to implement the view display of 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 Android.widget.ImageView; The public class Httputils {//tool class is directly defined as a static method and can be/*url for internal classes, so it must be set to the final type////* Read completion needs to notify the main thread, which requires the use of handler*/public static VO ID Getnewsjson (Final String url,final Handler Handler) {//access network for a long time, open new Thread (Xin Runnable () {@Override public
void Run () {//TODO auto-generated method stub HttpURLConnection conn;
InputStream is;
try {conn = (httpurlconnection) new URL (URL). OpenConnection ();
Get Way to obtain Conn.setrequestmethod ("getting");
Get the input stream Is=conn.getinputstream ();
Read the data with a buffer in which to pass in a reader bufferedreader reader = new BufferedReader (new InputStreamReader (IS));
Read the data String line = ""; Not finished reading a line to splice, efficient StringBuilder result = new StringBuilder ();
while (line = Reader.readline ())!= null) {result.append (line);
msg = new Message ();
Msg.obj can be put in any object msg.obj = Result.tostring ();
Handler.sendmessage (msg);
catch (Exception e) {e.printstacktrace ();
}}). Start ();
The public static void Setpicbitmap (final imageview ivpic,final String pic_url) {new Thread (new Runnable () {@Override public void Run () {//TODO auto-generated Method stub try {httpurlconnection conn = (httpurlconnection) New URL (pic
_url). OpenConnection ();
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 block E.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;
The public class Newsadapter extends Baseadapter {//Declares the context object, and the GetView method behind it requires the private contexts;
Private list<news> newslist;
Public Newsadapter (context context, list<news> newslist) {this.context = context;
This.newslist = newslist;
@Override public int GetCount () {//TODO auto-generated a stub return newslist.size ();
@Override public Object getitem (int position) {//TODO auto-generated Method stub return Newslist.get (position);
@Override public long getitemid (int position) {//TODO auto-generated method stub return position; @Override Public View geTview (int position, View Convertview, ViewGroup arg2) {//TODO auto-generated Method Stub if (Convertview = null) {con
Vertview = 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 is used to set the display format for each item
<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" Match_parent "> <imageview Android
: id= "@+id/ivpic" android:layout_width= "42DP" android:layout_height= "42DP" android:src= "@drawable/ic_launcher" /> <textview android:id= "@+id/tvtitle" android:layout_width= "Wrap_content" android:layout_height=
"Wrap_content" android:layout_alignparenttop= "true" android:layout_torightof= "@+id/ivpic" android:text= "title"
Android:textsize= "18sp"/> <textview android:id= "@+id/tvdesc" android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content" android:layout_alignleft= "@+id/tvtitle" android:layout_below= "@+id/tvTitle" android:text= "desc" android:textsize= "18sp"/> <textview android:id= "@+id/tvtime" Android:layout_ Width= "Wrap_content" Android:layout_height= "Wrap_content" android:layout_alignparentright= "true" android:text= "Time" android:textsize= "10
SP "/> </RelativeLayout>
Note: You need to display a single picture in this item, so use the bitmap class. Because of the use of network transport, so need to use the concept of threading!!
Key understanding of the relationship between the handler message and the loop.
This is the entire content of this article, I hope to learn more about Android software programming help.