我正在使用Retrofit從api返回響應。來自該響應的數據將被提供給回收者視圖。將數據對象傳遞給回收站視圖時,我會得到一個空指針異常。這是因爲,在設置回收站視圖之前,應用程序不會等待返回響應。無論如何有這個應用程序在繼續之前等待響應?Android Retrofit - 在執行其他代碼之前等待響應?
我試過做同步改造請求,但我仍然得到同樣的問題。我已經嘗試在AsyncTask的onPostExecute方法中調用setupRecyclerView(),但這也不起作用。
public class SearchResultsActivity extends BaseActivity {
// UI
private Toolbar toolbar;
private SearchView searchbox;
private RecyclerView rvResults;
// Business Logic
private String searchQuery;
public Response response;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
searchQuery = getSearchQuery();
setupToolbar(searchQuery);
searchForProduct(searchQuery);
}
private void setupRecyclerView() {
rvResults = (RecyclerView) findViewById(R.id.rvResults);
rvResults.setHasFixedSize(true);
rvResults.setLayoutManager(new LinearLayoutManager(activityContext));
ResultAdapter adapter = new ResultAdapter(response.getResults());
rvResults.setAdapter(adapter);
}
private void setupToolbar(String query) {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
}
private void searchForProduct(String query) {
new SearchZaposTask().execute("e");
}
private String getSearchQuery() {
String query = "";
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
}
return query;
}
public class SearchZaposTask extends AsyncTask<String, Void, Response> {
@Override
protected Response doInBackground(String... params) {
RestAdapter retrofit = new RestAdapter.Builder()
.setEndpoint(Constants.BASE_URL)
.build();
ZapposAPI api = retrofit.create(ZapposAPI.class);
return api.searchZappos(searchQuery);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Response searchresponse) {
super.onPostExecute(searchresponse);
//Toast.makeText(activityContext,response.getResults().get(0).getProductName(),Toast.LENGTH_LONG).show();
response = searchresponse;
setupRecyclerView();
}
}
}
編輯:添加ZapposAPI爲@tmalseed看
public interface ZapposAPI {
@GET("/mobileapi/v1/search?")
Response searchZappos(@Query("term") String query);
@GET("/mobileapi/v1/search?")
void searchZapos(@Query("term") String query, Callback<Response> responseCallback);
@GET("https://zappos.amazon.com/mobileapi/v1/product/asin/{asin}")
Asin searchByAsin(@Path("asin") String asin);
}
由於一些奇怪的原因,來電setupRecyclerView將無法正常工作。我有類似的問題,而如果我從onBacakGround()調用此相同的函數調用工作正常。專家對此問題需要更多見解!我切換到凌空,我沒有面對這個問題!如果它適合你的需求,也許你想射門射門! – k2ibegin
您可以使用改裝而不使用asyncSk。這可能是更容易的任務。按照我的github回購:https://github.com/manishandroid/RetrofitAndroidExample –
你可以請張貼您的ZapposAPI代碼? –