Nasr Mohamed
Nasr Mohamed

Reputation: 15

parsing request from volley

I have a weird problem i make a simple request to the server and it responds successfully and i parse it with no problem then i assign the values returned from the server to my response model class but nothing appear all the values are null despite i find them in the log file: (hint: most of the response is in arabic language)

here is my Response Model class:

    public class QuestionResponse {
        private String lang,questionID,question,choiceOne,choiceTwo,choiceThree,
                type;

        public QuestionResponse(){}

        public QuestionResponse(String lang, String questionID, String question, 
                                String choiceOne, String choiceTwo, String choiceThree, String type) {
            this.lang = lang;
            this.questionID = questionID;
            this.question = question;
            this.choiceOne = choiceOne;
            this.choiceTwo = choiceTwo;
            this.choiceThree = choiceThree;
            this.type = type;
        }

        public String getLang() {
            return lang;
        }

        public void setLang(String lang) {
            this.lang = lang;
        }

        public String getQuestionID() {
            return questionID;
        }

        public void setQuestionID(String questionID) {
            this.questionID = questionID;
        }

        public String getQuestion() {
            return question;
        }

        public void setQuestion(String question) {
            this.question = question;
        }

        public String getChoiceOne() {
            return choiceOne;
        }

        public void setChoiceOne(String choiceOne) {
            this.choiceOne = choiceOne;
        }

        public String getChoiceTwo() {
            return choiceTwo;
        }

        public void setChoiceTwo(String choiceTwo) {
            this.choiceTwo = choiceTwo;
        }

        public String getChoiceThree() {
            return choiceThree;
        }

        public void setChoiceThree(String choiceThree) {
            this.choiceThree = choiceThree;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }
    }

and here is my request method:

