raginggoat
raginggoat

Reputation: 3600

Android JSON Issue

I have an activity that allows the user to enter a zip code or city to get weather info for. They are then taken to another activity that displays the info. This works ok except if you go back to the first activity to put in a different zip code or city. When you put another location in and go to the second activity to show the weather info for the new location, it pulls the info for the first location instead. For example, I put in a location and then go to the second activity and it shows the temp as 64 and the humidity as 88%. I then go back to the first activity and input a new location and go to the second activity, It still pulls the info for the first location so it shows 64 and 88% again. Any suggestions?

Here is my code.

First Activity:

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

Second Activity:

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

Upvotes: 0

Views: 132

Answers (2)

Steve Benett
Steve Benett

Reputation: 12933

The problem is that your List in your Weather class is only initialized once, because it is static.

This is what happens:

  1. You pass the first url to the second Activity via Intent.
  2. The Activity and the static ArrayList will be instantiated.
  3. Your parser fills the ArrayList (2 elements)
  4. You go back to the first Activity
  5. A new Url will be passed to the second Activity
  6. The ArrayList will NOT be instantiated new!

You parse the new JSON from the new url response. The parser adds two elements to the ArrayList. Now you can check that there are 4 elements in it.

Because you read the list like this:

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

Only the first two elements will be set to the TextViews, which are the values from the first url.

You can avoid this by simply creating the ArrayList in onCreate(). Or don't make the AsyncTask a static inner class. This way you don't have to declare your fields of the Activity as static.

Upvotes: 1

ayon
ayon

Reputation: 2180

Try removing the SetonEditorActionListener part of your first activity , see if it works correctly. Your code seems good. Try printing log of the value that is being passed to second Activity. There's an small issue, I think you should parse the JSON in onPostExecute method , because you may get Window Leak error if JSONException occurs.Hope it helps.

Upvotes: 0

Related Questions