我刚刚开始学习开发android应用程序,我需要调用一个URL来获取JSON响应。

这是我的java类:-

public class SpeakersFragment extends Fragment {

    List<String> titles;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {



        View view = inflater.inflate(R.layout.fragment_speakers, container, false);

        initData();
        RecyclerView rv = (RecyclerView)view.findViewById(R.id.info_speaker_recycler);
        rv.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);
        RecyclerAdapter adapter = new RecyclerAdapter(getActivity(), titles);
        rv.setAdapter(adapter);

        new GetSpeakersList().execute(URL);

        return view;
    }


public class GetSpeakersList extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {

            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                    Log.v("CatalogClient", server_response);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            Log.e("Response", "" + server_response);


        }
    }

    private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }


当我检查日志时,根本没有响应。我尝试创建一个新项目,如果我在onCreate()而不是onCreateView中调用GetSpeakersList,它将很好地工作。

可以指导我如何使它工作吗?谢谢!

最佳答案

对于持续不断的网络请求,使用AsyncTask可能非常麻烦:尝试使用广受欢迎的,受支持的库进行联网:以下是两个流行的库:

1)Retrofit

要么

2)Volley

10-08 16:49