2017-03-07 63 views
0

我試圖從天氣陣列中使用預測的openweathermap API獲取'描述'和'主'字符串。與天氣api不同,預測有一個「列表」陣列,在該陣列內還有另一個名爲「天氣」的陣列。我似乎無法將這些信息視爲單個字符串。我希望能夠以一個TextView中顯示「雲」和「雲彩」如何從openweathermap API的預測天氣數組中獲取描述字符串?

enter image description here

public class MainActivity extends AppCompatActivity { 

     EditText cityName; 
     TextView weatherTxt; 
     TextView nameText; 




    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     cityName = (EditText) findViewById(R.id.cityName); 
     weatherTxt = (TextView) findViewById(R.id.weatherTxt); 
     nameText = (TextView) findViewById(R.id.cityNameTxt); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 

     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    public void GetWeather(View view){ 

     Log.i ("city name", cityName.getText().toString()); 

     InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
     mgr.hideSoftInputFromWindow(cityName.getWindowToken(), 0); 

     downloadTask task = new downloadTask(); 
     task.execute("http://api.openweathermap.org/data/2.5/forecast?q=" 
       +cityName.getText().toString()+ 
       "&appid=71aefce4499fe64969286582c7e80ea2"); 


    } 



    public class downloadTask extends AsyncTask<String, Void, String>{ 

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

      String result = ""; 
      URL url; 
      HttpURLConnection urlConnection = null; 

      try { 
       url = new URL(urls[0]); 

       urlConnection = (HttpURLConnection) url.openConnection(); 

       InputStream in = urlConnection.getInputStream(); 

       InputStreamReader reader = new InputStreamReader(in); 

       int data = reader.read(); 

       while (data != -1){ 

        char current = (char) data; 

        result += current; 

        data = reader.read(); 
       } 

       return result; 


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

      return null; 
     } 

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


     try { 

      String mainTxt = ""; 
      String descriptionTxt = ""; 
      String weather = ""; 
      String tempratureTxt = ""; 
      String main = ""; 

      JSONObject jsonObject = new JSONObject(result); 

      JSONObject city = jsonObject.getJSONObject("city"); 
      String name = city.getString("name"); 
      Log.i("name", name); 

      JSONArray list = jsonObject.getJSONArray("list"); 
      JSONObject listObject = list.getJSONObject(0); 



      for (int i =0; i <= 6; i++){ //look through all the list until you reach 7 (i.e. 7 day forecast) 

       JSONObject weatherInfo = listObject.getJSONArray("weather").getJSONObject(0); 
       String weatherMain = weatherInfo.getString("main"); 
       String weatherDescription = weatherInfo.getString("description"); 

       JSONObject mainTemp = listObject.getJSONObject("main"); 
       String temp = mainTemp.getString("temp"); 


       Log.i ("main", weatherMain); 
       Log.i ("description", weatherDescription); 
       Log.i ("temp", temp); 

       weather = weatherMain; 
       main = weatherDescription; 
       tempratureTxt = temp; 

       if (weather != ""){ 

        mainTxt += "Day " +i+ ": " +weather + "\r\n"; 
        descriptionTxt += main + "\r\n"; 
        tempratureTxt += temp + "\r\n"; 

        //Toast.makeText(getBaseContext(), message + " - " 
          // + message,Toast.LENGTH_SHORT).show(); 

       } 


      } 



      //move this inside the while loop if you want to display all week 



      //This displays the weather information in the Activity TextView 
      if (mainTxt != ""){ 

       weatherTxt.setText(mainTxt); 
       descriptionText.setText(descriptionTxt); 
       temperatureText.setText(tempratureTxt); 
       nameText.setText("The Weather in " +name+ " is: "); 



      } 


     } catch (JSONException e) { 


      e.printStackTrace(); 
     } 


    } 
    } 
} 

回答

0

嘗試使用getJsonArray直接拿你的「名單」的價值,那麼你就可以訪問索引你想,然後訪問所需的關鍵:

JsonArray list = jsonObject.getJsonArray("list"); 
JsonObject listObject = list.getJsonObject(0); 
JsonObject weather = listObject.getJsonArray("weather").getJsonObject(0); 
String weatherMain = weather.getString("main"); 
String weatherDesc = weather.getString("description"); 

如果你想他們都可以把探微最後三個行的for循環迭代要經過所有的陣列。

+0

太棒了!已經工作。 唯一的問題是,看起來不行。 我已經更新了我的代碼。有什麼建議麼? – Toby

+0

沒關係。我剛剛移動'JSONObject listObject = list.getJSONObject(0);'進入for循環。 – Toby