【问题标题】:Recent ways to connect Android Studio with mySQL?将 Android Studio 与 mySQL 连接的最新方法?
【发布时间】:2020-04-07 22:47:48
【问题描述】:

对于我的年终项目,我正在尝试使用 Android Studio 创建一个应用。我希望这个应用程序具有登录和注册功能,但我已经为此苦苦挣扎了好几个星期了。我不知道如何将它连接到我的在线 mySQL 数据库(这对我来说更容易,因为我不想进入 mySQLite,因为我没有太多时间了)到我的应用程序和能够向这个数据库发送一些东西。比如注册时不知道如何将信息发送到数据库,登录时不知道如何获取这些信息。

到目前为止,我已经在线制作了 mySQL 数据库,并且我已经编写了一些标准的 PHP 代码来将给定的信息(post 方法)添加到数据库中。我尝试了多种方法将 Android Studio 中的信息发送到该数据库,但似乎没有任何效果。我已经学习了以下教程:

https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

https://www.youtube.com/watch?v=Wwh66xFRLwU

https://www.youtube.com/watch?v=QxffHgiJ64M&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka

还有一些我再也找不到了。我还搜索了 StackOverflow,但似乎没有任何效果。现在我刚刚回到起点,我只有编辑文本框,我已经转换为字符串,我不知道如何将它们发送到我的 register.php 文件(我的互联网访问在清单中。 xml)。我查找的所有内容似乎都已使用多年且不起作用,我现在真的很绝望。

【问题讨论】:

  • 如果您的 PHP 设置为 Web 服务,请使用 Retrofit 与其对话。
  • 教程已经过时了。
  • 我会使用 ajax

标签: php android mysql android-studio


【解决方案1】:

最好的方法是使用 Volley 库。 Volley 是一个 HTTP 库,它使 Android 应用程序的联网变得更容易,最重要的是更快。

数据由 PHP 生成并使用 Json 数组传递。

您需要同时使用 Android 和 PHP 编程,并提供一个数据库表(示例中未提供 db 表)。还没有提供一个包含名为 Constants.php 的数据库密码的 php 文件。

将 HTTP POST 变量发送到 PHP 服务器并返回一个带有 MySQL 数据的 JSON 数组作为响应。

特点 当您按下 ADD TO MYSQL BUTTON 时发送和接收数据。 它将 POST 变量“名称”和“角色”发送到预定义的 HTTP URL(val url: String) 响应作为 JSONObject 数组返回到 val obj 中。 该示例包含一个 JSONObject,其中一个条目具有 2 个变量“错误”和“消息” 对于 MySQL 和 PHP 中的更多行,您需要遍历 JSON 数组。 VolleySingleton 还有有趣的 ImageLoader 用于图像。您可以跳过此功能 当您想添加从服务器调用的线路时,例如:http://198.128.34.23/main.php?op=dbadd 如果你想得到一些东西,你可以打电话给http://198.128.34.23/main.php?op=dbget

代码轨迹 -没有- 提示 将行<uses-permission android:name="android.permission.INTERNET"/> 放入AndroidManifest

MainActivity 类

package com.stsu.phpjson

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.android.volley.*
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        addMyBtn.setOnClickListener {  addMySQL() }
    }

    private fun addMySQL() {

            val url:String = "http://198.128.34.23/main.php?op=dbadd"
      //      val rq:RequestQueue=Volley.newRequestQueue(this)
            val stringRequest = object: StringRequest(Request.Method.POST, url,
                    Response.Listener<String> { response ->
                // Process the json
                try {
                    val obj = JSONObject(response)
                    db_display.text = obj.getString("message")
                }catch (e:Exception){
                    db_display.text = "Exception: $e"
                }

            }, Response.ErrorListener { error ->
                db_display.text = error.message
            }) {


                @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String>
                {
                    val params = HashMap<String, String>()
                    params.put("name", "Maria24")
                    params.put("role", "Parthena243")
                    return params

                }

            }
            // Add the volley post request to the request queue
            VolleySingleton.getInstance(this).addToRequestQueue(stringRequest)



        }

                }

VolleySingleton 类

package com.stsu.phpjson

import android.app.Application
import android.content.Context
import android.graphics.Bitmap
import android.support.v4.util.LruCache
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley


class VolleySingleton  constructor(context: Context)
{
    companion object {
        @Volatile
        private var INSTANCE: VolleySingleton? = null
        fun getInstance(context: Context) =
                INSTANCE ?: synchronized(this) {
                    INSTANCE ?: VolleySingleton(context).also {
                        INSTANCE = it
                    }
                }
    }
    val imageLoader: ImageLoader by lazy {
        ImageLoader(requestQueue,
                object : ImageLoader.ImageCache {
                    private val cache = LruCache<String, Bitmap>(20)
                    override fun getBitmap(url: String): Bitmap {
                        return cache.get(url)
                    }
                    override fun putBitmap(url: String, bitmap: Bitmap) {
                        cache.put(url, bitmap)
                    }
                })
    }
    val requestQueue: RequestQueue by lazy {
        // applicationContext is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        Volley.newRequestQueue(context.applicationContext)
    }
    fun <T> addToRequestQueue(req: Request<T>) {
        requestQueue.add(req)
    }



}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/db_display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.425"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.76" />


    <Button
        android:id="@+id/addMyBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Add to MySQL"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="266dp" />


</android.support.constraint.ConstraintLayout>

PHP-MAIN-FILE.php

<?php 




require_once 'DbOperation.php';

        $response = array(); 

        //// http://----Ur IP Address ---/heroapi/HeroApi/v1/?op=addheroes

        if(isset($_GET['op'])){

            switch($_GET['op']){


                /// Check URL and testing API

                /// Require POST
            case 'dbadd':
                if(isset($_POST['name']) && isset($_POST['role'])){
                    $db = new DbOperation(); 
                    if($db->createDemo($_POST['name'], $_POST['role'])){
                        $response['error'] = false;
                        $response['message'] = 'Artist added successfully';
                    }else{
                        $response['error'] = true;
                        $response['message'] = 'Could not add artist';
                    }
                }else{
                    $response['error'] = true; 
                    $response['message'] = 'Required Parameters are missing';
                }
            break; 

                ////http:
//----FROM your IP Address
                ////Require GET
                case 'dbget':
                    $db = new DbOperation();
                    $hero = $db->getDemo();
                    if(count($hero)<=0){
                        $response['error'] = true; 
                        $response['message'] = 'Nothing found in the database';
                    }else{
                        $response['error'] = false; 
                        $response['hero'] = $hero;
                    }
                break; 

            case 'file':
                if (isset($_FILES["uploaded_file"]["name"]))
                    {
                    $name = $_FILES["uploaded_file"]["name"];
                    $tmp_name = $_FILES["uploaded_file"]["error"];
                    $error = $_FILES["uploaded_file"]["error"];

                    if(!empty($name)) 
                    {
                        $location = './assets/';
                        if(!is_dir($location))
                            mkdir($location);
                        if (move_uploaded_file($tmp_name, $location. $name))
                        {
                            $response['error'] = false;
                            $response['message'] = 'Uploaded';
                        }
                        else {
                        $response['error'] = true;
                        $response['message'] = 'Upload failed';
                        }   
                    }
                    else { 
                        $response['error'] = true;
                        $response['message'] = 'Blank file'; 
                        }

                    }
                    else {
                        $response['error'] = true;
                        $response['message'] = 'NULL POST FILE'; 
                    }
            break;
            case 'filestr':
                if (isset($_POST['imstr']) && isset($_POST['filename'])) {
                    $imstr = $_POST['imstr'];
                    $filename = $_POST['filename'];
                    $path = "./";



                    if (file_put_contents($path. $filename, base64_decode($imstr)) == TRUE) {
                        $response['error'] = false; 
                        $response['message'] = 'Succesfully uploaded image';
                    }
                    else 
                    {
                        $response['error'] = true; 
                        $response['message'] = 'Server could not save: ';
                    }
                } else {
                    $response['error'] = true; 
                    $response['message'] = 'Null data received';
                    }
            break;

            default:
                $response['error'] = true;
                $response['message'] = 'No operation to perform';

        }

    }else{
        $response['error'] = false; 
        $response['message'] = 'Invalid Request';
    }

    echo json_encode($response);
 ?>

PHP 包含的文件(将其命名为 DbOperation.php)

<?php


class DbConnect
{
    //Variable to store database link
    private $con;

    //Class constructor
    function __construct()
    {

    }

    //This method will connect to the database
    function connect()
    {
        //Including the constants.php file to get the database constants
        include_once dirname(__FILE__) . '/Constants.php';

        //connecting to mysql database
        $this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        //Checking if any error occured while connecting
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            return null;
        }

        //finally returning the connection link
        return $this->con;
    }

}

?>

【讨论】:

  • 别忘了在 AndroidManifest.xml 中添加一行: 如果您需要更多帮助,请询问我,但请给我点赞并将我的帖子标记为答案。谢谢
  • 您的 PHP 代码急需重构。 DbConnect 没有任何用途。
  • 这是一个帮助连接到 Db 的帮助类。我认为在这种情况下有用
  • mysqli 也是一个有助于连接的类。请阅读:Should we ever check for mysqli_connect() errors manually?
猜你喜欢
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
相关资源
最近更新 更多