public QuestionResponse getQuestion(){

        String BaseUrl = "http://winnerten.com/wini/public/api/";
        String finalUrl = BaseUrl+"get-question";
        final String token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQwYzZiMDliNDQ5NjczNDUzYzNkYTY5OWUyZGY1NTI3ZjkxZTY4MDMifQ.eyJhenAiOiIyNTIyMTAyMDMyOTYtbWw5amRicmswaDJodGVicWRtdW9mNzRyaHZ1NDk1ZGwuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyNTIyMTAyMDMyOTYtZjdvMHU5OGt2bjVvZjhsYXZ1cnB0dHYwNzRwMDVqNzMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMTU2NDMyMjIzNjQ5Njc1OTY2NDIiLCJlbWFpbCI6ImZhdGVtYWFobWVkMTk1M0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZXhwIjoxNTMzMTIyMjQyLCJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJpYXQiOjE1MzMxMTg2NDIsIm5hbWUiOiJmYXRlbWEgYWhtZWQiLCJwaWN0dXJlIjoiaHR0cHM6Ly9saDQuZ29vZ2xldXNlcmNvbnRlbnQuY29tLy13c0FPMWlpTUFYMC9BQUFBQUFBQUFBSS9BQUFBQUFBQUFBQS9BQW5uWTdwTG9PSlptNXU1V2F5YmlYRGhGQnktSy1xRzNRL3M5Ni1jL3Bob3RvLmpwZyIsImdpdmVuX25hbWUiOiJmYXRlbWEiLCJmYW1pbHlfbmFtZSI6ImFobWVkIiwibG9jYWxlIjoiZW4ifQ.HSqzBnGOEw9j33gnIiHycaAb8MPwaq7Elh94D9yBFrTABaOtLL9TNQxX4v7AeyWMRFApFrXw9F0lLfh7khH4dPSwTWKe8dnBJYvlUs_mGHP0tk0VuNr4fNhMWVgbRnn6EnfCUtLRHimXmPCJXJW8NVPtGuNWH5clifC-BbIYgQgXorMW9TCROmBUVj6E-kP023zFvhTHzbrcs7aNq8hx0P30gwyrbnyyWpfCUGG0Q5n5GmaF8onEkMjWx7Z-ZC4UsFSFECzf2Pj9ydB9K3FRUkYO0XZIyRtURZLNs8f6zbB6e0jjw26ETugUVqHTFYvoUcJeWwHK9Axuz9ZuBCeeww";

        final QuestionResponse ques= new QuestionResponse();
        RequestQueue queue = Volley.newRequestQueue(this);

        StringRequest postRequest = new StringRequest(Request.Method.POST, finalUrl,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("ques.response",response);
                        try {
                            JSONObject all = new JSONObject(response);
                            JSONObject data = all.getJSONObject("data");
                            questionId = String.valueOf(data.getInt("questions_id"));
                            type = data.getString("type");

                            ques.setQuestionID(String.valueOf(data.getInt("questions_id")));
                            ques.setType(data.getString("type"));
                            Log.d("id",questionId);
                            Log.d("type",type);
                            if(type.equals("multi")){
                                question = data.getString("question");
                                choiceOne = data.getString("choice_1");
                                choiceTwo = data.getString("choice_2");
                                choiceThree = data.getString("choice_3");
                                lang = data.getString("lang");

                                ques.setQuestion(data.getString("question"));
                                ques.setChoiceOne(data.getString("choice_1"));
                                ques.setChoiceTwo(data.getString("choice_2"));
                                ques.setChoiceThree(data.getString("choice_3"));
                                ques.setLang(data.getString("lang"));

                                Log.d("question",question);
                                Log.d("ch_1",choiceOne);
                                Log.d("ch_2",choiceTwo);
                                Log.d("ch_3",choiceThree);
                                Log.d("type",type);
                            }
                            else if(type.equals("image")){
                                question = data.getString("question");
                                choiceOne = data.getString("choice_1");
                                choiceTwo = data.getString("choice_2");
                                choiceThree = data.getString("choice_3");
                                lang = data.getString("lang");

                                ques.setQuestion(data.getString("question"));
                                ques.setChoiceOne(data.getString("choice_1"));
                                ques.setChoiceTwo(data.getString("choice_2"));
                                ques.setChoiceThree(data.getString("choice_3"));
                                ques.setLang(data.getString("lang"));
                            }
                            else if(type.equals("correct")){
                                question = data.getString("question");
                                choiceOne = data.getString("choice_1");
                                choiceTwo = data.getString("choice_2");
                                choiceThree = data.getString("choice_3");
                                lang = data.getString("lang");

                                ques.setQuestion(data.getString("question"));
                                ques.setChoiceOne(data.getString("choice_1"));
                                ques.setChoiceTwo(data.getString("choice_2"));
                                ques.setChoiceThree("");
                                ques.setLang(data.getString("lang"));

                            }
                            Log.d("ques.parse.done","question parsing done");

                        } catch (JSONException e) {
                            Log.d("ques.parsing.error","parsing failed");
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.d("ques.error.response",error.toString());
                    }
                }
        ){
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", token);
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImNlMDU4OGM4MmJiYjMwOGFjNTk1NWY3ZWVhMDI3ODVlYmM0NzkyZjFjY2ZmN2JjNzdkYmE3YjJmYjM5YjNiMThlMTY2NjgxZTQ0NTBmMWY4In0.eyJhdWQiOiIxIiwianRpIjoiY2UwNTg4YzgyYmJiMzA4YWM1OTU1ZjdlZWEwMjc4NWViYzQ3OTJmMWNjZmY3YmM3N2RiYTdiMmZiMzliM2IxOGUxNjY2ODFlNDQ1MGYxZjgiLCJpYXQiOjE1MzI3NzgwMjgsIm5iZiI6MTUzMjc3ODAyOCwiZXhwIjoxNTY0MzE0MDI4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.EdebRxSgPIjU74xyqZFI-HqAjQJlmICaCNohRQNEK4LG4t3aIOAdna1J4IlZbmX-LXc7NxrMpXtOUs9Ino9OPN6IOBqL1exG57hLdvzQLlBxyagtsa4OKhZLdWIkD_DlZCepalNjg2q9TN1SIb6INihaVHWr-cxWu3jy4I_1IO-hrJmGox_M2lpvF-gMKd5TRoS9nLSSOfXMG9kdkRu5sV0l4DHViq7DylLivfiP_xoCq67AzBGqwqQqQwx7UBjQYF0QcdDJOzmCm4xiSFGpDZJKww8V8xHkCTesD-k3Zmc5Mqx5M-COO_8dewsP2ifLyRbKN8m8gOqVhrJlT1Rgkb71bYsCISMQ3QzFk2Y6ju_bxdiHDSrs99wlK4GxfmqAtBuzFXkamw7P0Ay-hwzPEg2rV0M7Ui2F9e9wNKkVmibBxyPIzHSEGpNF_lNG1TJbmhAHwngZh17TwhOLqTXV71nDJpKFzQgX1dTGC4ORtlMVEgpbGlDDfH0hY51qDUp7t-c4Egsue8nI1uyQ-CBiste1bGCBlpCkG-6WEEoYcQ1l4zJLmYu_VrR82ROEkgNFYQ4seck90s_iP2_tZr8GoiTmwFdIHui95pFBceTZIFQNvQ6jwJeo58jjB7-Ye-JvmyPm59FQm5Vigy-nEsvfuOCE7wxcrGh9qx--wOvfYQs");
                headers.put("Accept", "application/json");
                return headers;
            }
        };


        // handles the slow connection, i.e connection timeout //
        //int socketTimeout = 5000;  //5 seconds
        int socketTimeout = 30000; // 30 seconds. You can change it
        RetryPolicy policy = new DefaultRetryPolicy(
                socketTimeout,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

        postRequest.setRetryPolicy(policy);
        queue.add(postRequest);

        return ques;
    }

