0

For my end of the year project I'm trying to create an app with Android Studio. I want this app to have a login&register feature but I've been struggling with it for weeks now. I don't have any clue how to connect this to my online mySQL database (which is a lot easier for me since I don't want to get into mySQLite because I don't have a lot of time left) to my app and be able to send something into this database. Like when registering I don't know how to send the information to the database, and when login in I don't know how to get this information.

So far I've made the mySQL database online, and I've written some standard PHP code to add the given information (post method) into the database. I've tried many ways to send the info in Android Studio to this database and nothing seems to work. I've followed the following tutorials already:

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

And some other ones I wasn't able to find again. I also searched through StackOverflow but nothing seems to work. Right now I'm just back at the start, I just have edit text boxes that I've converted to strings and I don't know how to send them to my register.php file (and my internet access is on in manifest.xml). Everything I look up seems to be years old and doesn't work and I'm getting really desperate right now.

stayutazen
  • 23
  • 1
  • 3

1 Answers1

0

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;
    }

}

?>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Thanasis
  • 329
  • 4
  • 8
  • Don't forget to put line: in AndroidManifest.xml If you need any more help please ask me, but give me an upvote and an mark my post as answer. Thanks – Thanasis Dec 19 '19 at 19:51
  • 1
    Your PHP code is in dire need of refactoring. The `DbConnect` has no purpose. – Dharman Jan 06 '20 at 23:11
  • It is a help class that helps in connecting to Db. I think there is use in this context – Thanasis Jan 11 '20 at 17:56
  • mysqli is also a class that helps in connecting. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) – Dharman Jan 11 '20 at 17:58