我目前正在使用一個AsyncTask,並在doInBackground
方法運行一段代碼,需要處理某些異常。由於doInBackground
方法被覆蓋,所以我不能在方法中添加一個throws子句。我已經插入了一個捕獲異常的try-catch方法,但由於我的方法返回一個Summoner對象,我不得不包含return null;
語句,並且我發現我的代碼仍在執行該語句。不能添加一個拋出子句重寫的方法,導致我不得不返回null
我對AsyncTask的使用經驗非常有限,所以如果您需要更多信息或者我在此忽略某些內容,請隨時指出。
public class GetSummonerData extends AsyncTask<String, Void, Summoner>
{
@Override
protected void onPreExecute()
{
Button button = (Button) findViewById(R.id.btnSearch);
button.setText("Loading...");
}
@Override
protected Summoner doInBackground(String... asyncParams)
{
try
{
String summonerName = asyncParams[1];
RiotApi api = new RiotApi("api-key");
Map<String, Summoner> summoners = null;
//The following line of code will call the API
summoners = api.getSummonersByName(Region.valueOf(asyncParams[0]), summonerName);
//stage 1
return summoners.get(summonerName);
}
catch (RiotApiException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Summoner result)
{
//stage 2
startNewIntent(result);
}
}
public void startNewIntent(Summoner summoner)
{
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra("summoner", summoner);
startActivity(intent);
}
在階段1,summoners
變量擁有1個召喚者對象。在階段2,onPostExecute
的返回結果等於空。爲什麼即使在try塊中有return語句,也會執行返回null?
你想實現什麼? –
我正在尋找一個解釋,爲什麼它仍然執行返回null語句之後,結果已經在方法的早期返回。 –