简体   繁体   中英

How to get the description string from the forecast weather array from the openweathermap API?

I'm trying to get the 'description' and 'main' strings from the weather array using the forecast openweathermap api. Unlike the weather api, the forecast has an array of 'list' and within that array, there is another array called 'weather'. I can't seem to get that information as an individual string. I want to be able to display 'clouds' and 'broken clouds' within a TextView

在此处输入图片说明

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();
        }


    }
    }
}

Try using getJsonArray directly to get your "list" value, then you can access the index you want and then access the key you want:

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");

And if you want them all you can juste put the three last lines in a for loop to iterate to go through all the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM