2023年9月21日 星期四

Android Studio - JSON 資料交換格式(一百一十四)

Android Studio - JSON 資料交換格式(一百一十四):

JSON(JavaScript Object Notation)是由美國程式設計師設計和構想出的資料交換格式,擁有易讀、易寫的特點,並且機器解析和生成容易。是依據 JavaScript 物件語法的資料格式,屬於 JavaScript 的子集,也採用了 C 語言家族的習慣用法。

- JSON 資料交換格式
JSON 格式主要包含兩種數據結構:對象(Object)和數組(Array):
  • 對象(Object):對象是由零個或多個鍵值對(key-value pairs)組成的無序集合,鍵值對之間用逗號分隔,用大括號 {} 包裹。鍵是字符串,值可以是字符串、數字、布爾值、null、對象或數組。
  • 數組(Array):數組是由零個或多個值組成的有序列表,值之間用逗號分隔,用方括號 [] 包裹。值可以是字符串、數字、布爾值、null、對象或數組。

JSON 的格式:

{ 

  "name": "a",

  "email":"a@a.com,

  "password": "0000"

}


JSON 的格式:

{ 

  "name": "a",

  "email":"a@a.com,

  "password": "0000",

  "contents" [

    {

      "age": 28,

      "address": "Taiwan,

    }

  ],

  "member": true

}


JSON 是個以純文字為基底去儲存和傳送簡單結構資料,可以透過特定的格式去儲存任何資料(字串、數字、陣列、物件),也可以透過物件或陣列來傳送較複雜的資料。一旦建立了您的 JSON 資料,就可以非常簡單的跟其他程式溝通或交換資料,因為 JSON 就只是個純文字格式。

PHP JSON 函數:

Plugin version

Required Gradle version

json_encode

對變數進行 JSON 編碼

json_decode

JSON 格式的字串進行解碼,轉換為 PHP 變數

json_last_error

返回最後發生的錯誤


2023年 9月 21日(Wed)天氣報告
氣溫:50.0°F / 10.0°C @ 07:00
風速:每小時 5公里
降雨機會:2%
相對濕度:百分之 86%
天氣:多雲時陰

2023年9月20日 星期三

Android Studio - Android Java Login PHP 登入程式(一百一十三)

Android Studio - Android Java Login PHP 登入程式(一百一十三):

完成了 Android Java 的登入程式,便需要在 NAS 上的 PHP Server 編寫程式,PHP 程式主要是接收從 Android 傳送(POST)過來的資料,資料是用 JSON 格式,這 2個資料變數是 email ($_POST['email'])和 password($_POST['password']),並透過 PHP 程式連接 MySQL 資料庫,用 MySQL 連接資料庫的查詢指令,將判斷 email 帳號與密碼是否正確,然後將結果用 JSON 格式回傳到 Android。

Android PHP MySQL 連接
PHP Provided Information:
Linux 系統:Debian 2.6.12.6-arm1 版本
Apache 系統:Apache 2.2.3 版本
PHP 系統:PHP 5.2.0-8 版本
MySQL 系統:MySQL 5.0.32 版本
JSON 系統:JSON 1.2.1 版本

Login.php PHP 登入程式:

<?php

 

if ($_SERVER['REQUEST_METHOD']=='POST') {

 

    $email = $_POST['email'];

    $pass = $_POST['password'];

    require_once 'connect.php';

 

    $sql = "SELECT * FROM users WHERE email='$email' ";

    $response = mysqli_query($conn, $sql);

   

    $result = array();

    $result['login'] = array();

   

    if ( mysqli_num_rows($response) === 1 ) {

        $row = mysqli_fetch_assoc($response);

       

        if ( $pass== $row['password'] ) {

          

            $index['Name'] = $row['Name'];

            $index['email'] = $row['email'];

            $index['id'] = $row['id'];

            $index['pass'] = $row['password'];

            $index['no'] = $row['no'];

            $index['add'] = $row['address'];

 

            array_push($result['login'], $index);

 

            $result['success'] = "1";

            $result['message'] = "success";

            echo json_encode($result);

           

            mysqli_close($conn);

 

        } else {

            $result['success'] = "0";

            $result['message'] = "Worng Password";

            echo json_encode($result);

 

            mysqli_close($conn);

        }

 

    }else{

        $result['success'] = "0";

        $result['message'] = "error";

        echo json_encode($result);

        mysqli_close($conn);

    }

}

?>


