Android Retrofit 2, PHP With Example

Lokesh Deshmukh
Prog-Ramming Solutions
3 min readJul 7, 2021

After going through this blog you will be able to :

  1. Get response from server.

What is Server ?

A server is a computer program or device that provides a service to another computer program. Like we have GoDaddy and BigRocks which provide us server on lease.

Sign up on anyone of these or other server providers. Initially you will get the access to CPanel. It will look like this:

After login you will get the portal in which you can access file manager, PhpMyAdmin(for Database), etc.

First we will create Simple Php File and will access that file info in Android App :

We created this file named “atestphp.php”.

In that file I wrote code to output simple json:

{“data”:”testdata”}

You can click and test this in browser also : cchat.in/demo/atestphp.php

Now we have something on our Server. Let’s create an app to access this data from Android App.

Firstly we will create new project with Android studio and add this dependency in gradle:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Create a kotlin file RetrofitInstance. This will create an static retrofit instance to make api call:

object RetrofitInstance {
private var retrofit: Retrofit? = null
private const val BASE_URL = "https://cchat.in/demo/"

/**
* Create an instance of Retrofit object
*/
@JvmStatic
val retrofitInstance: Retrofit?
get() {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
}

Now we need to create API Interface class to make different api calls over the same domain.

interface APIInterface {
@get:GET("atestphp.php")
val defaultData: Call<SampleData?>?
}

As our base url in RetrofitInstance class is “https://cchat.in/demo/” if call this method defaultData the API call will be “https://cchat.in/demo/atestphp.php”.

To call this in android app we will use following code:

APIInterface service = RetrofitInstance.getRetrofitInstance().create(APIInterface.class);

Call<SampleData> call = service.getDefaultData();

call.enqueue(new Callback<SampleData>() {
@Override
public void onResponse(Call<SampleData> call, Response<SampleData> response) {
((TextView)findViewById(R.id.server_response_text)).setText(response.body().getData());
Toast.makeText(MainActivity.this,response.body().getData(),Toast.LENGTH_LONG).show();
}

@Override
public void onFailure(Call<SampleData> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Error message: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});

Running the app:

On Click of Get_Default_Data button we are calling above method and we are getting response from our newly created php file atestphp.php.

Happy Coding!

--

--

Lokesh Deshmukh
Prog-Ramming Solutions

Android developer | Photographer | Web Deveoper| Freelancer