and here is my response log file:

08-09 13:35:51.931 6077-6077/com.example.nasrmohamed.testapi10 D/ques.response: {"data":{"questions_id":55,"created_at":"2018-08-08 14:42:28","updated_at":"2018-08-08 14:42:28","question":"\u0645\u0627\u0647\u0649 \u0627\u0644\u0633\u0644\u0633\u0644\u0629 \u0627\u0644\u0645\u0643\u0648\u0646\u0629 \u0645\u0646 \u0639\u0638\u0627\u0645 \u0648\u063a\u0636\u0627\u0631\u064a\u0641 \u0648\u0627\u0644\u062a\u0649 \u062a\u0645\u062a\u062f \u0645\u0646 \u0627\u0644\u062c\u0645\u062c\u0645\u0629 \u0627\u0644\u0649 \u0627\u0644\u0639\u0635\u0639\u0635\u061f","choice_1":"\u0627\u0644\u0642\u0641\u0635 \u0627\u0644\u0635\u062f\u0631\u0649","choice_2":"\u0627\u0644\u0647\u064a\u0643\u0644 \u0627\u0644\u0639\u0638\u0645\u0649","choice_3":"\u0627\u0644\u0639\u0645\u0648\u062f \u0627\u0644\u0641\u0642\u0631\u0649","type":"multi","lang":"ar"},"code":200}

Upvotes: 0

Views: 215

Answers (4)

user4571931
user4571931

Reputation:

Try this code..

