0

I'm new in Android. I tried to fetch json data in android using retrofit2, it showing "connect time out" and displaying nothing. Same code if I'm Using with some other rest api it is working fine. Please help me to resolve this issues. Thank you in advance.

Here is my MainActivity.java class :

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;
import java.util.concurrent.TimeUnit;

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 {

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.listViewHeroes);
        getUsers();
    }
    public void getUsers(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
                .build();
        Api api = retrofit.create(Api.class);
        System.out.println("api:"+api);
        Call<List<User>> call = api.getUsers();
        Log.i("inside main","method..");
        call.enqueue(new Callback<List<User>>() {

            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {

                List<User> userList = response.body();
                Log.i("hello ..","hi");
                String[] users = new String[userList.size()];

                for (int i = 0; i < userList.size(); i++) {
                    users[i] = userList.get(i).getName();
                    Log.i("User name is :"+users[i],"User list");
                    listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, users));
                }

            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Log.i("fail","fail..");
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Api Interface

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {
    String BASE_URL = "http://192.168.1.8:8083/FarmerWebApplication/";
    @GET("getUsers")
    Call<List<User>> getUsers();

}

User.java class

import com.google.gson.annotations.SerializedName;

public class User {

    @SerializedName("uname")
    private String name;
    private String address;


    public User(String name, String address) {
        this.name = name;
        this.address = address;
    }
    public String getName(){
        return name;
    }

    public String getAddress() {
        return address;
    }

Below is the json response which I want to fetch using http://192.168.1.8:8083/FarmerWebApplication/getUsers api. 192.168.1.8 is my system ip address.

[
    {
        "uid": 1,
        "uname": "amit",
        "uaddress": "Bangalore"
    },
.....
]

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listViewHeroes"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

Please feel free to ask if more detail required. Thank you.

Amit Singh
  • 81
  • 2
  • 11
  • copy the url in your browser and check if its giving proper json response, if yes try increasing your retrofit timeout like this >> https://stackoverflow.com/questions/29380844/how-to-set-timeout-in-retrofit-library – Navneet Krishna May 13 '19 at 18:38
  • @NavneetKrishna Thank you for your Quick response. I tried your solution. Even I'm getting the same Issues. – Amit Singh May 13 '19 at 18:53

3 Answers3

0

Maybe is here the problem :

@SerializedName("uname")
private String name;
private String address;

and your response is :

{
    "uid": 1,
    "uname": "amit",
    "uaddress": "Bangalore"
},

You must have the same name in your interface and your response ,change in interface :

private String uname; private String uaddress;

For more information see documentation : https://square.github.io/retrofit/

Dev_Abraham
  • 404
  • 4
  • 6
0

May be your server or local host return data in delay you can check it by increasing timeout time

here is a kotlin code for

okhttp client

 val okHttpClientBuilder = OkHttpClient.Builder()
                .addInterceptor(ChuckInterceptor(application))
                .addInterceptor(AppVersionInterceptor())
                .connectTimeout(1, TimeUnit.MINUTES)
                .readTimeout(1, TimeUnit.MINUTES)
                .writeTimeout(1, TimeUnit.MINUTES)
Hello world
  • 80
  • 1
  • 10
  • I tried it in java code. I increase it till 5 minutes. Even it is showing the same issues. its not going inside the onResponse(). it is skipping onResponse() and control transfer to the onFailure() method and displaying Connect Timed out in TOST message. – Amit Singh May 13 '19 at 19:29
0

Retrofit not able to complete network due to which Connection Time out occur.

It seems you are running API at localhost. Make sure you on same network, correct system IP address and port number is correct.

Try to call webservice on machine browser with same URL used in mobile. Check response is expected.

  • Yes I'm running on my localhost. For that reason I'm using IPv4 of my system and port adress of Apache Tomcat. And My machine and Android device is connected with the same router. Even I'm getiing this issues. – Amit Singh May 13 '19 at 19:43
  • check your local machine which running Tomcat IP address with port. For my case, 192.168.0.102:8080/api/notes which takes GET request and i am able to get response on my mobile device. You can call same url from your mobile browser to check whether API is accessible or not. – Ankit ihelper Sharma May 13 '19 at 19:50
  • please refer this link.. https://stackoverflow.com/questions/6246127/cant-access-tomcat-using-ip-address – Rajasimman R May 14 '19 at 04:28