2015-11-26 28 views
1

我想从API检索天气数据作为JSON,但它不起作用。如何将天气数据(例如5天预报)转换为文本视图?如何检索json中的天气数据[android]

我的代码如下,但我需要以某种方式适应它传递JSON 5天天气预报并将其放入文本视图。

package mytweets.mytweets; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.json.JSONArray; 
import org.json.JSONObject; 
import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Base64; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 


public class MytweetsActivity extends Activity { 

    // we are reading weathe 

    final String URL `enter code here`="http://api.openweathermap.org/data/2.5/forecast/daily?q,gb&mode=json&units=metric&cnt=5&APPID=xxxxxxxxxxxxxxxx"; 

    final String Consumer_Key = "mPfkAwVuuiVYeuZWdHAMzQ"; // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new 
    final String Consumer_Secret = "bkmiQqellGg9jnJFj41E8zukYSNk0FX1W7v1nU376rE"; // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new 

    JSONArray tweets = null; //an array of tweets 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_mytweets); 

     Button btn_token = (Button)findViewById(R.id.get_token); 
     btn_token.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       new GetTokenTask().execute(); 
      } 
      }); 

     Button btn_feed = (Button)findViewById(R.id.get_tweets); 
     btn_feed.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       TextView txt_token = (TextView)findViewById(R.id.txt_token); 
       String token = txt_token.getText().toString(); 
       new GetTweetsTask().execute(token, URL); 
      } 
      }); 
    } 

    protected class GetTokenTask extends AsyncTask<Void, Void, String> { // the class extends AsynTask in order to run as a thread in the background 

     @Override 
     protected String d  
      try { 
        DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
        HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token"); //asks for a token 

        String apiString = Consumer_Key + ":" + Consumer_Secret; 
        String authorization = "Basic " + Base64.encodeToString(apiString.getBytes(), Base64.NO_WRAP); // twitter ants the authorization in bytes 

        httppost.setHeader("Authorization", authorization); 
        httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); 
        httppost.setEntity(new StringEntity("grant_type=client_credentials")); 

        InputStream inputStream = null; 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 

        inputStream = entity.getContent(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); // reading the input stream 
        StringBuilder sb = new StringBuilder(); 

        String line = null; 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line + "\n"); 
        } 

        return sb.toString(); 
       }catch (Exception e){ 
        Log.e("GetTokenTask", "Error:" + e.getMessage()); 
        return null; 
       } 
      } 

      @Override 
      protected void onPostExecute(String jsonText){ 
       try { 
        JSONObject root = new JSONObject(jsonText); 
        String bearer_token = root.getString("access_token"); 

        TextView txt = (TextView)findViewById(R.id.txt_token); 
        txt.setText(bearer_token);  
       }catch (Exception e){ 
        Log.e("GetTokenTask", "Error:" + e.getMessage()); 
       } 
      } 
     } 

     protected class GetTweetsTask extends AsyncTask<String, Void, String> { //the class is run as a thread in the background to get the tweets 

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

       try { 
        DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
        HttpGet httpget = new HttpGet(params[1]); 
        httpget.setHeader("Authorization", "Bearer " + params[0]); 

        httpget.setHeader("Content-type", "application/json"); //json content type 

        InputStream inputStream = null; 
        HttpResponse response = httpclient.execute(httpget); 
        HttpEntity entity = response.getEntity(); 

        inputStream = entity.getContent(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
        StringBuilder sb = new StringBuilder(); 

        String line = null; 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line + "\n"); 
        } 
        return sb.toString(); 
       }catch (Exception e){ 
        Log.e("GetFeedTask", "Error:" + e.getMessage()); 
        return null; 
       } 
      } 

      @Override 
      protected void onPostExecute(String jsonString){ 
       try { 
        TextView txt_tweets = (TextView)findViewById(R.id.txt_tweets); 

        JSONObject forecastJson = new JSONObject(jsonString); 
        JSONArray forecastArray = forecastJson.getJSONArray("list"); 

        String txt = ""; 

        int i; 

        double minTemp, maxTemp; 

        // we are going to parse the json string and only display created_at and text. You can decide to display more objects if you want. 
        for (i=0;i<tweets.length();i++) 
        { 

          JSONObject dailyForecast = forecastArray.getJSONObject(i); 
          JSONObject tempObject = dailyForecast.getJSONObject("temp"); 
          minTemp = tempObject.getDouble("min"); 
          maxTemp = tempObject.getDouble("max"); 
          //add these minTemp and maxTemp to array or the 
          //way you want to use 


         txt_tweets.setText(txt); 

         txt += "------------\n"; //separtors, check the output 


        } 



       }catch (Exception e){ 
        Log.e("GetFeedTask", "Error:" + e.getMessage()); 
       } 
      } 
     } 

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

     }  

    } 
+0

什么不行?什么是你得到的错误信息? – Jens

+0

嘿谢谢你的回复,基本上我希望5天的预测能够在文本视图中显示出来,叫做文本推文。到目前为止,我只是试图从JSOn开放天气api获取温度,然后一旦这个工作,我可以实施全天5天的天气预报。因此,请你或其他人帮助我解决如何解析和阅读json从openweather api到应用程序。谢谢 – Lewis

+0

是的,我试图帮助。但是你的问题太广泛了。当你运行你的代码时会发生什么?你卡在哪里? – Jens

回答

1

这是气象数据的JSON格式:

city: { 
id: 2643743, 
name: "London", 
coord: { 
lon: -0.12574, 
lat: 51.50853 
}, 
country: "GB", 
population: 0 
}, 
cod: "200", 
message: 0.0268, 
cnt: 5, 
list: [ 
{ 
dt: 1448535600, 
temp: { 
day: 8.58, 
min: 8.58, 
max: 9.18, 
night: 9.18, 
eve: 8.58, 
morn: 8.58 
}, 
pressure: 1025.14, 
humidity: 95, 
weather: [ 
{ 
id: 500, 
main: "Rain", 
description: "light rain", 
icon: "10d" 
} 
], 
speed: 3.67, 
deg: 224, 
clouds: 92, 
rain: 0.35 
}, 
{}, 
{}, 
{}, 
{} 
] 

我们使用气象数据(例如分钟,最高温度),你需要如下解析:

JSONObject forecastJson = new JSONObject(jsonString); 
JSONArray forecastArray = forecastJson.getJSONArray("list"); 
double minTemp, maxTemp; 
for(int i = 0; i < forecastArray.length(); i++) { 
    JSONObject dailyForecast = forecastArray.getJSONObject(i); 
    JSONObject tempObject = dailyForecast.getJSONObject("temp"); 
    minTemp = tempObject.getDouble("min"); 
    maxTemp = tempObject.getDouble("max"); 
    //add these minTemp and maxTemp to array or the 
    //way you want to use 
} 

如果您有进一步的疑问,请告诉我。

+0

感谢您的帮助,我必须失去它仍然不起作用,我需要以某种方式使得_weather buttion执行流程。我已经添加了你在string = text“”下建议的代码“” – Lewis

+0

非常感谢你的帮助,所以我想这样的JSONObject c = tweets.getJSONObject(i); txt + =“------------ \ n”; // separtors,检查输出 txt + =“temp:”+ c.getString(“temp”)+“\ n”; //获取天气温度 – Lewis

+0

如果您详细说明您面临的问题,那么我可以尝试提供帮助。还有一点,您在代码片段中粘贴了api密钥,绝不会将您的api密钥分享给公共论坛。我编辑并掩盖了这一点。 – Debashis

0

使用数组和对象,并确保你有一个json解析器