Android 基础知识

Android 主页 Android 概述 Android 下载安装和开发环境配置 Android Studio IDE Android 架构 Android 应用程序组件 Android Hello World 示例 Android 资源 Android 活动 Android 服务 Android 广播接收器 Android 内容提供者 Android 片段 Android Intents/Filters

Android 用户界面

Android UI 布局 Android UI 控件 Android 事件处理 Android 样式和主题 Android 自定义组件

Android 高级概念

Android 拖放 Android 通知 Android 基于位置的服务 Android 发送电子邮件 Android 发送短信 Android 拨打电话 Android 发布应用程序

Android 实用示例

Android 警报对话框 Android 动画 Android 音频捕捉 Android 音频管理器 Android 自动完成 Android 最佳实践 Android 蓝牙 Android 相机 Android 剪贴板 Android 自定义字体 Android 数据备份 Android 开发者工具 Android 模拟器 Android Facebook 集成 Android 手势 Android 谷歌地图 Android 图像效果 Android 图像切换 Android 内部存储 Android JetPlayer Android JSON 解析器 Android Linkedin 集成 Android 旋转加载器 Android 本地化 Android 登录应用 Android 媒体播放器 Android 多点触控 Android 导航 Android 网络连接 Android NFC 指南 Android PHP/MySQL Android 进度圈 Android 进度条 Android 推送通知 Android 渲染脚本 Android RSS 阅读器 Android 屏幕投射 Android SDK 管理器 Android 传感器 Android 会话管理 Android 共享首选项 Android SIP 协议 Android 拼写检查器 Android SQLite 数据库 Android 支持库 Android 测试 Android 文字转语音 Android TextureView Android Twitter 集成 Android UI 设计 Android UI 模式 Android UI 测试 Android WebView 布局 Android Wi-Fi Android Widgets Android XML 解析器

Android 其他

Android 面试问题 Android 有用的资源 Android 测验


Android - PHP/MYSQL

在本章中,我们将解释如何将 PHP 和 MYSQL 与您的 android 应用程序集成。 如果你有一个网络服务器,并且你想在你的 android 应用程序上访问它的数据,这非常有用。

MYSQL 用作网络服务器上的数据库,PHP 用于从数据库中获取数据。 我们的应用程序将使用必要的参数与 PHP 页面进行通信,PHP 将联系 MYSQL 数据库并获取结果并将结果返回给我们。


PHP - MYSQL

创建数据库

MYSQL 数据库可以使用这个简单的脚本轻松创建。 CREATE DATABASE 语句创建数据库。

<?php
   $con=mysqli_connect("example.com","username","password");
   $sql="CREATE DATABASE my_db";
   if (mysqli_query($con,$sql)) {
      echo "Database my_db created successfully";
   }
?>

创建表格

一旦创建了数据库,就该在数据库中创建一些表了。 CREATE TABLE 语句创建数据库。

<?php
   $con=mysqli_connect("example.com","username","password","my_db");
   $sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role CHAR(30))";
   if (mysqli_query($con,$sql)) {
      echo "Table have been created successfully";
   }
?>

在表格中插入数据

何时创建数据库和表。 现在是时候向表中插入一些数据了。 Insert Into 语句创建数据库。

<?php
   $con=mysqli_connect("example.com","username","password","my_db");
   $sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin', 'admin','adminstrator')";
   if (mysqli_query($con,$sql)) {
      echo "Values have been inserted successfully";
   }
?>

PHP - GET 和 POST 方法

一旦创建,PHP 还用于从 mysql 数据库中获取记录。 为了获取记录,必须将一些关于要获取的记录的信息传递给 PHP 页面。

第一种传递信息的方法是通过使用$_GET 命令的GET 方法。 变量在 url 中传递并获取记录。 它的语法如下 −

<?php
   $con=mysqli_connect("example.com","username","password","database name");

   if (mysqli_connect_errno($con)) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }

   $username = $_GET['username'];
   $password = $_GET['password'];
   $result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' 
      and Password='$password'");
   $row = mysqli_fetch_array($result);
   $data = $row[0];

   if($data){
      echo $data;
   }
   mysqli_close($con);
?>

第二种方法是使用 POST 方法。 上述脚本的唯一变化是将 $_GET 替换为 $_POST。 在 Post 方法中,变量不通过 URL 传递。


Android - 连接 MYSQL

通过 Get 方法连接

通过 PHP 页面连接 MYSQL 有两种方式。 第一个称为Get 方法。 我们将使用 HttpGet 和 HttpClient 类进行连接。 它们的语法如下 −

URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));

之后,您需要调用 HttpClient 类的 execute 方法并在 HttpResponse 对象中接收它。 之后,您需要打开流来接收数据。

HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));

通过 Post 方法连接

在 Post 方法中,将使用 URLEncoder,URLConnection 类。 urlencoder 将对传递变量的信息进行编码。 它的语法如下−

URL url = new URL(link);
String data  = URLEncoder.encode("username", "UTF-8") 
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") 
+ "=" + URLEncoder.encode(password, "UTF-8");
URLConnection conn = url.openConnection(); 

您需要做的最后一件事是将此数据写入链接。 写入后,需要打开流来接收响应的数据。

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
wr.write( data ); 
BufferedReader reader = new BufferedReader(new 
InputStreamReader(conn.getInputStream()));			

示例

下面的示例是通过 PHP 页面将您的 android 应用程序与 MYSQL 数据库连接的完整示例。 它创建了一个基本应用程序,允许您使用 GET 和 POST 方法登录。

PHP - MYSQL 部分

在此示例中,已在 000webhost.com 创建了一个名为 temp 的数据库。 在该数据库中,已创建一个名为 table1 的表。 该表包含三个字段 (Username, Password, Role)。 该表只有一条记录,即 ("admin","admin","administrator")。

下面给出了 php 页面,它通过 post 方法接受参数。

<?php
   $con=mysqli_connect("mysql10.000webhost.com","username","password","db_name");

   if (mysqli_connect_errno($con)) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
	
   $username = $_POST['username'];
   $password = $_POST['password'];
   $result = mysqli_query($con,"SELECT Role FROM table1 where 
   Username='$username' and Password='$password'");
   $row = mysqli_fetch_array($result);
   $data = $row[0];

   if($data){
      echo $data;
   }
	
   mysqli_close($con);
?>

Android 部分

要试验这个例子,你需要在连接了 wifi 互联网的实际设备上运行它。

步骤 描述
1 您将使用 Android Studio IDE 创建一个 Android 应用程序,并将其命名为 PHPMYSQL,位于 com.example.phpmysql 包下。
2 修改 src/MainActivity.java 文件添加活动代码。
3 创建 src/SigninActivity.java 文件以添加 PHP MYSQL 代码。
4 修改布局 XML 文件 res/layout/activity_main.xml 如果需要,添加任何 GUI 组件。
5 修改 res/values/string.xml 文件并添加必要的字符串组件。
6 修改 AndroidManifest.xml 以添加必要的权限。
7 运行应用程序并选择一个正在运行的 android 设备并在其上安装应用程序并验证结果。

这是src/com.example.phpmysql/MainActivity.java的内容。

package com.example.phpmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

   private EditText usernameField,passwordField;
   private TextView status,role,method;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      usernameField = (EditText)findViewById(R.id.editText1);
      passwordField = (EditText)findViewById(R.id.editText2);

      status = (TextView)findViewById(R.id.textView6);
      role = (TextView)findViewById(R.id.textView7);
      method = (TextView)findViewById(R.id.textView9);
   }

   public void login(View view){
      String username = usernameField.getText().toString();
      String password = passwordField.getText().toString();
      method.setText("Get Method");
      new SigninActivity(this,status,role,0).execute(username,password);

   }

   public void loginPost(View view){
      String username = usernameField.getText().toString();
      String password = passwordField.getText().toString();
      method.setText("Post Method");
      new SigninActivity(this,status,role,1).execute(username,password);
   }
}

这是src/com.example.phpmysql/SigninActivity.java的内容。

package com.example.phpmysql;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

public class SigninActivity  extends AsyncTask{
   private TextView statusField,roleField;
   private Context context;
   private int byGetOrPost = 0;

   //flag 0 means get and 1 means post.(By default it is get.)
   public SigninActivity(Context context,TextView statusField,TextView roleField,int flag) {
      this.context = context;
      this.statusField = statusField;
      this.roleField = roleField;
      byGetOrPost = flag;
   }

   protected void onPreExecute(){
   }

   @Override
   protected String doInBackground(String... arg0) {
      if(byGetOrPost == 0){ //means by Get Method

         try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];
            String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;

            URL url = new URL(link);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            HttpResponse response = client.execute(request);
            BufferedReader in = new BufferedReader(new 
               InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line="";

            while ((line = in.readLine()) != null) {
               sb.append(line);
               break;
            }
				
            in.close();
            return sb.toString();
         } catch(Exception e){
            return new String("Exception: " + e.getMessage());
         }
      } else{
         try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];

            String link="http://myphpmysqlweb.hostei.com/loginpost.php";
            String data  = URLEncoder.encode("username", "UTF-8") + "=" +
               URLEncoder.encode(username, "UTF-8");
            data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + 
               URLEncoder.encode(password, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();

            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write( data );
            wr.flush();

            BufferedReader reader = new BufferedReader(new
               InputStreamReader(conn.getInputStream()));

            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null) {
               sb.append(line);
               break;
            }
				
            return sb.toString();
         } catch(Exception e){
            return new String("Exception: " + e.getMessage());
         }
      }
   }

   @Override
   protected void onPostExecute(String result){
      this.statusField.setText("Login Successful");
      this.roleField.setText(result);
   }
}

将以下内容添加到 build.gradle 并重建整个项目。

android {
   useLibrary 'org.apache.http.legacy'
}

这是activity_main.xml 的内容。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <EditText
      android:id="@+id/editText2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignRight="@+id/editText1"
      android:layout_below="@+id/editText1"
      android:layout_marginTop="25dp"
      android:ems="10"
      android:inputType="textPassword" >
   </EditText>

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentRight="true"
      android:layout_alignParentTop="true"
      android:layout_marginTop="44dp"
      android:ems="10" >

   <requestFocus android:layout_width="wrap_content" />

   </EditText>

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/editText1"
      android:layout_alignParentLeft="true"
      android:text="@string/Username" />

   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:text="@string/App"
      android:textAppearance="?android:attr/textAppearanceLarge" />

   <TextView
      android:id="@+id/textView7"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/textView5"
      android:layout_alignLeft="@+id/textView6"
      android:text="@string/Role"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:textSize="10sp" />

   <TextView
      android:id="@+id/textView5"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/textView6"
      android:layout_marginTop="27dp"
      android:layout_toLeftOf="@+id/editText1"
      android:text="@string/LoginRole" />
   <TextView
      android:id="@+id/textView8"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/textView6"
      android:layout_alignLeft="@+id/textView5"
      android:layout_marginBottom="27dp"
      android:text="@string/method" />

   <TextView
      android:id="@+id/textView4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView8"
      android:layout_below="@+id/button1"
      android:layout_marginTop="86dp"
      android:text="@string/LoginStatus" />

   <TextView
      android:id="@+id/textView6"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/textView4"
      android:layout_centerHorizontal="true"
      android:text="@string/Status"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:textSize="10sp" />

   <TextView
      android:id="@+id/textView9"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/textView8"
      android:layout_alignLeft="@+id/textView6"
      android:text="@string/Choose"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:textSize="10sp" />

   <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerVertical="true"
      android:layout_toRightOf="@+id/textView6"
      android:onClick="loginPost"
      android:text="@string/LoginPost" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/button2"
      android:layout_alignBottom="@+id/button2"
      android:layout_alignLeft="@+id/textView2"
      android:onClick="login"
      android:text="@string/LoginGet" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/editText2"
      android:layout_alignBottom="@+id/editText2"
      android:layout_alignParentLeft="true"
      android:text="@string/Password" />

</RelativeLayout>

这是Strings.xml的内容。

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">PHPMYSQL</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="Username">Username</string>
   <string name="Password">Password</string>
   <string name="LoginGet">Login - Get</string>
   <string name="LoginPost">Login - Post</string>
   <string name="App">Login Application</string>
   <string name="LoginStatus">Login Status</string>
   <string name="LoginRole">Login Role</string>
   <string name="Status">Not login</string>
   <string name="Role">Not assigned</string>
   <string name="method">Login Method</string>
   <string name="Choose">Choose Method</string>
	
</resources>

这是AndroidManifest.xml的内容。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.phpmysql" >

      <uses-permission android:name="android.permission.INTERNET"/>
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.phpmysql.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

让我们尝试运行您的 PHPMYSQL 应用程序。 我假设您已将实际的 Android 移动设备与您的计算机连接起来。要从 Android Studio 运行应用程序,请打开项目的一个活动文件,然后单击工具栏中的运行 Eclipse 运行图标 图标。在启动您的应用程序之前,Android Studio 将显示以下窗口以选择您要运行 Android 应用程序的选项。

Anroid PHP/MySQL 教程

选择您的移动设备作为选项,然后检查您的移动设备,它将显示以下屏幕 −

Anroid PHP/MySQL 教程

现在只需输入您的用户名和密码。 在我的情况下,我输入 admin 作为用户名和密码。 如图所示 −

Anroid PHP/MySQL 教程

现在按下获取按钮并等待几秒钟,响应将被下载并显示给您。 在这种情况下,响应是在admin作为用户名和密码的情况下获取的角色。如下图所示 −

Anroid PHP/MySQL 教程

现在再次按下 POST 按钮,将出现相同的结果。 如下图所示 −

Anroid PHP/MySQL 教程