0

I've got a class, GetWeather.java, which fetches weather data from an API. It is called from the main activity of my app periodically via a separate thread. The thread hits the GetWeather class and posts the returned data to a TextView.

In either case a System.out.println of the returned data from within the GetWeather class shows that the data is indeed being returned.

Below is GetWeather.java:

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.HttpClient;
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.net.Uri;
import android.util.Log;

public class GetWeather {

    InputStream is = null;

    JSONArray jArray = null;
    JSONObject json_data = new JSONObject();
    String result = "";

    String strTemp = "";
    String strWindSpeed = "";
    String strWindDir = "";
    String strVisibility = "";

    String strPosition = "";

    public static final Uri KEY_121 = Uri.parse("http://api.worldweatheronline.com/free/v1/weather.ashx");
    String strWeatherApiKey = "REMOVED";

    public GetWeather(String Location) {
        strPosition = Location;
    }

    public void returnWeather() {
        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(KEY_121 + "?key="
                    + strWeatherApiKey + "&q=" + strPosition + "&format=json");

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        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();
            result = sb.toString();

        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // parse json data
        try {
            JSONObject object = new JSONObject(result);
            JSONObject weather = object.getJSONObject("data");
            JSONArray current_conditions = weather
                    .getJSONArray("current_condition");
            for (int i = 0; i < current_conditions.length(); i++) {
                JSONObject object1 = (JSONObject) current_conditions.get(i);
                strTemp = object1.getString("temp_C");
                strWindSpeed = object1.getString("windspeedMiles");
                strWindDir = object1.getString("winddir16Point");
                strVisibility = object1.getString("visibility");

                // Testing output
                System.out.println(strTemp);
                System.out.println(strWindSpeed);
                System.out.println(strWindDir);
                System.out.println(strVisibility);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
    }
}

Here is the relevant code from the main activity:

Runnable updateConsoleRunnable = new Runnable() {
    public void run() {
        tvConsole.setMovementMethod(new ScrollingMovementMethod());
        tvConsole.setSelected(true);

        handler.postDelayed(this, TIME_DELAY);

        // Only display weather data while service is enabled
        if (isServiceRunning()) {
            GetWeather weather = new GetWeather(strPosition);
            weather.returnWeather();

            // Weather package
            tvConsole
                    .append("Weather Update\n-------------------\n\nCurrent Temp (C): "
                            + weather.strTemp
                            + "C\n"
                            + "Wind is out of the "
                            + weather.strWindDir
                            + " at "
                            + weather.strWindSpeed
                            + " MPH\n"
                            + "Visibility is "
                            + weather.strVisibility
                            + " miles\n\n");

            // Auto-scroll textview
            // Does not function on Android 4.0+
            final Layout layout = tvConsole.getLayout();
            if (layout != null) {
                int scrollDelta = layout.getLineBottom(tvConsole
                        .getLineCount() - 1)
                        - tvConsole.getScrollY()
                        - tvConsole.getHeight();
                if (scrollDelta > 0)
                    tvConsole.scrollBy(0, scrollDelta);
            }

        }

    }
};

As I mentioned previously, this works as expected in Gingerbread and FroYo, but ICS and JellyBean OS fail to see the variables set by GetWeather. I think, I read somewhere this has something to do with needing an AsyncTask, but I am not able to make-out heads or tails of it.

Advance Thanks

3
  • if you can put any logs please!! May 30, 2013 at 12:10
  • It looks like you might be trying to update the UI from something other than the UI thread? May 30, 2013 at 12:18
  • @ChrisStratton yep. That issue never occurred to me, actually.
    – Sam
    May 30, 2013 at 13:03

2 Answers 2

2

you cannot touch anything in the ui thread from a background thread, to do that use Handlers, initialize your background thread passing it a Handler object. When data arrives use the handler to send a message to the ui. In the ui when the message from the background thread comes, just update the Views.

1

Try to use async task like this,

In your main activity,

public class GetWeather extends AsyncTask<Void, Integer, Void> {



    public GetWeather(Activity activity) {
        this.activity = activity;


        context = activity;
        dialog = new ProgressDialog(context);


    }

    /** progress dialog to show user that the backup is processing. */
    private ProgressDialog dialog;
    /** application context. */
    private Activity activity;
    private Context context;



    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();






    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub


        GetWeather weather = new GetWeather(strPosition);
        weather.returnWeather();


        return null;
    }

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



                     tvConsole
                .append("Weather Update\n-------------------\n\nCurrent Temp (C): "
                        + weather.strTemp
                        + "C\n"
                        + "Wind is out of the "
                        + weather.strWindDir
                        + " at "
                        + weather.strWindSpeed
                        + " MPH\n"
                        + "Visibility is "
                        + weather.strVisibility
                        + " miles\n\n");

        // Auto-scroll textview
        // Does not function on Android 4.0+
        final Layout layout = tvConsole.getLayout();
        if (layout != null) {
            int scrollDelta = layout.getLineBottom(tvConsole
                    .getLineCount() - 1)
                    - tvConsole.getScrollY()
                    - tvConsole.getHeight();
            if (scrollDelta > 0)
                tvConsole.scrollBy(0, scrollDelta);
        }




                     }



  }

And call it like,

new GetWeather(Mainactivity.this).execute();
1
  • Thanks for that. I'll look into this tonight and see if I can merge it into the existing project.
    – Sam
    May 30, 2013 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.