Best way is to use Volley library. Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
The data is generated by PHP and passes them using a Json array.
You need to program in both Android and PHP and also provide a database table (db table not provided in the example). Not provided is also an included php file with the DB passwords called Constants.php.
Sends HTTP POST variables to PHP server and Get back a JSON Array with MySQL data as a response.
Features
When you press the ADD TO MYSQL BUTTON sends and receives data.
It sends POST variables “name” and “role” to a predefined HTTP URL (val url: String)
The response comes back in the val obj as a JSONObject Array.
The example contains a JSONObject with one entry with 2 variables “error” and “message”
For more rows from MySQL and PHP you need to iterate through the JSON Array.
The VolleySingleton has also the fun ImageLoader for images. You can skip this function
When you want to add a line you call from your server something like: http://198.128.34.23/main.php?op=dbadd
if you want to get something you call http://198.128.34.23/main.php?op=dbget
Code Trail
-NONE-
Tips
Put line <uses-permission android:name="android.permission.INTERNET"/>
in AndroidManifest
MainActivity Class
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 Class
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 Included file (name it as 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;
}
}
?>