Android Studio java.net.MalformedURLException: Protocol not found: -


i working on sunshine app udacity tutorials. somewhere on lesson2. when try run feature of app errors:

04-29 12:21:13.311  22025-22424/name.company.sunshine.app e/fetchweathertask﹕ error     java.net.malformedurlexception: protocol not found: "http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7             @ java.net.url.<init>(url.java:176)             @ java.net.url.<init>(url.java:125)             @ name.company.sunshine.app.forecastfragment$fetchweathertask.doinbackground(forecastfragment.java:144)             @ name.company.sunshine.app.forecastfragment$fetchweathertask.doinbackground(forecastfragment.java:101)             @ android.os.asynctask$2.call(asynctask.java:288)             @ java.util.concurrent.futuretask.run(futuretask.java:237)             @ android.os.asynctask$serialexecutor$1.run(asynctask.java:231)             @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1112)             @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:587)             @ java.lang.thread.run(thread.java:841) 04-29 12:21:13.321  22025-22025/name.company.sunshine.app d/abslistview﹕ unregisterirlistener() called 04-29 12:21:13.321  22025-22025/name.company.sunshine.app e/viewrootimpl﹕ senduseractionevent() mview == null  

line 144

 url url = new url(builturi.tostring()); 

i provide entire class if need it.

and else, have in manifest

<uses-permission android:name="android.permission.internet" />  

but when install app never asks permission.

this file :

package name.company.sunshine.app;  import android.net.uri; import android.os.asynctask; import android.os.bundle; import android.support.v4.app.fragment; import android.text.format.time; import android.util.log; import android.view.layoutinflater; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.arrayadapter; import android.widget.listview;  import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject;  import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.url; import java.text.simpledateformat; import java.util.arraylist; import java.util.arrays; import java.util.list;  /**  * placeholder fragment containing simple view.  */ public class forecastfragment extends fragment {      private arrayadapter<string> mforecastadapter;      public forecastfragment() {      }       @override     public void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         sethasoptionsmenu(true);     }       @override     public void oncreateoptionsmenu(menu menu,menuinflater inflater) {         inflater.inflate(r.menu.forecastfragment, menu);     }      @override     public boolean onoptionsitemselected(menuitem item) {         // handle action bar item clicks here. action bar         // automatically handle clicks on home/up button, long         // specify parent activity in androidmanifest.xml.         int id = item.getitemid();          if(id == r.id.action_refresh){          fetchweathertask weathertask =   new fetchweathertask();             weathertask.execute("94043");             return true;         }          return super.onoptionsitemselected(item);     }      @override     public view oncreateview(layoutinflater inflater, viewgroup container,                              bundle savedinstancestate) {         view rootview = inflater.inflate(r.layout.fragment_main, container, false);          // these 2 need declared outside try/catch         // can closed in block.          string forecastarray[]  = {                 "today-sunny-88/63",                 "tuesday-foggy-14/32",                 "wednesday-cloudy-22/33"         };           list<string> weekforecast = new arraylist<string>(                 arrays.aslist(forecastarray));           mforecastadapter = new arrayadapter<string>(getactivity(),r.layout.list_item_forecast,r.id.list_item_forecast_textview,weekforecast);           listview listview = (listview) rootview.findviewbyid(r.id.listview_forecast);         listview.setadapter(mforecastadapter);          return rootview;     }      public class fetchweathertask extends asynctask<string, void, string[]> {          private final string log_tag = fetchweathertask.class.getsimplename();          @override         protected string[] doinbackground(string... params) {              //if there's no zip code, there's nothing up. verify size of params             if(params.length == 0){                 return null;             }              // these 2 need declared outside try/catch             // can closed in block.             httpurlconnection urlconnection = null;             bufferedreader reader = null;              // contain raw json response string.             string forecastjsonstr = null;              string format = "json";             string units = "metric";             int numdays = 7;              try {                 // construct url openweathermap query                 // possible parameters avaiable @ owm's forecast api page, @                 // http://openweathermap.org/api#forecast                 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();                  log.v(log_tag,"built uri"+builturi.tostring());                  url url = new url(builturi.tostring());                  // create request openweathermap, , open connection                 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(log_tag, "error ", e);                 // if code didn't weather data, there's no point in attemping                 // parse it.                 return null;             } {                 if (urlconnection != null) {                     urlconnection.disconnect();                 }                 if (reader != null) {                     try {                         reader.close();                     } catch (final ioexception e) {                         log.e(log_tag, "error closing stream", e);                     }                 }             }              try{                 return getweatherdatafromjson(forecastjsonstr,numdays);             } catch (jsonexception e){                 log.e(log_tag,e.getmessage(),e);                 e.printstacktrace();             }             return null;         }          /* date/time conversion code going moved outside asynctask later,         * convenience we're breaking out own method now.                 */         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.          */         private string formathighlows(double high, double low) {             // presentation, assume user doesn't care tenths of degree.             long roundedhigh = math.round(high);             long roundedlow = math.round(low);              string highlowstr = roundedhigh + "/" + roundedlow;             return highlowstr;         }          /**          * 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";             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";              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.              time daytime = new time();             daytime.settonow();              // start @ day returned local time. otherwise mess.             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.                 jsonobject weatherobject = dayforecast.getjsonarray(owm_weather).getjsonobject(0);                 description = weatherobject.getstring(owm_description);                  // temperatures in child object called "temp".  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);                  highandlow = formathighlows(high, low);                 resultstrs[i] = day + " - " + description + " - " + highandlow;             }              (string s : resultstrs) {                 log.v(log_tag, "forecast entry: " + s);             }             return resultstrs;          }     }  } 

now don t have error anymore after deleting "/" ", line not being printed

for (string s : resultstrs) {                     log.v(log_tag, "forecast entry: " + s);                 } 

probably fails connect or something. can't see in logcat reason .

the issue escaping " before start of url , considering part of url. since "http not valid protocol , valid values http https ftp etc.

final string forecast_base_url =  "\"http://api.openweathermap.org/data/2.5/forecast/daily?";  

should

final string forecast_base_url ="http://api.openweathermap.org/data/2.5/forecast/daily?"; 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -