简体   繁体   中英

Unable to fetch JSON data using retrofit2 in Android

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.

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/

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM