2013-10-16 29 views
0

我有一項活動,允許用戶輸入郵政編碼或城市來獲取天氣信息。然後他們被帶到另一個顯示信息的活動。除非您回到第一次放置不同郵政編碼或城市的活動,否則這種方法可以正常工作。當您放置另一個位置並轉到第二個活動以顯示新位置的天氣信息時,它會改爲爲第一個位置提供信息。例如,我放置一個位置,然後進入第二個活動,它顯示溫度爲64,溼度爲88%。然後我回到第一個活動並輸入一個新的位置,然後轉到第二個活動,它仍然會提取第一個位置的信息,以便再次顯示64和88%。有什麼建議麼?Android JSON問題

這是我的代碼。

第一項活動:

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.KeyEvent; 
import android.view.View; 
import android.view.inputmethod.EditorInfo; 
import android.view.inputmethod.InputMethodManager; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.TextView.OnEditorActionListener; 

public class WeatherLocation extends Activity 
{ 
    EditText locationText; 
    TextView label; 
    Button getWeather; 
    String enteredText; 
    String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=%s&format=json&num_of_days=5&key=37a5fj42xpyptvjgkhrx5rwu"; 
    String newURL; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.weatherlocation); 

     locationText = (EditText) findViewById(R.id.locationText); 
     label = (TextView) findViewById(R.id.label); 
     getWeather = (Button) findViewById(R.id.showWeather); 

     locationText.setText("Current Location"); 

     locationText.setOnEditorActionListener(new OnEditorActionListener() 
     { 
      @Override 
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
      { 
       boolean handled = false; 
       if (actionId == EditorInfo.IME_ACTION_DONE) 
       { 
        enteredText = locationText.getText().toString(); 
        enteredText = enteredText.replaceAll(" ", "+"); 
        System.out.println(enteredText); 

        // hide the virtual keyboard 
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 
               InputMethodManager.RESULT_UNCHANGED_SHOWN); 

        newURL = String.format(url, enteredText); 
        System.out.println("Formatted URL: " + newURL); 
        handled = true; 
       } 

       return handled; 
      } 
     }); 

     getWeather.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       Intent weather = new Intent(WeatherLocation.this, Weather.class); 
       weather.putExtra("INTENT_KEY_URL", newURL); 
       startActivity(weather); 
      } 
     }); 
    } 
} 

次活動:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.ArrayList; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.content.Intent; 
import android.graphics.Color; 
import android.graphics.Typeface; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.DisplayMetrics; 
import android.util.Log; 
import android.widget.TextView; 

public class Weather extends WeatherLocation 
{ 
    static TextView currentTemp; 
    static TextView humidityText; 

