android - Cannot find symbol getActivity()? -


i learning android udacity's course on developing android apps.

in show how develop weather app, stuck in code add code changing temperature units.

my question why can't use getactivity() method in following code:

its in first line of first function.

class fetchweathertask extends asynctask<string ,void,string []> {      public string formathighlows(double high, double low) {         sharedpreferences sharedprefs=preferencemanager.getdefaultsharedpreferences(getactivity());         string unittype=sharedprefs.getstring(getstring(r.string.pref_units_key),getstring(r.string.pref_units_metric));         if(unittype.equals(getstring(r.string.pref_units_imperial)))         {             high=(high*1.8)+32;             low=(low*1.8)+32;         }         else if(!unittype.equals(getstring(r.string.pref_units_metric)))         {             toast.maketext(getactivity(),"invalid unit",toast.length_short).show();         }         long roundedhigh = math.round(high);         long roundedlow = math.round(low);         string str= roundedhigh+"/"+roundedlow;         return str;      }     @override     protected string [] doinbackground(string []params)      {  httpurlconnection urlconnection = null;         bufferedreader reader = null;          // contain raw json response string.         string forecastjsonstr = null;         string format="json";         string units="metric";         int numdays=7;         try {              final string forecast_base_url="http://api.openweathermap.org/data/2.5/forecast/daily?";             final string query_param="q";             final string format_param="mode";             final string units_param="units";             final string days_param="cnt";             uri builturi=uri.parse(forecast_base_url).buildupon()                     .appendqueryparameter(query_param,params[0])                     .appendqueryparameter(format_param,format)                     .appendqueryparameter(units_param,units)                     .appendqueryparameter(days_param,integer.tostring(numdays))                     .build();             url url = new url(builturi.tostring());                      http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7             urlconnection = (httpurlconnection) url.openconnection();             urlconnection.setrequestmethod("get");             urlconnection.connect();              // read input stream string             inputstream inputstream = urlconnection.getinputstream();             stringbuffer buffer = new stringbuffer();             if (inputstream == null) {                 // nothing do.                 return null;             }             reader = new bufferedreader(new inputstreamreader(inputstream));              string line;             while ((line = reader.readline()) != null) {                 // since it's json, adding newline isn't necessary (it won't affect parsing)                 // make debugging *lot* easier if print out completed                 // buffer debugging.                 buffer.append(line + "\n");             }              if (buffer.length() == 0) {                 // stream empty.  no point in parsing.                 return null;             }             forecastjsonstr = buffer.tostring();         } catch (ioexception e) {             log.e("placeholderfragment", "error ", e);             // if code didn't weather data, there's no point in attemping             // parse it.             return null;         } finally{             if (urlconnection != null) {                 urlconnection.disconnect();             }             if (reader != null) {                 try {                     reader.close();                 } catch (final ioexception e) {                     log.e("placeholderfragment", "error closing stream", e);                 }             }         }          try         {             return getweatherdatafromjson(forecastjsonstr,numdays);         }         catch(jsonexception e)         {          }         return null;     }     protected void onpostexecute(string[] result) {         /*receives string array doinbackground method. result default returned onpost execute         * , can access arraylist of weather populates listview because have made static.*/         if (result != null) {             mainactivityfragment.weather_adapter.clear();             for(string dayforecaststr : result) {                 mainactivityfragment.weather_adapter.add(dayforecaststr);             }             // new data server.  hooray!         }     }     private string getreadabledatestring(long time){         // because api returns unix timestamp (measured in seconds),         // must converted milliseconds in order converted valid date.         simpledateformat shorteneddateformat = new simpledateformat("eee mmm dd");         return shorteneddateformat.format(time);     }      /**      * prepare weather high/lows presentation.      */       /**      * take string representing complete forecast in json format ,      * pull out data need construct strings needed wireframes.      *      * fortunately parsing easy:  constructor takes json string , converts      * object hierarchy us.      */     private string[] getweatherdatafromjson(string forecastjsonstr, int numdays)             throws jsonexception      {         // these names of json objects need extracted.         final string owm_list = "list";/*it contain weather data 7 days, array*/         /*every element of list has 1 element long array called weather contains weather details of corresponding         day.          */         final string owm_weather = "weather";         final string owm_temperature = "temp";         final string owm_max = "max";         final string owm_min = "min";         final string owm_description = "main";/*this contain weather description main title clear          /*the json object created string contains data in json format*/         jsonobject forecastjson = new jsonobject(forecastjsonstr);         jsonarray weatherarray = forecastjson.getjsonarray(owm_list);          // owm returns daily forecasts based upon local time of city being         // asked for, means need know gmt offset translate data         // properly.          // since data sent in-order , first day         // current day, we're going take advantage of nice         // normalized utc date of our weather.         // doing because have associate date each forecast entry.          time daytime = new time();         daytime.settonow();          // start @ day returned local time. otherwise mess.         // julian day returns number of days have passed since julian period.         int julianstartday = time.getjulianday(system.currenttimemillis(), daytime.gmtoff);          // work exclusively in utc         daytime = new time();          string[] resultstrs = new string[numdays];         for(int = 0; < weatherarray.length(); i++) {             // now, using format "day, description, hi/low"             string day;             string description;             string highandlow;              // json object representing day             jsonobject dayforecast = weatherarray.getjsonobject(i);              // date/time returned long.  need convert             // human-readable, since people won't read "1400356800"             // "this saturday".             long datetime;             // cheating convert utc time, want anyhow             datetime = daytime.setjulianday(julianstartday+i);             day = getreadabledatestring(datetime);              // description in child array called "weather", 1 element long.it contains description of             /*weather corresponding day in form of string*/             /*weatherobject corresponding object of ith day*/             jsonobject weatherobject = dayforecast.getjsonarray(owm_weather).getjsonobject(0);             /*owm_description contains "main" description clear*/             description = weatherobject.getstring(owm_description);              // temperatures in child object called "temp".it contains max , min temperatures             // in double format keys mentioned owm_max , owm_min try not name variables             // "temp" when working temperature.  confuses everybody.             jsonobject temperatureobject = dayforecast.getjsonobject(owm_temperature);             double high = temperatureobject.getdouble(owm_max);             double low = temperatureobject.getdouble(owm_min);              resultstrs[i] = day + " - " + description + " - " +math.round(high)+" / "+math.round(low);          }         return resultstrs;     }  } 

get context , save in member variable of class :

class fetchweathertask extends asynctask<string ,void,string []> { private context mcontext;  public fetchweathertask(context context) {     this.mcontext = context; }  // use context this.mcontext everywhere want 

}

you should call above class using :

new fetchweathertask(context).execute(/* string parameters */); 

Comments