androidjsonnetwork-programmingaquery

AQuery JSONObject null


This is the full code of fragment which I am trying to use. I used AQuery to get the json. But I had a problem. The JsonObject,JsonObject... always gets null. I tried the url on "postman" and It returned the json I needed. The question is 1. I changed JSONObject to String and I got the file. How is it possible. 2. I heard about Retrofit. I read all the docs but I couldn't understand ..According to the people who use Retrofit They say Retrofit is better than AQuery. How can I change this code to Retrofit? 3. Is it an AQueryproblem or my code's problem

Thank you.

public class PastQuestionFragment extends Fragment {
AQuery aq = new AQuery(getActivity());
String postUrl = "http://192.168.0.21:3000/SendPastQuestion";

TextView pastQuestion;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) 
inflater.inflate(R.layout.fragment_pastquestion, container, false);
    pastQuestion = (TextView) rootView.findViewById(R.id.pastquestion);


    aq.ajax(postUrl, JSONObject.class, new AjaxCallback<JSONObject>() {
        @Override
        public void callback(String url, JSONObject json, AjaxStatus status) 
{
            if (json != null) {
                Log.d("debug", "json is not null");
                try {
                    pastQuestion.setText(json.getString("pastquestion"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("debug", "json is null");
            }
        }
    });
    return rootView;
}
}

Solution

  • You have to add this to your app build.gradle

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile "com.squareup.retrofit2:converter-gson:2.3.0"
    

    Next create a Webservice.class, like this for example (you don't need the authorization token, only if you have a token associated call)

    public interface WebServices {
    
    @GET("metadata/countries")
    Call<List<Country>> getCountries(@Header("Authorization") String authorization);
    
    @GET("metadata/states") ;; In your case should @POST("SendPastQuestion")
    Call<List<State>> getStates(@Header("Authorization") String authorization);
    }
    

    And then you need to create a Retrofit instance

    Webservice service = new Retrofit.Builder()
                .baseUrl(Codes.V1.getDescription()) ;; In your case should be "http://192.168.0.21:3000/"
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(WebServices.class);
    

    And finally call it

    Response<List<State>> response = services.getStates("Bearer "+token).execute();
    

    In terms of app Architecture, you can follow the one indicated by Google, https://developer.android.com/topic/libraries/architecture/guide.html