2017-08-26 24 views
0

這是我嘗試使用的完整代碼片段。我使用AQuery來獲取json。但我有一個問題。 JsonObject,JsonObject ...始終爲空。我嘗試了「郵遞員」的URL,它返回了我需要的JSON。問題是 1.我將JSONObject改爲String,並且得到了該文件。這怎麼可能。 2.我聽說過Retrofit。我閱讀所有的文檔,但我不明白..根據誰使用改造他們說改造比AQuery更好。我如何將此代碼更改爲Retrofit? 3.它是AQueryproblem或我的代碼的問題AQuery JSONObject null

謝謝。

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

回答

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

然後你需要創建一個改造實例

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