我有以下代碼來獲取整數數據計數。 getData(NewsSettings)
方法返回3.當我點擊按鈕,應用程序顯示我No new news found
。Toast在調用方法之前運行
爲什麼它在getData之前運行敬酒?
修訂
我已經加入了完整的onCreate
和getData
方法。當我運行,它讓我No new news found
然後Inside Response
然後Data count = 3
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
assert getSupportActionBar() != null;
getSupportActionBar().setTitle(R.string.action_profile);
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Button button = (Button) findViewById(R.id.buttonBuilder);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newsSettings = new NewsSettings();
newsSettings.setPreferredCity(pref.getString("prefCity", ""));
int dataCount = getData(newsSettings);
if(dataCount > 0)
Toast.makeText(getApplicationContext(), dataCount + " new news found", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "No new news found", Toast.LENGTH_SHORT).show();
}
});
}
private int getData(NewsSettings newsSettings) {
final int[] data = {0};
RequestInterface requestInterface = RequestHelper.getInstance().getRequest();
ServerRequest request = new ServerRequest();
request.setOperation("dataCount");
request.setNewsSettings(newsSettings);
Call <ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback <ServerResponse>() {
@Override
public void onResponse(Call <ServerResponse> call,
retrofit2.Response <ServerResponse> response) {
ServerResponse resp = response.body();
Toast.makeText(getApplicationContext(), "Inside Response", Toast.LENGTH_SHORT).show();
if(resp.getResult().equals(Constants.SUCCESS)) {
data[0] = resp.getNewsSettings().getDataCount();
Toast.makeText(getApplicationContext(), "Data count = " + data[0], Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call <ServerResponse> call, Throwable t) {
Log.d(Constants.TAG,"failed");
Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
return data[0];
}
你嘗試另一種方法調試它? dataCount必須<0才能寫出敬酒「沒有發現新消息」 –
我不相信你。你有沒有證據表明Toast是在getData運行之前發送的? –
你應該把「getData」的代碼,並檢查調試器。這在許多層面似乎都是錯誤的,因爲我認爲你過分簡化了你的代碼,並且這樣做,刪除了錯誤或隱藏了它。順便說一句,只需嘗試「int dataCount = 3;」只是爲了檢查,但我很確定問題是getData方法。 – Feuby