0

I'm trying to insert data from Android to Mysql.

The problem I'm getting is that the data that I input from EditText on the Android app won't send to the database

I'm using Retrofit as HTTP handler and PHP as backend.

Here's the code:

Retrofit.kt

package com.example.connecttomysql

import com.google.gson.GsonBuilder
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class Retrofit {
    fun getRetroClient() : Retrofit{
        val gson = GsonBuilder().setLenient().create()
        return Retrofit.Builder().baseUrl("http://192.168.1.7/android/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }
}

Request.kt

package com.example.connecttomysql

import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName

class Request {
    @SerializedName("name")
    @Expose
    var name: String? = null
}

UserResponse.kt

package com.example.connecttomysql

import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName

class UserResponse {
    @SerializedName("error")
    @Expose
    var error: String? = null

    @SerializedName("message")
    @Expose
    var message: String? = null


}

UserAPI.kt

package com.example.connecttomysql

import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST

interface UserAPI {
    @POST("config.php")
    fun addName(@Body userRequest: Request) : Call<UserResponse>
}

MainActivity.kt

package com.example.connecttomysql

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {
    private lateinit var inputName : EditText
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        inputName = findViewById(R.id.addName)
        findViewById<Button>(R.id.addNameButton).setOnClickListener { addName() }

    }

    private fun addName(){
        val request = Request()
        request.name = inputName.text.toString()

        val retro = Retrofit().getRetroClient().create(UserAPI::class.java)
        retro.addName(request).enqueue(object : Callback<UserResponse>{
            override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
                val user = response.body()
                Log.e("Success", user?.error.toString())
                Log.e("Success", user?.message.toString())
                Log.e("Success", inputName.text.toString())
            }

            override fun onFailure(call: Call<UserResponse>, t: Throwable) {
                Log.e("Error", t.message.toString())
            }

        })
    }
}

Config.php

<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "android";
$connection = mysqli_connect($host,$username,$password,$database);
if(!$connection){
    echo "Failed to connect to Mysql ". mysqli_connect_error();
}
$response = array();
if(isset($_POST['name'])){
    $name = $_POST['name'];
    $query = mysqli_query($connection,"INSERT INTO user (name) VALUES ('$name')");
    if($query){
        $response['error'] = false;
        $response['message'] = "Successfully added name to database";
    }else{
        $response['error'] = true;
        $response['message'] = "Could not add data to database";
    }
}else{
        $response['error'] = true;
        $response['message'] = "No name";
}    
echo json_encode($response);    
?>

From Android Logcat

2021-07-31 03:05:20.310 30371-30371/com.example.connecttomysql E/Success: true
2021-07-31 03:05:20.311 30371-30371/com.example.connecttomysql E/Success: No name
2021-07-31 03:05:20.311 30371-30371/com.example.connecttomysql E/Success: baee

From that log, it seems that the "name" doesn't go through from Android to Config.php. That's why it shows "No name" from json result.

What am I missing here?

Thank you in advance

Shadow
  • 33,525
  • 10
  • 51
  • 64
Jugs
  • 57
  • 5

1 Answers1

1

you are sending body and trying to receive a field

you can receive the body in php side:

<?php
$request = file_get_contents('php://input');
$request_json= json_decode($request , true);
$name = $request_json['name']

OR (not recommended)

change Retrofit part to:

interface UserAPI {
      @FormUrlEncoded
      @POST("config.php")
      fun addName(@Field userRequest: Request) : Call<UserResponse>
}

then you receive the Request object in php which contains a name part

Amir Hossein
  • 392
  • 3
  • 11