


Android news browsing client based on PHP background, php background android news_PHP tutorial
Jul 12, 2016 am 08:50 AMAndroid news browsing client based on PHP background, php background android news
The example in this article shares with you the Android news browsing client, based on php background, for your reference, specific The content is as follows
1. Use HBuilder to configure the PHP environment and test whether the MySQL statement can be queried. This has been explained in detail before.
2. Here the php background implements the query function of mysql and returns a client in JSON data format
Create a mysql_connect.php file here in PHP to connect to the database and set the character set format.
<?php $con = mysql_connect("localhost","root","123456"); //設(shè)置字符集為UTF-8 可解決中文亂碼 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 JSON string format. Only the json_encode method is needed.
<?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); ?>
The focus is on the design and development of the Android side
1. Design interface
Since the same format needs to be set in each Item of the ListView, the ListView Adapter is used here
Add a ListView control in the main interface LinearLayout
2. Mainactivity program is as follows:
public class MainActivity extends Activity implements OnItemClickListener{ private ListView lvNews ; private NewsAdapter adapter ; //定義集合 private List<News> newsList ; //獲取json字符串的URL地址 public static final String GET_NEWS_URL = "http://211.87.234.20/NewsDemo/getNewsJSON.php"; //獲取msg之后如何處理 private Handler getNewsHandler = new Handler(){ public void handleMessage(android.os.Message msg){ String jsonData = (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.getString("pic_url") ; System.out.println("title="+title) ; //add一個(gè)News類型的Object newsList.add(new News(title,desc,time,content_url,pic_url)) ; } //通知更新 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) ; //初始化 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. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub News 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 needed here to realize the view display of the item.
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 { //工具類直接定義成靜態(tài)方法即可 /*url用于內(nèi)部類中,所以要將其設(shè)定為final類型*/ /*讀取完成需要通知主線程,需要使用handler*/ public static void getNewsJSON(final String url,final Handler handler){ //訪問網(wǎng)絡(luò),時(shí)間長(zhǎng),開啟新線程 new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub HttpURLConnection conn ; InputStream is ; try { conn = (HttpURLConnection) new URL(url).openConnection() ; //GET方式獲取 conn.setRequestMethod("GET") ; //得到輸入流 is=conn.getInputStream() ; //讀取數(shù)據(jù)用緩沖,里面要傳入一個(gè)reader BufferedReader reader = new BufferedReader(new InputStreamReader(is)); //一行一行讀取數(shù)據(jù) String line = ""; //沒讀完一行進(jìn)行拼接,高效 StringBuilder result = new StringBuilder(); while((line = reader.readLine()) != null){ result.append(line); } Message msg = new Message() ; //msg.obj可以放進(jìn)去任何對(duì)象 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(){ @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就是所需圖片資源 /*從資源文件中的到圖片*/ Bitmap bitmap = BitmapFactory.decodeStream(is) ; ivPic.setImageBitmap(bitmap) ; is.close() ; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start() ; } }
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 { //聲明上下文對(duì)象,后面的getView方法需要 private Context context; private List<News> newsList; public NewsAdapter(Context context, List<News> newsList){ this.context = context ; this.newsList = newsList ; } @Override public int getCount() { // TODO Auto-generated method 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){ 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: This item needs to display a single image, so the Bitmap class is used. Since network transmission is used, the concept of threads needs to be used! !
The key is to understand the relationship between handler message and loop.
The above is the entire content of this article. I hope it will be helpful to everyone in learning Android software programming.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.
