0

这是我尝试使用的片段的完整代码。我使用 AQuery 来获取 json。但我有一个问题。JsonObject,JsonObject... 总是为空。我在“邮递员”上尝试了 url,它返回了我需要的 json。问题是 1. 我将 JSONObject 更改为 String 并且我得到了文件。这怎么可能。2. 我听说过改造。我阅读了所有文档,但我无法理解..根据使用 Retrofit 的人的说法,他们说 Retrofit 比 AQuery 更好。如何将此代码更改为 Retrofit?3.是AQuery问题还是我的代码问题

谢谢你。

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;
}
}
4

1 回答 1

0

您必须将此添加到您的应用程序 build.gradle

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

接下来创建一个Webservice.class,例如这样(您不需要授权令牌,只有当您有与令牌相关的调用时)

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);
}

然后你需要创建一个Retrofit 实例

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);

最后调用它

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

在应用架构方面,你可以按照谷歌指示的, https://developer.android.com/topic/libraries/architecture/guide.html

于 2017-08-26T12:14:48.263 回答