使用ASyncTask <>在Logcat中打印数据出错

时间:2019-02-07 11:52:21

标签: android android-asynctask logcat

我正在尝试使用RiotApi打印从ASyncTask Api获得的一些数据,然后使用Log.d记录数据和Log.i将它们记录在logcat中如果RiotApiException方法引发了printSummonerData()异常。但是,当我运行该应用程序时,它会编译并运行良好,并且我没有得到RiotApiExceptions,但没有记录数据。有人可以帮我弄清楚为什么会这样吗?

PS:我不确定我是否应该首先使用ASyncTask(我是线程,同步和异步任务等的新手),但是我从Android文档中读到的内容我不应该使用网络请求等阻止主UI线程。因此,我认为我应该使用ASyncTask。如果我的假设是错误的,请纠正我。

 public class MainActivity extends AppCompatActivity {

    private final static String API_KEY = "MYKEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new DownloadSummonerData();
    }

    private static class DownloadSummonerData extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... urls) {
            try {
                printSummonerData();
            } catch (RiotApiException e) {
                e.printStackTrace();
                Log.i("LOL","Something went wrong!");
            }
            return null;
        }

        protected void onProgressUpdate(Void... progress) {

        }

        protected void onPostExecute(Void result) {

        }
    }


    private static void printSummonerData() throws RiotApiException {
        ApiConfig config = new ApiConfig().setKey(API_KEY);
        RiotApi api = new RiotApi(config);
        Summoner summoner = api.getSummonerByName(Platform.EUNE, "XmaxUniverse");
        Log.d("LOL","Name: " + summoner.getName());
        Log.d("LOL","Summoner ID: " + summoner.getId());
        Log.d("LOL","Account ID: " + summoner.getAccountId());
        Log.d("LOL","PUUID: " + summoner.getPuuid());
        Log.d("LOL","Summoner Level: " + summoner.getSummonerLevel());
        Log.d("LOL","Profile Icon ID: " + summoner.getProfileIconId());
    }
}

1 个答案:

答案 0 :(得分:1)

您没有启动AsyncTask。做他的

new DownloadSummonerData().execute();

OR

// Assume DownloadSummonerData extends AsyncTask
DownloadSummonerData myAsyncTask= new DownloadSummonerData();

// Execute in parallel
myAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)