I need to use this api :

I wrote the following code:

public class JsonResponse { HttpURLConnection urlConnection ; BufferedReader reader ; String resultJson ; String strJson; private String phone; private String address; private String name; public String get() { try { URL url = new URL("http://search-maps.yandex.ru/v1/?text=Отель&lang=ru_RU&apikey=тут мой Api key"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } resultJson = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } return resultJson;} protected void onPostExecute(String strJson) { onPostExecute(strJson); JSONObject dataJsonObj; String Name; try { dataJsonObj = new JSONObject(strJson); JSONArray objects = dataJsonObj.getJSONArray("features"); JSONObject meta = objects.getJSONObject(Integer.parseInt("CompanyMetaData")); JSONObject phones = meta.getJSONObject("CompanyMetaData.Phones"); String name = meta.getString("name"); String address = meta.getString("address"); String phone = phones.getString("formatted"); } catch (JSONException e) { e.printStackTrace(); } } public String getPhone() { return phone; } public String getName() { return name; } public String getAddress() { return address; } public String getStrJson() { return strJson; } } 

Call to main activity:

 JsonResponse json = new JsonResponse(); Log.d(TAG,"Json:" + json.getStrJson() ); Log.d(TAG,"JsonName:" + json.getName() ); Log.d(TAG,"JsonPhone:" + json.getPhone() ); Log.d(TAG,"JsonAddress:" + json.getAddress() ); 

The logs are null.

  • You have created an instance of the class, but did not call the desired method. Nothing has been done and everything is null . And the request to the network must be done from a non-UI stream. - Yuriy SPb
  • @ ЮрийСПб I do not understand> And the request to the network should be done from a non-UI stream. - Viktoor
  • Use Thread, AsynkTask, IntentService etc. When you try to request a network from the main thread, the application will crash. - Yuriy SPb
  • It’s not very likely that you wrote this code, since without calling get() you want to see the values ​​:) - Eugene Krivenja

1 answer 1

Option A. Multithreading: in this case, the JsonResponse # get () method is rewritten to run, the class itself is either inherited from Thread or we connect the Runnable interface. And in the main activity we are already running this stream. After completion of the execution, you can use the Handler to notify the main thread. Here is a little: a link .

Option B. AsyncTask. Here is the material: link .

Well, on the habre: hub .