آموزش های پایه ذخیره_سازی وب_سرویس

Connect Android training to the PHP MySQL web service by Retrofit


In this matter, we write a easy web service (PHP) beneath PHP and the MySQL database and look at it with an Android software that includes a registration type and an entry type. The undertaking uses the well-known Retrofit 2 library for communication between the Web service and the shopper.
This part consists of the following subjects:

  • PHP Temporary Introduction
  • Introducing the MySQL database management system
  • Introducing the phpMyAdmin panel to manage the MySQL database
  • How to work with Local Server WampServer
  • How to create databases and tables in the phpMyAdmin panel
  • Construct a easy web service beneath PHP and the MySQL database
  • Introducing and describing the features used in the Web service source
  • How to print JSON knowledge in PHP
  • How to Check and Error Web Providers by Postman Software
  • How to Check and Troubleshoot a Web Service With out Software and by URL
  • Add the Retrofit and Converter Gson libraries to the Android challenge
  • Definition of app access to the community and the Internet
  • Introducing the @SerializedName of the Gson Library
  • Use the @POST and @GET methods to send and receive info between the shopper and the API
  • Create a registration type and login by Fragment
  • Changing the variables using the exchange technique
  • Manage onResponse and onFailure in the enqueue technique

This matter is offered in pdf format and in 47 pages. You will notice the following a number of primary pages for the sections “Web Service” and “Android Project”:

In the identify of Allah. In the previous, we turned accustomed to the fashionable Retrofit library, in addition to the JSON knowledge transfer format. The previous meeting undertaking was quite simple and only involved receiving static (static) info from a json file.
On this session, I intend to create a very simple and light-weight RESTful API utilizing the server-side PHP language and MySQL database that has the means to transfer knowledge between it and a shopper. Right here is our Android shopper.
Then I create an Android undertaking that features a registration type (register) and a login type (logon).
The best way it really works is that by completing the consumer registration type, the info entered by Retrofit and stored in the HTTP platform is shipped to the web service and saved in the database. Also, in the login type, the info entered by the consumer (username and password) is matched to the info saved in the database, and if the info is entered appropriately, a welcome message containing the identify and consumer identify of the individual is displayed.

Notice: Earlier than studying this matter, make sure to learn the past matter. The small print previously said on this matter usually are not repeated.

Build web service using PHP and MySQL

PHP is an object-oriented programming language used to build server-side purposes.
MySQL is a database administration system (DBMS) that permits you to store, search, type, and retrieve database knowledge. Many databases are at present managed by this technique. When you have already worked with internet hosting providers and have the experience of establishing an internet site (reminiscent of a WordPress website), you're in all probability acquainted with MySQL and the phpMyAdmin management panel. MySQL is free, like SQLite, owned by Oracle.
I do not intend to train PHP language or absolutely describe MySQL here. In case you are accustomed to all programming languages, you’ll be able to simply perceive the PHP web service code. We already discovered SQL statements in SQLite.
First I run WampServer. In the previous section, we turned conversant in the server vamp and we stated that via this software we will launch an area web server on our personal PC.

Word: Don’t confuse the web server with the web service. Web service is an software operating on a web server. WampServer launches a web server on our pc that supports both PHP and MySQL. That’s precisely what we’d like to set up a web service for this matter. As well as, in the earlier section, it was famous that as well as to WampServer, there are other choices like Xampp, which is dependent upon your style. And of course WampServer solely has a Windows model.

After operating WampServer, it takes a number of seconds to load its providers. If the providers are loaded appropriately, the software icon modifications to green and exhibits the phrase All Providers Operating:

Run Local Server WampServer

If the icon is just not green, right-click on it and choose Refresh.
By clicking on the server icon, the following menu opens:

WampServer menu

The Localhost choice opens the WampServer residence page in the browser that shows details about the lively modules. phpMyAdmin is the MySQL admin panel that we use for this panel to build and manage the database. Listed here are the different options for managing totally different elements. If the software icon just isn’t but inexperienced, click Restart All Providers as soon as.
First I want to create a database. To do that, click on on phpMyAdmin. The Login Panel opens in the browser:

Log in to phpMyAdmin

In WampServer or different Native Servers, the username is equal to root and Password must be empty. Upon arrival, the panel opens as follows:

PhpMyAdmin panel

I’m going to the Databases part and create a database with the userdata customized identify:

Build a database in phpMyAdmin

After creating the database, I add a desk with the identify of the desired information to the database. I want four columns for this desk, so I'll put 4 in the Number of columns column. These are four elements for storing consumer info that includes the id, the identify of the consumer, the username, and the password.

Create table in MySQL database

table database

I’ve an INT line of 5 and the rest of the VARCHAR line of 50. id ought to be unique to every consumer and routinely add a unit by registering each consumer, so tick for this line Part A I (abbreviated to AUTO INCREMENT):

Auto increment

Build table in database

About Sort and Size, and extra, is mentioned intimately in the SQLite discussion and doesn’t need to be repeated. Here I did the creation of a table and column in the visible surroundings, however it was additionally attainable to do that by writing the Question. Click on on Preview SQL. The following query is shown:

