Android news browser client based on PHP background, php background android news

Source: Internet
Author: User

Android news browser client based on PHP background, php background android news

This example shares the Android news browser client, which is based on the php background for your reference. The details are as follows:

1. Use HBuilder to configure the PHP environment and test whether MySQL statements can be queried.

2. mysql query is implemented in the php background, and clients are returned in JSON data format.

Create a mysql_connect.php file in PHP to connect to the database and set the character set format.

<? Php $ con = mysql_connect ("localhost", "root", "123456"); // SET the character SET to UTF-8 to solve 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);?>

Create a new getNewsJSON. php file to convert the query result to the JSON string format. You only need the json_encode 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']);} // convert an array to a JSON string echo json_encode ($ arr);?>

Focus on Android Design and Development

1. Design Interface

Because the same format needs to be set in each Item of ListView, The ListView + Adapter format is used here.

Add a ListView control to LinearLayout on the main interface.

2. The Mainactivity program is as follows:

Public class MainActivity extends Activity implements OnItemClickListener {private ListView lvNews; private NewsAdapter adapter; // defines the set private List <News> newsList; // obtain the URL of the json String public static final String GET_NEWS_URL = "http: // 211.87.234.20/NewsDemo/getNewsJSON. php "; // how to handle private Handler getNewsHandler = new Handler () {public void handleMessage (android. OS. message msg) {String json Data = (String) msg. obj; System. out. println (jsonData); try {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. getSt Ring ("pic_url"); System. out. println ("title =" + title); // add a News-type ObjectnewsList. add (new News (title, desc, time, content_url, pic_url);} // notify the updated adapter. notifyDataSetChanged ();} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}};}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_mai N); 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 items to the action bar if it is present. getMenuInfl Ater (). inflate (R. menu. main, menu); return true ;}@ Overridepublic void onItemClick (AdapterView <?> Arg0, View arg1, int position, long arg3) {// TODO Auto-generated method stubNews news = newsList. get (position); Intent intent = new Intent (this, BrowseNewsActivity. class); intent. putExtra ("content_url", news. getContent_url (); startActivity (intent );}}

A tool class HttpUtils and a custom NewsAdapter are required to display the item view.

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; public class HttpUtils {// The tool class can be directly defined as a static method./* the url is used in the internal class. Therefore, you need to set it to the final type * // * to complete reading. To know the main thread, use handler */public static void getNewsJSON (final String url, final Handler handler) {// to access the network for a long time, enable new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubHttpURLConnection conn; InputStream is; try {conn = (HttpURLConnection) new URL (url ). openConnection (); // GET method to obtain conn. setRequestMethod ("GET"); // obtain the input stream is = conn. getInputStream (); // buffer used to read data. A readerBufferedR is required. Eader reader = new BufferedReader (new InputStreamReader (is); // a row reads data in a row String line = ""; // The row is not read and spliced, efficient StringBuilder result = new StringBuilder (); while (line = reader. readLine ())! = Null) {result. append (line);} Message msg = new Message (); // msg. obj can be included 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 ). openConnection (); conn. connect (); InputStream is = conn. getInputStream (); // bitmap is the required image resource/* from the resource file to the image */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 {// declare the Context object. The following getView method requires private context Context; private List <News> newsList; public NewsAdapter (context Context, list <News> 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 (convertView = 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 is used to set the display format of 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="10sp"    /></RelativeLayout>

Note: The Bitmap class is used to display a single image in this item. Because network transmission is used, the thread concept is required !!

The key is to understand the relationship between handler message and loop.

The above is all the content of this article, hoping to help you learn Android software programming.

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.