이번에는 동기화를 진행하여 네트워크를 통한 조회결과를 가져오는 부분이다.


// TODO (1) Create a class called GithubQueryTask that extends AsyncTask<URL, Void, String>
// TODO (2) Override the doInBackground method to perform the query. Return the results. (Hint: You've already written the code to perform the query)
// TODO (3) Override onPostExecute to display the results in the TextView

MainActivity 에 inner class로 GithubQueryTask를 추가
GithubQueryTask의 doInBackground method에서 쿼리를 날리고 결과를 받는다.

GithubQueryTask의 onPostExecute method에서 가져온 결과를 TextView에 보여준다.


import android.os.AsyncTask;

...

     // TODO (1) Create a class called GithubQueryTask that extends AsyncTask<URL, Void, String>
    public class GithubQueryTask extends AsyncTask<URL, Void, String> {

        // TODO (2) Override the doInBackground method to perform the query. Return the results. (Hint: You've already written the code to perform the query)
        @Override
        protected String doInBackground(URL... params) {
            URL searchUrl = params[0];
            String githubSearchResults = null;
            try {
                githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return githubSearchResults;
        }


        // TODO (3) Override onPostExecute to display the results in the TextView
        @Override
        protected void onPostExecute(String githubSearchResults) {
            if (githubSearchResults != null && !githubSearchResults.equals("")) {
                mSearchResultsTextView.setText(githubSearchResults);
            }
        }
    }


// TODO (4) Create a new GithubQueryTask and call its execute method, passing in the url to query

makeGithubSearchQuery 에서 쿼리를 날릴 때 변경한 GithubQueryTask를 사용하도록 한다.(기존것은 주석처리)

//        String githubSearchResults = null;
//        try {
//            githubSearchResults = NetworkUtils.getResponseFromHttpUrl(githubSearchUrl);
//            mSearchResultsTextView.setText(githubSearchResults);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // TODO (4) Create a new GithubQueryTask and call its execute method, passing in the url to query
        new GithubQueryTask().execute(githubSearchUrl); 


App을 실행시켜서 'queen'이라는 단어로 쿼리를 날리면

먼저 url을 화면에 보여주고 잠시 후에 쿼리 결과가 나타난다.


네트워크를 통한 요청을 했을 때 응답을 받을 때까지 대기하도록 해야하기 때문임.

응답받기전에 결과를 처리하려고 한 T02.04는 에러가 날 수 밖에 없음.

728x90
BLOG main image
"그게 뭐 어쨌다는 거냐?" 늘 누가 나에게 나에대한 말을할 때면 이말을 기억해라. by nobang

카테고리

nobang이야기 (1933)
Life With Gopro (7)
Life With Mini (79)
Diary (971)
너 그거 아니(do you know) (162)
난 그래 (159)
Study (290)
속지말자 (10)
Project (34)
Poem (15)
Song (0)
Photo (113)
낙서장 (45)
일정 (0)
C.A.P.i (2)
PodCast (0)
nobang (27)
고한친구들 (4)
recieve (0)
History (0)
android_app (2)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

Total :
Today : Yesterday :