Query build database table

That’s, if you realize the writing of a query, we will create the table by putting it in the SQL part:

SQL Query

Nevertheless, both methods could be executed. In the previous step, the visual setting, after getting into the row info, I'll save the choice and build the columns:

Take the database table

OK! I at present don’t have a database.
In the www folder for WampServer, I create a folder named api, and I will upload the information I've already ready right here:

PHP and MySQL Web Services

I’ve written this easy web service with the PHP language so the php file extensions. Is. Briefly describe the codes for every file to find out how to use this web service normally. To open information, use a easy and free editor like ++ Notepad or Chic Textual content (the Web service is situated in the Train folder).
db_connect.php:
On this file, I entered the database info and then the connection command to the database was written:

Db_connect.php file

4 variables with custom names that include database info. The database is hosted on the similar system, so the value is localhost. The consumer and password are the username and password of the phpMyAdmin login. That’s root for consumer and empty string for password. I saved the database identify in the dbname variable. It is best to know that the naming of variables, as you already know in Java, is bigoted and never legally potential.
The mysqli_connect () perform creates a connection for the database. This perform takes four enter values, which is the similar as the info outlined at the beginning of the file. To ensure I write the connection command appropriately and communicate with the database, I wrote a if () that checks for connection or non-connection. If there’s $ connection (that is, mysqli_connect with the info it has been in a position to connect to the database), a profitable connection message might be printed, otherwise the connection failure message will probably be printed. To examine the outcome, just run the file on the browser:

Testing database connection

The primary message is printed, which suggests there isn’t a drawback connecting to the database. After making certain that the connection to the database is functioning appropriately, delete or Comment if to take away the remaining web service output:

Comment on PHP

After disabling this command, no redirects ought to be printed by invoking the file again in the browser:

Android Web Service Output

At the starting of the meeting, we decided that our software would have a registration type and an entry type. So two separate information are added to the web service to manage these areas.

register.php:

Web Service Membership Section

First, we call the db_connect.php request command, as a result of we’d like to connect to the database to get consumer info and log into the database. In the registration type, info including the identify, username and password are acquired from the consumer. The $ $ identify, $ username, and $ password variables are acquired by the $ _GET technique of knowledge acquired from the shopper aspect and saved internally.
In the registration course of, the consumer have to be checked. The username that you’ve chosen has not already been chosen by another person. So I wrote a variable named $ sql_select that its value is a SELECT query:

SELECT * FROM information WHERE username = '$ username'

This command checks the information table inside the database, and if it accommodates a worth equal to the value saved in the $ username variable from the shopper (registration type) acquired, it returns it.
In the $ end result variable, the mysqli_query () perform first connects to the database ($ connection), then sends the above command to the database. Lastly, what this question gets (ie the existence or absence of a username comparable to what the present consumer intends to register) is saved on this variable.
Then we now have one condition. The mysqli_num_rows () perform in PHP declares the number of rows returned from the queue (num stands for numbers and rows means rows).
mysqli_num_rows ($ end result)> zero
If the username that the individual entered has already been selected by one other consumer, then $ return returns it so mysqli_num_rows () will probably be larger than zero, and subsequently the first a part of the situation will run:

$ standing = “REGISTERED”;

That’s, the REGISTERED text string is stored inside the $ standing variable.
But when the consumer has not already registered with this username, mysqli_num_rows ($ outcome) is zero, so the second part of the condition is executed. That is, code inside the physique else.
On line 15 I defined a query referred to as $ sql_insert. This query enters the values ​​stored in $ identify, $ username, and $ password in the information tab and in the names, username, and password fields. To ensure the info is stored appropriately in the database, I added a clause after this query if the question is shipped to the database, the SUCCESS assertion and in any other case the ERROR clause is saved in the $ standing variable.

So here the $ standing variable can save three states:
– Username already used and returns the REGISTERED message.
– The username is free, the registration operation is successful and the consumer info is saved in the database and ultimately returns SUCCESS.
– The username is free, however for some cause, the info acquired isn’t recorded on the database, which returns the ERROR.

Lastly, the worth saved in $ status is echoed by the json_encode () perform in the form of an JSON object:

echo json_encode (array (“response” => $ standing));

The output of this line is a JSON object that has a pair of names / values. I set the identify of the reply. The worth can also be $ standing.
At the finish, the connection closes to the database by the mysqli_close () perform, as a result of we do not want this connection until the subsequent operation.

Observe: We've already stated that each one languages ​​in the world are supported by the JSON format. In PHP, the json_encode () perform is used to ship knowledge to a shopper.

login.php:

Web Services Logging Section

