0

I'm creating this app which get a 'bus' object from JSON file and display its info using an id. The problem is I followed tutorials and did everything as I saw in posts and videos, but the app always fail to get the response. What could be that I'm missing?

I'm working on Android Studio, with the required gradle files needed for retrofit2 and gson-converter. I created API interface, Retrofit creator class, and ServiceApi generator class.Also made @SerializedName annotations for the class which will get json data. Still, no clue why it doesn't work.

The JSON :

{
    "response_code":5,
    "response_msg":"Success",
    "bus":{
        "vehicle_id":"1",
        "vehicle_plate":"ا ا ا 4389",
        "category":"ورشة",
        "category_id":2,
        "last_seen":"2019-04-15T12:19:24.4223277",
        "location":{
            "lat":0.0,
            "lon":0.0
        },
        "status":{
            "sos":false,
            "ignition":"",
            "movement":false,
            "speed":0.0
        },
            "driver":{
                "driver_id":0,
                "driver_name":""
            },
            "inspection_report":[]
        }
}

Here is MainActivity.java (for now just a test "success" or "fail", but it always give me failure):

public class MainActivity extends AppCompatActivity {


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

        ApiGenerator.getServiceApi().getBusStatus("1").enqueue(new Callback<BusStatus>() {
            @Override
            public void onResponse(Call<BusStatus> call, Response<BusStatus> response) {
                Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<BusStatus> call, Throwable t) {
                Toast.makeText(MainActivity.this, "fail", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

Here is BusStatus.java which will get json data:

public class BusStatus {

    @SerializedName("response_code")
    private Integer response_code;
    @SerializedName("response_msg")
    private String response_msg;
    @SerializedName("bus")
    private Bus bus;

    public BusStatus(int response_code, String response_msg, Bus bus) {
        this.response_code = response_code;
        this.response_msg = response_msg;
        this.bus = bus;
    }

    public Integer getResponse_code() {
        return response_code;
    }

    public void setResponse_code(Integer response_code) {
        this.response_code = response_code;
    }

    public String getResponse_msg() {
        return response_msg;
    }

    public void setResponse_msg(String response_msg) {
        this.response_msg = response_msg;
    }

    public Bus getBus() {
        return bus;
    }

    public void setBus(Bus bus) {
        this.bus = bus;
    }
}

Interface MyApi.java (not sure if I wrote the query in the right way):

public interface MyApi {



    @GET("/*API PATH*/")
    Call<BusStatus> getBusStatus(@Query("id") String vehicle_id);

}

RetrofitClient creator, RetrofitClientInstance:

public class RetrofitClientInstance {

    private static Retrofit retrofit;

    public static Retrofit getRetrofitInstance(){
        Gson gson = new GsonBuilder().setLenient().create();
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(/*BASE URL*/)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }

}

API generator, ApiGenerator.java:

public class ApiGenerator {

    public static MyApi getServiceApi(){
        return RetrofitClientInstance.getRetrofitInstance().create(MyApi.class);
    }

}

I also made sure that I added internet permission in AndroidManifest.xml (don't mind other contents):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testgettingdata">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

What I want is it to success for now so I can continue, but no idea why it is failing even thought I've tried to debug but couldn't understand what make it fails directly. If there is a mistake in my code please guide me.

Edit: this is the error I get when I get Throwable t message: "java.net.UknownServiceExeption: CLEARTEXT communication to (/the base url/) not permitted by network security policy"

Mohammad Y
  • 13
  • 5
  • Can you post the detailed log of why it fails? – Luca Nicoletti Apr 17 '19 at 07:46
  • I mean it goes to 'onFailure' method, so I guess no connection to the file or something like this. – Mohammad Y Apr 17 '19 at 07:49
  • Check log For error there must be some error . `Throwable` is part of `onFailure` So use `t.printStacktrace()` to print error in logs . Also you can not just determine the API call success inside `onSuccess` . You need to use `response.isSuccessful()` to check this or HttpStatus Code too which is `resonse.code()`. – ADM Apr 17 '19 at 07:50
  • @Jian Astrero still same result, no response. – Mohammad Y Apr 17 '19 at 07:50
  • @ADM It's just for test, to make sure that it goes to 'onResponse' – Mohammad Y Apr 17 '19 at 07:53
  • It says "java.net.UknownServiceExeption: CLEARTEXT communication to gis.naqaba.com.sa not permitted by network security policy". Does that mean the network is the cause? But it does display the json file when I open the URL. – Mohammad Y Apr 17 '19 at 08:04
  • 1
    Possible duplicate of [Android 8: Cleartext HTTP traffic not permitted](https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted) – Zoe Jun 14 '19 at 19:28

2 Answers2

0

you have to change in your Base url into this :-

http://(BASE URL)/api/

and in inetrface like this:-

@GET("(API PATH)?")
Call<BusStatus> getBusStatus(@Query("id") String vehicle_id);
Mohammad Y
  • 13
  • 5
Sandeep Malik
  • 1,972
  • 1
  • 8
  • 17
0

I think you are using Android Pie, which is the reason why you are having this problem. This is because, as stated in the documentation:

Starting with Android 9 (API level 28), cleartext support is disabled by default.

You could have a further read on this situation from here or you could go on and add usesCleartextTraffic as an attribute for your application tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>
Jian Astrero
  • 744
  • 6
  • 19