如何从api获取天气数据?

时间:2019-05-19 14:53:26

标签: java android api

我是android的新手。我想创建一个通过api从weather app获取数据的weather app。我编写了api代码。但它无法正常工作,并且也不会在logcat中显示。我添加了JsonObject和jsonPart,但没有显示。首先我尝试在Log中尝试,然后在device中尝试,但它根本没有显示。

    public  class DownloasTask extends AsyncTask<String,Void,String>{
    @Override
    at a 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 = result +current;
                data =reader.read();
               }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            Log.i("Exception"," url failed");
            Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
            return null;
        }

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try{
            JSONObject jsonObject = new JSONObject(result);
            String weatherInfo = jsonObject.getString("weather");
            JSONArray arr = new JSONArray(weatherInfo);
            String message ="";
            for(int i = 0;i<arr.length();i++){
                JSONObject jsonPart =arr.getJSONObject(i);
                String main =jsonPart.getString("main");
                String description =jsonPart.getString("description");
                if(!(main.equals("")) && !description.equals("")){
                    message +=main +": "+description+"\r\n";
                }

                Log.i("main",jsonPart.getString("main"));
                Log.i("description",jsonPart.getString("description"));
            }
            if(!message.equals("")){
                textView2.setText(message);
            }else {
                Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.i("jsonobject", "onPostExecute: ");
            Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
        }
    }
}
       public  void getWeather(View view){
    DownloasTask task = new DownloasTask()
    task.execute("https://openweathermap.org/data/2.5/forecast?q=" + 
        editText.getText().toString() + 
      "&appid=b1b15e88fa797225412429c1c50c122a1");
    InputMethodManager inputMethodManager = 
  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

 inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(),0);

   }

}

0 个答案:

没有答案