user.sql 資料庫:

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (

  `id` int(255) NOT NULL auto_increment,

  `Name` varchar(20) NOT NULL,

  `email` varchar(30) NOT NULL,

  `password` varchar(20) NOT NULL,

  `no` bigint(20) NOT NULL,

  `address` varchar(100) NOT NULL,

  PRIMARY KEY  (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

INSERT INTO `users` (`id`, `Name`, `email`, `password`, `no`, `address`) VALUES

(1,'a','a@a.com','0000',0,'A123 CA'),

(2,'b','b@a.com','0000',0,'A222 CA'),

(3,'c','c@a.com','0000',0,'A333 CA'),

(4, 'd', 'd@a.com', '0000', '0', 'A443 CA'),

(5, 'e', 'e@a.com', '0000', '0', 'A555 CA');


2023年 9月 20日(Wed)天氣報告
氣溫:52.0°F / 11.0°C @ 07:00
風速:每小時 3公里
降雨機會:15%
相對濕度:百分之 94%
天氣:多雲

2023年9月19日 星期二

Android Studio - Android Java Login PHP 登入程式(一百一十二)

Android Studio - Android Java Login PHP 登入程式(一百一十二):

首先是編寫 Android Login 程式,Android 程式負責登入功能,將輸入使用者的帳號、密碼傳送給後端 PHP 處理,並回傳登入是否成功的訊息。

Android Java Login PHP 登入程式
  • 操作系統:Windows 7 64-bit 版本
  • 開發環境:Android Studio 4.0.1 版本
  • 測試手機:Samsung Galaxy M33 5G
  • 測試手機系統版本:Android 12(Snow Cone / 2021)Android Studio 12 版本(Snow Cone)Build.VERSION_CODES.S / SDK 31
  • 原程式:C:\Development\Development_Android\Android_Project\DIY-Android-107-08b LoginBugworkshop Bugworkshop 20230914
  • 程式:C:\Development\Development_Android\Android_Project\ DIY-Android-107-08b LoginBugworkshop Bugworkshop 20230914

Android Java Login PHP 登入程式編程步驟:
  • 輸入個人電郵和密碼,按 Login 鍵
  • 程式會將電郵和密碼轉成 JSON,然後 POST 到 NAS PHP 的 URL
  • PHP Server 接收電郵和密碼,便會連接 MySQL 並查詢電郵和密碼是否正確,將結果傳回手機
  • 手機接收結果,並顯示解讀

AndroidManifest.xml:

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="bugworkshop.loginSystem">

 

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.INTERNET" />

 

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme"

        android:usesCleartextTraffic="true">

 

        <activity android:name=".Login>

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>


activity_login.xml:

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

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:textAlignment="center">

 

    <TextView

        android:id="@+id/textUser"

        android:layout_width="80dp"

        android:layout_height="57dp"

        android:layout_marginStart="20dp"

        android:layout_marginTop="48dp"

        android:text="User :"

        android:textSize="30sp"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

 

    <EditText

        android:id="@+id/email"

        android:layout_width="234dp"

        android:layout_height="57dp"

        android:layout_marginStart="10dp"

        android:layout_marginTop="48dp"

        android:inputType="text"

        android:textSize="30sp"

        app:layout_constraintStart_toEndOf="@+id/textUser"

        app:layout_constraintTop_toTopOf="parent" />

 

    <TextView

        android:id="@+id/textPassword"

        android:layout_width="150dp"

        android:layout_height="50dp"

        android:layout_marginStart="20dp"

        android:layout_marginTop="24dp"

        android:text="Password :"

        android:textSize="30sp"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toBottomOf="@+id/textUser" />

 

    <EditText

        android:id="@+id/password"

        android:layout_width="176dp"

        android:layout_height="51dp"

        android:layout_marginStart="10dp"

        android:layout_marginTop="24dp"

        android:inputType="text"

        android:password="true"

        android:textSize="30sp"

        app:layout_constraintStart_toEndOf="@+id/textPassword"

        app:layout_constraintTop_toBottomOf="@+id/email" />

 

    <Button

        android:id="@+id/signin"

        android:layout_width="206dp"

        android:layout_height="60dp"

        android:layout_marginTop="32dp"

        android:text="LOGIN"

        android:textSize="30sp"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="0.497"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toBottomOf="@+id/password" />

 

    <TextView

        android:id="@+id/hello"

        android:layout_width="299dp"

        android:layout_height="53dp"

        android:layout_marginTop="36dp"

        android:text="Hello"

        android:textAlignment="center"

        android:textSize="24sp"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="0.504"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toBottomOf="@+id/signin" />

 

</androidx.constraintlayout.widget.ConstraintLayout>


Login.java:

package bugworkshop.loginSystem;

 

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

 

import com.android.volley.AuthFailureError;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.StringRequest;

import com.android.volley.toolbox.Volley;

 

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

 

import java.util.HashMap;

import java.util.Map;

 

public class Login extends AppCompatActivity {

 

    EditText password, email;

    TextView hello;

    Button signin;

    TextView alert;

 

    String pass,mail;

    public RequestQueue mQueue;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

 

        password = findViewById(R.id.password);

        email = findViewById(R.id.email);

        hello = findViewById(R.id.hello);

        signin = findViewById(R.id.signin);

 

        signin.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                checklogin();

            }

        });

    }

 

    private void checklogin() {

 

        mail = email.getText().toString().trim();

        pass  = password.getText().toString().trim();

 

        String url = "http://192.168.0.122/~test/efarm//login.php";

 

        StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {

            @Override

            public void onResponse(String response) {

                try {

                    JSONObject jsonobject = new JSONObject(response);

                    String success = jsonobject.getString("success");

                    JSONArray jsonarray = jsonobject.getJSONArray("login");

                    JSONObject jo = jsonarray.getJSONObject(0);

 

                    if(success.equals("1")) {

                        hello.setText(jo.getString("Name") + " Login OK");

                    }

                    else{

                        hello.setText("Wrong Username or Password");

                    }

                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

        }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {

                error.printStackTrace();

                hello.setText("Error Logging in check Internet Connection");

                Toast.makeText(getApplicationContext(), "Error Logging in check Internet Connection", Toast.LENGTH_LONG).show();

            }

        }){

            @Override

            protected Map<String,String> getParams(){

                HashMap<String,String> param = new HashMap<String,String>();

                param.put("email",mail);

                param.put("password",pass);

                return param;

            }

 

            @Override

            public Map<String, String> getHeaders() throws AuthFailureError {

                Map<String,String> params = new HashMap<String, String>();

                params.put("Content-Type","application/x-www-form-urlencoded");

                return params;

            }

        };

 

        mQueue = Volley.newRequestQueue(Login.this);

        mQueue.add(sr);

    }

}


2023年 9月 19日(Tue)天氣報告
氣溫:54.0°F / 12.0°C @ 07:00
風速:每小時 2公里
降雨機會:2%
相對濕度:百分之 68%
天氣:多雲時陰