public class Data{

@SerializedName("updated_at")
private String updatedAt;

@SerializedName("question")
private String question;

@SerializedName("questions_id")
private int questionsId;

@SerializedName("choice_2")
private String choice2;

@SerializedName("created_at")
private String createdAt;

@SerializedName("choice_3")
private String choice3;

@SerializedName("type")
private String type;

@SerializedName("lang")
private String lang;

@SerializedName("choice_1")
private String choice1;

public void setUpdatedAt(String updatedAt){
    this.updatedAt = updatedAt;
}

public String getUpdatedAt(){
    return updatedAt;
}

public void setQuestion(String question){
    this.question = question;
}

public String getQuestion(){
    return question;
}

public void setQuestionsId(int questionsId){
    this.questionsId = questionsId;
}

public int getQuestionsId(){
    return questionsId;
}

public void setChoice2(String choice2){
    this.choice2 = choice2;
}

public String getChoice2(){
    return choice2;
}

public void setCreatedAt(String createdAt){
    this.createdAt = createdAt;
}

public String getCreatedAt(){
    return createdAt;
}

public void setChoice3(String choice3){
    this.choice3 = choice3;
}

public String getChoice3(){
    return choice3;
}

public void setType(String type){
    this.type = type;
}

public String getType(){
    return type;
}

public void setLang(String lang){
    this.lang = lang;
}

public String getLang(){
    return lang;
}

public void setChoice1(String choice1){
    this.choice1 = choice1;
}

public String getChoice1(){
    return choice1;
}

@Override
public String toString(){
    return 
        "Data{" + 
        "updated_at = '" + updatedAt + '\'' + 
        ",question = '" + question + '\'' + 
        ",questions_id = '" + questionsId + '\'' + 
        ",choice_2 = '" + choice2 + '\'' + 
        ",created_at = '" + createdAt + '\'' + 
        ",choice_3 = '" + choice3 + '\'' + 
        ",type = '" + type + '\'' + 
        ",lang = '" + lang + '\'' + 
        ",choice_1 = '" + choice1 + '\'' + 
        "}";
    }
    }

response data..

public class ResponseData{

@SerializedName("code")
private int code;

@SerializedName("data")
private Data data;

public void setCode(int code){
    this.code = code;
}

public int getCode(){
    return code;
}

public void setData(Data data){
    this.data = data;
}

public Data getData(){
    return data;
}

@Override
public String toString(){
    return 
        "Response{" + 
        "code = '" + code + '\'' + 
        ",data = '" + data + '\'' + 
        "}";
    }
   }

add below dependecy into app level gradle file..

   implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

create retrofit object..

public class ApiClient {
private final static String BASE_URL = "https://api.github.com"; // define your url..

public static ApiClient apiClient;
private Retrofit retrofit = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}
}

api calling..

public interface ApiInterface {
@GET("path")
Call<ResponseData> getUserData();
}

api calling activity..

 Call<ResponseData> dataCall=apiInterface.getUserData();
    dataCall.enqueue(new Callback<ResponseData>() {
        @Override
        public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
            if (response!=null && response.isSuccessful() && response.body()!=null){

            }
            else{
                if (response.errorBody()!=null){
                    ErrorResponse errorResponse=new Gson().fromJson(response.errorBody().toString(),ErrorResponse.class);
                    Log.d("Error data",response.errorBody().toString());
                }
            }
        }

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

        }
    });

Upvotes: 0

Hemaolle
Hemaolle

Reputation: 2158

Looks like the problem is that you return ques from the getQuestion function immediately, but it will take some time for the request to get sent and the response gotten. So when you return ques it hasn't been parsed yet.

You could solve that by passing the getQuestion function a callback object that would be called when the request actually returns. Something like this:

public class ResponseHandler {

    public void HandleReturnedQuestionResponse(QuestionRepsponse ques) {
        // Do stuff when the response has returned 
    }

}


public QuestionResponse getQuestion(ResponseHandler responseHandler) {

    // ...

    StringRequest postRequest = new StringRequest(Request.Method.POST, finalUrl,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {

                        // ... parse reponse ...

                        responseHandler.HandleReturnedQuestionResponse(ques)
                    }
}

// Usage:
getQuestion(new ResponseHandler())

Upvotes: 0

Arbaz.in
Arbaz.in

Reputation: 1558

For Volley just do Simple

Step1:-Create gson object.

Gson gson = new GsonBuilder().create();

Step2:-Filled/Store that response in to your model file

ModelFile modelFile= gson.fromJson(YOUR_RESPONSE_STRING, ModelFile .class);

Step3:- Check data.

put debug and check the response data is filled in your model or not

Upvotes: 0

Diwakar Singh
Diwakar Singh

Reputation: 287

Yes, because "ques" is returning before the setting up the values from the response in it.

Try to set your "ques" values inside this method

              @Override
                public void onResponse(String response) {
                   //set your values here in the adapter
                   }

Upvotes: 1

Related Questions