Sun. Jan 20th, 2019

send data to remote server using android retrofit Library with PHP MySQL

send data to the remote server using android retrofit Library with PHP MySQL | In this tutorial, we will learn how to send data to the remote server using android retrofit Library with PHP MySQL. Retrofit is a type-safe rest client for java and android. Retrofit Library is developed by the Company “Square” which makes the Credit/Debit Card Reader for the point of sale terminals.Android Retrofit API is one of the most useful libraries which makes life easy to communicate with the server and get the data back from the server in a nice java object format. Retrofit basically works on annotations that we have seen before in android “@override”. Annotation is used to provide semantic metadata.

Download Project – here

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Step:-1 Configuring Remote Server

  • Download WAMP Server on your PC. Install it and run the Wamp server. if Wamp server logo turns its color to green its ready to use.

  • Now Open the PHPMyAdmin by hitting “http://localhost/phpmyadmin/” in your browser. The username will be “root” and password will be blank. Click “GO”.
  • Create a Database name it “check”, then create a table inside check database. name it userdata.

  • Table column name will be id, name, email, password as shown in below image.

Step:-2 Creating PHP file

  • Open www folder inside C drive > wamp> www.
  • Create a folder inside www. name it user.
  • Inside user folder, create a file name it index.php.
  • Open Index.php file in Notepad++ Editor. and add the following code inside it.make sure file type must be PHP. and save it.
<?php

$username = $_POST['name'];
$useremail = $_POST['email'];
$userpassword = $_POST['password'];
$user = "root";
$pass = "";
$host= "localhost";
$dbname="check";

$con = mysqli_connect($host,$user,$pass,$dbname);
$sql="insert into userdata(name,email,password) values('".$username."','".$useremail."','".$userpassword."');";
if(mysqli_query($con,$sql)){
	echo  "data inserted";
	
}else{	
	echo "Failed";
}
?>

Step 3: – Creating Project & adding Dependencies

Open your Android Studio -> Go to File > New > New project -> Choose BlankActivity > Finish.

Open your app level build.gradle and add following Retrofit Library dependencies

compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'

Step 4: – Add Internet permission 

Add Internet permission to your AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET"/>

Step 5: – Add Layout File

Create or add an XML file inside layout folder name it activity_main.xml. this file contains three edit text which holds the value of name, email, password and a button which submit the details to remote server.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mytrendin.retrofitsenddata.MainActivity">


    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="name"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="27dp"
        android:id="@+id/name"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="email"
        android:ems="10"
        android:layout_below="@+id/name"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="28dp"
        android:id="@+id/email"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="password"
        android:ems="10"
        android:layout_below="@+id/email"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="33dp"
        android:id="@+id/password"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:text="Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="48dp"
        android:id="@+id/save"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Step 6: – Creating Server Url 

  • Open Command Prompt and Type “ipconfig” you will get ipv4 Address as shown in below image.

  • Here my server URL will be
//http://192.168.43.87/path to index.php file

http://192.168.43.87/user/index.php

Step 7: –  Create Interface ApiService.java

Create an interface name it “ApiService.java”. It holds “@FormUrlEncoded” which actually denotes that request body will be using FORM URL encoding which will be annotated with “@Field”. Requests which made by this annotations have applications www-form-urlencoded MIME type. Field names and their values are UTF-8 encoded. Call<Student> type inserData method will take three parameters name, email, password. In “@Field(“name”)”, the name will act as the key.it must have the same name as the column name of the database. “@post” annotation is used to post the data to the server using Android Retrofit library.

package com.mytrendin.retrofitsenddata;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * Created by csa on 05-May-17.
 */

public interface ApiService {

    @FormUrlEncoded
    @POST("/user/index.php")
    Call<Student> insertData(@Field("name") String name, @Field("email") String email , @Field("password") String password);
}

Step 7: –  Create >Student.java 

Create a POJO Class name it Student.java class which holds the getter and setter methods.

package com.mytrendin.retrofitsenddata;

/**
 * Created by csa on 05-May-17.
 */

public class Student {

    String name,email,password;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Step 7: –  Create >MainActivity.java 

On Save button click Create the Instance of the Retrofit which takes the URL of the base URL then build the retrofit.Create the instance of the Interface of ApiService and call its insertData method which we created the interface ApiService.java. insertData method will take the parameter which we have to send to the server.

package com.mytrendin.retrofitsenddata;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {


    EditText name,email, password;
    Button save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name= (EditText) findViewById(R.id.name);
        email= (EditText) findViewById(R.id.email);
        password= (EditText) findViewById(R.id.password);
        save = (Button) findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient client = new OkHttpClient();
                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://192.168.43.87")
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
                ApiService service = retrofit.create(ApiService.class);
                Student student = new Student();
                student.setName(name.getText().toString());
                student.setEmail(email.getText().toString());
                student.setPassword(email.getText().toString());
                Call<Student> call = service.insertData(student.getName(),student.getEmail(),student.getPassword());

                call.enqueue(new Callback<Student>() {
                    @Override
                    public void onResponse(Call<Student> call, Response<Student> response) {

                        Toast.makeText(MainActivity.this, "response"+response, Toast.LENGTH_LONG).show();

                        name.setText("");
                        email.setText("");
                        password.setText("");

                    }

                    @Override
                    public void onFailure(Call<Student> call, Throwable t) {


                        Log.i("Hello",""+t);
                        Toast.makeText(MainActivity.this, "Throwable"+t, Toast.LENGTH_LONG).show();

                    }
                });
            }
        });

    }
}

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

2 thoughts on “send data to remote server using android retrofit Library with PHP MySQL

  1. Its showing an error saying Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path$

Leave a Reply

Your email address will not be published. Required fields are marked *