The operation related to the login already registered is thru this file. First, the username and password that the consumer entered in the login type shall be posted to the server and stored in the $ username and $ password variables. Then I wrote a SELECT query that searched the username and password from the shopper aspect in the information database table, and returns the identify if this username and password are in the database.
The $ end result perform has an analogous perform to the perform contained in register.php.
Then, a condition is about: if the result of mysqli_num_rows ($ end result) is bigger than zero, use the mysqli_fetch_assoc () perform to store the worth of the identify of the corresponding row in the database inside the variable $ identify. Moreover, the SUCCESS clause is recorded as status. In the following, the standing (status), the consumer identify (identify) and its username (username) are printed in JSON format.

Observe: The username worth is taken from $ username, which is actually what the consumer enters and isn’t taken from the database.

If the result of mysqli_num_rows ($ outcome) is 0, the FAILED state shall be printed.
OK! Web service writing accomplished. Earlier than I’m going to Android Studio, I first want to check the Web service to be certain that the knowledge storage and knowledge restoration operations are executed appropriately and its JSON output format is right and full.

(Obtain the PDF file to learn the description of the web service)

Construct an Android Challenge Connect to the Web Service by the Retrofit Library

I'm going to Android Studio and I’ll create a venture referred to as Retrofit & PHP and an Empty Activity Activity.
The first step is to add Retrofit libraries to construct.gradle:

dependencies
    implementation fileTree (dir: 'libs', embrace: [‘*.jar’])
    implementation 'com.android.help:appcompat-v7:28.0.zero'
    implementation 'com.squareup.retrofit2: retrofit: 2.4.zero'
    implementation 'com.squareup.retrofit2: converter-gson: 2.4.0'

Do not forget to add the right to entry the manifest to connect to the community and the Web.

AndroidManifest.xml:








The info we receive from the web service is response (shared in both varieties) as well as identify and username for the login type. So, make a category and outline these three parameters. I will put the identify of this class Consumer:

Build User.java class in Android project

I defined three variables inside the class. Then I create the Getter strategies (alt + insert)
The aforementioned naming is totally different from the names I chose on the web service. Subsequently, we’d like to determine which of the variables corresponds to which item. To do that, we use an annotation referred to as @SerializedName that relates to the Gson library:

Consumer.java:

package deal and.android_studio.retrofitphp;

import com.google.gson.annotations.SerializedName;

public class Consumer

    @SerializedName (“response”)
    personal String apiResposnse;

    @SerializedName (“name”)
    personal string apiName;

    @SerializedName (“username”)
    personal String apiUsername;

    
    public String getApiResposnse ()
        return apiResposnse;
    

    public String getApiName ()
        return apiName;
    

    public String getApiUsername ()
        return apiUsername;
    

Perhaps ask why, why work onerous? It might be potential to outline the variables in the similar means as the parameters in the web service, in order that there isn’t any need for this additional motion (as in the previous). Your criticism is value it. However the developer naming process may be totally different from what’s already defined in the web service (and the potential to change the supply of the Web service) and the programmer is decided to be named in its personal method. Right here's how the Gson Library handles it.
To construct Retrofit I created a new class with the identify of the API. The code is as follows.

API.java:

package deal and.android_studio.retrofitphp;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class API

    public static last String BASE_URL = “http://192.168.56.1/api/”;
    public static Retrofit myRetrofit = null;

    public static Retrofit getAPI ()

        if (myRetrofit == null)

            myRetrofit = new Retrofit.Builder ()
                    .baseUrl (BASE_URL)
                    .addConverterFactory (GsonConverterFactory.create ())
                    .construct ();

        

        return myRetrofit;

    

Like the earlier one, I outlined the URL of the web service. Then a specified condition to verify if the Retrofit is null then create the Retrofit.Builder () if it isn’t null, that’s, it was already constructed.
It's time to make the Interface. Like a earlier meeting, I'll create a new class and set it to a class as an alternative of an interface sort. I put the ApiInterface identify on this file.

ApiInterface.java:

package deal and.android_studio.retrofitphp;

import retrofit2.Name;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Question;

public interface ApiInterface

    @POST (“register.php”)
    Name regCall (@Query (“name”) String Identify, @Query (“username”) String UserName,
@Query (“password”) String Password);

    @GET (“login.php”)
    Name loginCall (@Question (“username”) String UserName, @Question (“password”) String Password);
    

In the previous matter undertaking, we solely had a @GET technique, but here's also a @POST technique for the consumer's membership part the place consumer knowledge ought to be sent to the server. In fact, as famous in the Postman section, each @GET (ie login and registration) can be used because we use simple queries. Nevertheless, I used @POST to not be unfamiliar to you.

Word: The supply of the Android challenge and web service is within the Workouts folder

Download the PDF file to learn the tutorial.

Provided that low-end primary training is offered to the consumer and the proceeds are solely used to fund the website and supply future training, sharing this file with others is towards ethics.

In case you have hassle downloading from the field under (download basket), by visiting this hyperlink, select RetrofitPHP for five,000 USD.

Obtain this tutorial in PDF format with web service supply and undertaking
Variety of pages: 47
Measurement: three.5 MB
Worth: $ 5,000

If this tutorial was useful to you, please fee it:

Web Service: Part Three: Web Providers Creation with PHP and MyQSL and its Relfortivity

5 (100%) 1 vote