0

In the manifest file i have added these two lines as well.

android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true"

In the network_security_config file i have included my localaddress.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">http://192.168.0.107/android</domain>
    </domain-config>
</network-security-config>

Moreover, from the virtual device, i can enter the local address as well (192.168.0.107/android).

Codes are here:

In the Module:app used the retrofit2.

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

Now here in the MainActivity.java, call.enqueue(new Callback() is failing. As i am a beginner level developer i dont know what to use to watch the response(Toast/log). seeking help here as well.

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainActivity extends AppCompatActivity {

    private Button btn_upload,btn_select;
    private TextView text_view;

    private int REQ_PDF = 21;
    private String encodedPDF;

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

        text_view = findViewById(R.id.text_view);
        btn_select = findViewById(R.id.btn_select);
        btn_upload = findViewById(R.id.btn_upload);

        btn_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
                chooseFile.setType("application/pdf");
                chooseFile = Intent.createChooser(chooseFile, "Choose a PDF File");

                startActivityForResult(chooseFile,REQ_PDF);

            }
        });

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadDocument();
            }
        });
    }

    private void uploadDocument() {

        Call<ResponsePOJO> call = RetroFitClient.getInstance().getAPI().UploadDocument(encodedPDF);

        call.enqueue(new Callback<ResponsePOJO>() {

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


                Toast.makeText(MainActivity.this, response.body().getRemarks(), Toast.LENGTH_SHORT).show();

            }

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

                Toast.makeText(MainActivity.this, "Network Failed", Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_PDF && resultCode == RESULT_OK && data!=null){
            Uri path = data.getData();
            try {

                InputStream inputStream = MainActivity.this.getContentResolver().openInputStream(path);
                byte[] pdfInBytes = new byte[inputStream.available()];
                inputStream.read();
                encodedPDF = Base64.encodeToString(pdfInBytes,Base64.DEFAULT);

                Toast.makeText(this,"Document is selected",Toast.LENGTH_SHORT).show();


            } catch (IOException e) {
                e.printStackTrace();
            }
  
    }
}

ResponsePOJO.java

package com.example.pdfupload;

import android.widget.Toast;

class ResponsePOJO {
    private boolean status;
    private String remarks;

    public boolean isStatus() {
        return status;
    }

    public String getRemarks() {
        return remarks;
    }

}

RetroFitClient.java

package com.example.pdfupload;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetroFitClient {
    private static final String BASE_URL="http://192.168.0.107/android/";
    private static RetroFitClient myClient;
    private Retrofit retrofit;

    private RetroFitClient(){
        retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    public static synchronized RetroFitClient getInstance(){
        if (myClient == null){
            myClient = new RetroFitClient();
        }
        return myClient;
    }

    public Api getAPI(){
        return retrofit.create(Api.class);

    }
}

Api.java

package com.example.pdfupload;

import android.widget.Toast;

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

public interface Api
{

    @FormUrlEncoded
    @POST("upload_document.php")
    Call<ResponsePOJO> UploadDocument(

            @Field("PDF") String encodedPDF
    );
}
  • Can you share what exception you are getting ? – Abdul Jan 30 '21 at 09:31
  • Hello sir, I got this exception W/System.err: java.net.UnknownServiceException: CLEARTEXT communication to 192.168.0.107 not permitted by network security policy But i have added android:networkSecurityConfig="@xml/network_security_config" & android:usesCleartextTraffic="true" in the manifest file – Tahmida jerin Jan 31 '21 at 04:55
  • Have a look at this : https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted – Abdul Jan 31 '21 at 07:33
  • After adding following code this exception is handled. But now i am getting W/System.err: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ error. I have found few articles in stackoverflow. but couldnt understand any. pl help. – Tahmida jerin Feb 01 '21 at 06:10
  • Now, this is an issue in JSON parsing. Print your response body and compare it with your POJO model. – Abdul Feb 01 '21 at 06:14
  • Can you please help me with more detailed instructions like how can i get the response body printed and compare it with the POJO model? – Tahmida jerin Feb 01 '21 at 10:27
  • You can add an interceptor for body logging. https://stackoverflow.com/questions/32514410/logging-with-retrofit-2 kindly look into this. and after that pick the body and generate its POGO model online. – Abdul Feb 01 '21 at 10:53
  • Thanks a ton for your response. However, i made an indentation error in my php file thats why i was getting the json parsing error. After resolving the error the problem is fixed. Even if i remove the line- android:networkSecurityConfig="@xml/network_security_config" from the manifest file,Its working. Only android:usesCleartextTraffic="true" is enough to mitigate the clear text issues i guess. – Tahmida jerin Feb 02 '21 at 10:26

0 Answers0