0

Android 비동기 및 json 데이터 구문 분석을 배우려고합니다. 장소 사용자 유형에 대한 현재 날씨를 표시하기 위해 openweathermap.org API를 사용하고 있습니다. 내 응용 프로그램이 표시했습니다 그러나 날씨 설명, 위도, 경도, 풍속, 현재 온도 등의 모든 세부 정보를 표시하므로 융통성이 없습니다. 모든 문자열을 하나만 써야 재사용 할 수 없으므로 유연하지 않습니다. 내가지도 마커와 함께 현재 온도로 Google지도에서 장소를 표시하고 싶다면이 경우 현재 온도 및 위도와 경도에서 원하는 것을 얻을 수 있어야합니다. 이러한 세부 정보를 별도의 텍스트 필드에 표시하려고합니다. 나는 안드로이드에서 초보자입니다. 제 코드를 살펴보고 해결책과 지침을 제시해주십시오.Android에서 openweather지도 데이터를 개별적으로 표시하는 방법은 무엇입니까?

은 여기 내 JSONWeatherData.java

public class JSONWeatherData { 
    public static String getData(String weatherJson) throws JSONException { 
     String jsonResult = ""; 
     try { 
      JSONObject JsonObject = new JSONObject(weatherJson); 
      String cod = jsonHelperGetString(JsonObject, "cod"); 
      if(cod != null) { 
       if (cod.equals("200")) { 
        jsonResult += jsonHelperGetString(JsonObject, "name") + "\n"; 
        JSONObject sys = jsonHelperGetJSONObject(JsonObject, "sys"); 
        if (sys != null) { 
         jsonResult += jsonHelperGetString(sys, "country") + "\n"; 
        } 
        jsonResult += "\n"; 
        JSONObject coord = jsonHelperGetJSONObject(JsonObject, "coord"); 
        if(coord != null){ 
         String lon = jsonHelperGetString(coord, "lon"); 
         String lat = jsonHelperGetString(coord, "lat"); 
         jsonResult += "Lon: " + lon + "\n"; 
         jsonResult += "Lat: " + lat + "\n"; 
        } 
        jsonResult += "\n"; 
        JSONArray weather = jsonHelperGetJSONArray(JsonObject, "weather"); 
        if(weather != null){ 
         for(int i=0; i<weather.length(); i++){ 
          JSONObject thisWeather = weather.getJSONObject(i); 
          jsonResult += "Weather " + i + ":\n"; 
          jsonResult += jsonHelperGetString(thisWeather, "main") + "\n"; 
          jsonResult += jsonHelperGetString(thisWeather, "description") + "\n"; 
          jsonResult += "\n"; 
         } 
        } 
        JSONObject main = jsonHelperGetJSONObject(JsonObject, "main"); 
        if(main != null){ 
         jsonResult += "temp: " + jsonHelperGetString(main, "temp") + "\n"; 
         jsonResult += "\n"; 
        } 
        JSONObject wind = jsonHelperGetJSONObject(JsonObject, "wind"); 
        if(wind != null){ 
         jsonResult += "Wind Speed: " + jsonHelperGetString(wind, "speed") + "\n"; 
         jsonResult += "\n"; 
        } 
       } 
       else if(cod.equals("404")){ 
        String message = jsonHelperGetString(JsonObject, "message"); 
        jsonResult += "cod 404: " + message; 
       } 
      } else{ 
       jsonResult += "cod == null\n"; 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
      Log.e(TAG, e.getMessage(), e); 
      jsonResult += e.getMessage(); 
     } 
     return jsonResult; 
    } 
    private static String jsonHelperGetString(JSONObject obj, String k){ 
     String v = null; 
     try { 
      v = obj.getString(k); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return v; 
    } 
    private static JSONObject jsonHelperGetJSONObject(JSONObject obj, String k){ 
     JSONObject o = null; 
     try { 
      o = obj.getJSONObject(k); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return o; 
    } 
    private static JSONArray jsonHelperGetJSONArray(JSONObject obj, String k){ 
     JSONArray a = null; 
     try { 
      a = obj.getJSONArray(k); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return a; 
    } 
} 

주요 활동

Public class MainActivity extends Activity { 
    Button btnSubmitCity, btnMap; 
    EditText editCityText; 
    TextView weather_description, current_temp, wind_speed, textViewResult; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     editCityText = (EditText) findViewById(R.id.editCity); 
     btnMap =(Button) findViewById(R.id.mapButton); 
     btnSubmitCity = (Button) findViewById(R.id.submitCity); 
     weather_description = (TextView) findViewById(R.id.weatherDescription); 
     current_temp = (TextView) findViewById(R.id.currentTemp); 
     wind_speed = (TextView) findViewById(R.id.windSpeed); 
     //textViewResult = (TextView)findViewById(R.id.result); 
     textViewResult = (TextView)findViewById(R.id.result); 
     btnMap.setVisibility(View.INVISIBLE); 
     btnMap.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
      } 
     }); 
     btnSubmitCity.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       //editCityText.getText().toString(); 
       //HttpGetTask 
       String cityString = editCityText.getText().toString(); 
       if(TextUtils.isEmpty(cityString)) { 
        Toast.makeText(MainActivity.this, "Enter a place", Toast.LENGTH_LONG).show(); 
        return; 
       } else{ 
        new HttpGetTask(cityString, weather_description).execute(cityString); 
        btnMap.setVisibility(View.VISIBLE); 
       } 
       //String cityString = city.getText().toString(); 
       //new HttpGetTask().execute(); 
       /* 
        new HttpGetTask(
         editCityText.getText().toString(), 
         textViewResult).execute(); 
       */ 
      } 
     }); 
    } 
    private class HttpGetTask extends AsyncTask<String, Void, String> { 
     final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"; 
     private static final String TAG = "HttpGetTask"; 
     String cityName; 
     TextView tvResult; 
     HttpGetTask(String cityName, TextView tvResult){ 
      this.cityName = cityName; 
      this.tvResult = tvResult; 
     } 
     @Override 
     protected String doInBackground(String... params){ 
      InputStream in = null; 
      HttpURLConnection httpUrlConnection = null; 
      String result = ""; 
      try { 
       Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() 
         .appendQueryParameter("q", cityName+",us") // city 
         .appendQueryParameter("mode", "json") // json format as result 
         .appendQueryParameter("units", "imperial") // metric unit 
         .appendQueryParameter("APPID", "Replace with your openweathermap API ID") 
         .build(); 
       URL url = new URL(builtUri.toString()); 
       httpUrlConnection = (HttpURLConnection) url.openConnection(); 
       in = new BufferedInputStream(
         httpUrlConnection.getInputStream()); 
       String data = readStream(in); 
       result = edu.uco.rawal.p6rabina.JSONWeatherData.getData(data); 
      } catch (MalformedURLException exception) { 
       Log.e(TAG, "MalformedURLException"); 
      } catch (IOException exception) { 
       Log.e(TAG, "IOException"); 
      } catch (JSONException e) { 
       Log.e(TAG, e.getMessage(), e); 
       e.printStackTrace(); 
      } finally { 
       if (null != httpUrlConnection) { 
        httpUrlConnection.disconnect(); 
       } 
       if (in != null) { 
        try { 
         in.close(); 
        } catch (final IOException e) { 
         Log.e(TAG, "Error closing stream", e); 
        } 
       } 
     } 
      return result; 
     } 
     @Override 
     protected void onPostExecute(String result) { 
      if (result == null || result == "") { 
       Toast.makeText(MainActivity.this, 
         "Invalid weather data. Possibly a wrong query", 
         Toast.LENGTH_SHORT).show(); 
       return; 
      } else { 
       //btnMap.setVisibility(View.VISIBLE); 
       tvResult.setText(result); 
      } 

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

이 코드 실행 및 출력 현재 날씨하지만, 자사의 모든 것이 하나의 문자열로 연결됩니다 때문 reusuable 없습니다.

답변

2

원하는대로 각 속성에 액세스하고 쉽게 액세스 할 수있게하려면 해당 속성이 포함 된 클래스 Weather을 만드는 것이 좋습니다. json을 구문 분석하기 시작할 때 인스턴스를 만들고 거기에 쓸 수 있습니다. 같은

String lon = jsonHelperGetString(coord, "lon"); 
String lat = jsonHelperGetString(coord, "lat"); 
jsonResult += "Lon: " + lon + "\n"; 
jsonResult += "Lat: " + lat + "\n"; 
... 

변화 STH하기 : 그냥이 대신의 예를 들어

,

Weather aWeather = new Weather(); 
String lon = jsonHelperGetString(coord, "lon"); 
String lat = jsonHelperGetString(coord, "lat"); 
aWeather.lon = long; 
aWeather.lat = lat; 
... 
return aWeather; 

이 onPostExcute (날씨 날씨)로 반환 형식 onPostExcute (문자열 문자열)을 변경하는 것을 잊지 마십시오;

+0

개인 클래스 HttpGetTask는 AsyncTask 을 확장하는 것은 어떻습니까? 나는 그것을 바꿀 필요가 있니? 조금 더 자세히 설명해 주시겠습니까? 나는 지난 2-3 주 동안 나 자신을 서서히 배우기 때문에 지식이 제한되어 있습니다. – robinleathal

+1

나는 모든 것을 설명 할 수 없다하지만 난 당신에게 달콤한 부분을 제공하기 위해 최선을 다할 것입니다 : HttpGetTask을 AsyncTask를 <문자열, 무효, 날씨> { 재정의 날씨 doInBackground 보호 (무효 ... PARAMS) { // 프로세스를 확장 구문 분석 대신 } 재정 보호 무효 onPostExecute (날씨 응답) { 가 // 이제} 여기 을 응답의 정보를 조작 할 수있는 날씨 객체를 반환 } // 기본적으로 당신을 잘못된 형식 죄송합니다 AsyncTask (세 번째 매개 변수)에서 AsyncTask

관련 문제