    static ArrayList<String> values = new ArrayList<String>(); 
    static String url; 
    static String fahr; 
    static String humidity; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.weather); 

     Intent intent = getIntent(); 
     url = intent.getStringExtra("INTENT_KEY_URL"); 

     Typeface kfb = Typeface.createFromAsset(getAssets(), "FranklinGothicStd-ExtraCond.otf"); 

     DisplayMetrics dm = new DisplayMetrics(); 
     getWindowManager().getDefaultDisplay().getMetrics(dm); 
     double x = Math.pow(dm.widthPixels/dm.xdpi, 2); 
     double y = Math.pow(dm.heightPixels/dm.ydpi, 2); 
     double screenInches = Math.sqrt(x + y); 

     float tempTextSize = 0; 
     float statsTextSize = 0; 

     if(screenInches < 4) 
     { 
      tempTextSize = 48; 
      statsTextSize = 24; 
     } 
     else if(screenInches < 7) 
     { 
      tempTextSize = 60; 
      statsTextSize = 30; 
     } 
     else if(screenInches < 10) 
     { 
      tempTextSize = 72; 
      statsTextSize = 36; 
     } 
     else 
     { 
      tempTextSize = 120; 
      statsTextSize = 60; 
     } 

     currentTemp = (TextView) findViewById(R.id.currentTemp); 
     currentTemp.setTypeface(kfb); 
     currentTemp.setTextColor(Color.WHITE); 
     currentTemp.setTextSize(tempTextSize); 

     humidityText = (TextView) findViewById(R.id.humidityText); 
     humidityText.setTypeface(kfb); 
     humidityText.setTextColor(Color.WHITE); 
     humidityText.setTextSize(statsTextSize); 

     new ParseJSON().execute(); 
    } 

    public static class JSONParser 
    { 
     static InputStream is = null; 
     static JSONObject jObj = null; 
     static String json = ""; 

     // constructor 
     public JSONParser() 
     { 

     } 

     public JSONObject getJSONFromUrl(String jsonUrl) 
     { 
      // Making HTTP request 
      try 
      { 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(jsonUrl); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      } 
      catch (UnsupportedEncodingException e) 
      { 
       e.printStackTrace(); 
      } 
      catch (ClientProtocolException e) 
      { 
       e.printStackTrace(); 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 

      try 
      { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) 
       { 
        sb.append(line + "\n"); 
       } 
       is.close(); 
       json = sb.toString(); 
      } 
      catch (Exception e) 
      { 
       Log.e("Buffer Error", "Error converting result " + e.toString()); 
      } 

      // try to parse the string to a JSON object 
      try 
      { 
       jObj = new JSONObject(json); 
      } 
      catch (JSONException e) 
      { 
       Log.e("JSON Parser", "Error parsing data " + e.toString()); 
      } 

      // return JSON String 
      return jObj; 
     } 
    } 

    public static class ParseJSON extends AsyncTask<Void,Void,ArrayList> 
     { 
     @Override 
     protected void onPreExecute() 
     { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 

     } 

     @Override 
     protected ArrayList doInBackground(Void... params) 
     { 
      JSONParser jParser = new JSONParser(); 

      // get json from url here 
      JSONObject json = jParser.getJSONFromUrl(url); 

      try 
      { 
       JSONObject data = new JSONObject(json.getString("data")); 
       JSONArray currentConditions = data.getJSONArray("current_condition"); 
       JSONArray weather = data.getJSONArray("weather"); 

       JSONObject temp = currentConditions.getJSONObject(0); 
       fahr = temp.getString("temp_F"); 
       humidity = temp.getString("humidity"); 

       values.add(fahr); 
       values.add(humidity); 
      } 
      catch(Exception e) 
      { 
       e.getMessage().toString(); 
      } 
      // return fahr; 
      return values; 
     } 


     @Override 
     protected void onPostExecute(ArrayList result) 
     { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 

      currentTemp.setText(result.get(0).toString() + "\u00B0F"); 
      humidityText.setText("Humidity: " + result.get(1).toString() + "%"); 
     } 
     } 
} 
+1

您是否嘗試登出'url'並查看是否正確的值被傳遞給第二個活動? 'Log.d(「Url」,url);' –

+0

我實際上在我發佈這個問題後添加了。正確的網址正在被傳遞。 – raginggoat

回答

1

問題是您的Weather類中的List僅初始化一次,因爲它是靜態的。

這是發生了什麼:

  1. 你可以通過意圖通過第一URL到第二活動。
  2. Activity和靜態ArrayList將被實例化。
  3. 你的解析器填充的ArrayList(2元)
  4. 你回到第一個活動
  5. 一個新的URL將被傳遞到第二活動
  6. ArrayList的將不能被實例化新!

您從新的url響應中解析新的JSON。解析器將兩個元素添加到ArrayList。現在你可以檢查它裏面有4個元素。

因爲你讀的名單如下:

currentTemp.setText(result.get(0).toString() + "\u00B0F"); 
    humidityText.setText("Humidity: " + result.get(1).toString() + "%"); 

只有前兩個元素將被設置爲TextViews,這是從第一URL的值。

您可以通過簡單地在onCreate()中創建ArrayList來避免這種情況。或者不要讓AsyncTask成爲一個靜態的內部類。這樣您就不必將活動的字段聲明爲靜態。

0

嘗試刪除您的第一個活動的SetonEditorActionListener部分,看看它是否工作正常。你的代碼看起來不錯。嘗試打印正在傳遞給第二個活動的值的日誌。有一個小問題,我認爲你應該解析onPostExecute方法中的JSON,因爲如果發生JSONException,你可能會得到Window Leak錯誤。希望它有幫助。