java - Why does my content_detail.xml doesn't show the action bar? -


mainactivity.java

package com.example.android.sunshine.app;  import android.os.bundle; import android.support.v7.app.actionbaractivity; import android.view.menu; import android.view.menuitem;   public class mainactivity extends actionbaractivity {      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);         if (savedinstancestate == null) {             getsupportfragmentmanager().begintransaction()                     .add(r.id.container, new forecastfragment())                     .commit();         }     }      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.main, menu);         return true;     }      @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();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             return true;         }            return super.onoptionsitemselected(item);     }  } 

forecastfragment.java

package com.example.android.sunshine.app;  import android.content.intent; 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.adapterview; 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;  /**  * created smanohar on 5/11/2016.  */ public class forecastfragment extends fragment {      private final string log_tag = forecastfragment.class.getsimplename();      arrayadapter<string> mforecastadapter;      public forecastfragment() {     }       public void oncreate(bundle savedinstancestate){         super.oncreate(savedinstancestate);         sethasoptionsmenu(true);     }      public void oncreateoptionsmenu(menu menu, menuinflater inflater){         inflater.inflate(r.menu.forecastfragment, menu);     }      public boolean onoptionsitemselected(menuitem item){         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);          string[] forecastarray = {"today - sunny 88/63",                 "tomorrow - sunny 70/64",                 "sunday - sunny 80/64",                 "monday - sunny 99/70",                 "tuesday - sunny 89/64",                 "wednesday - sunny 88/65",                 "thursday - sunny 99/76",                 "friday - sunny 87/89",                 "saturday - sunny 87/79"         };          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);         listview.setonitemclicklistener(new adapterview.onitemclicklistener() {             @override             public void onitemclick(adapterview<?> parent, view view, int position, long id) {                 string forecast = mforecastadapter.getitem(position);                 intent vieweachweatherintent = new intent(getcontext(),detailactivity.class)                         .putextra(intent.extra_text, forecast);                 startactivity(vieweachweatherintent);                // toast.maketext(getactivity(), forecast, toast.length_short).show();              }         });         return rootview;      }      /* 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;      }    public class fetchweathertask extends asynctask<string, void, string[]> {          private final string log_tag = fetchweathertask.class.getsimplename();          @override         protected string[] doinbackground(string... params) {             // 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;             string apikey = "4fc1fba049dd6070aa4425a94a12fec7";              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"; //                final string apikey = "&appid=" + ;                  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))                         .appendqueryparameter("appid" , apikey)                         .build();                   url url = new url(builturi.tostring());                  log.v(log_tag, "built uri " + 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();                  log.v(log_tag, "forecast json string: " + forecastjsonstr );              } 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;         }       @override      protected void onpostexecute(string[] result) {          if(result != null){              mforecastadapter.clear();              for(string dayforecaststr: result){                  mforecastadapter.add(dayforecaststr);              }           }      }  } } 

detailactivity.java

package com.example.android.sunshine.app;  import android.content.intent; import android.os.bundle; import android.support.v4.app.fragment; import android.support.v7.app.appcompatactivity; import android.view.layoutinflater; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.textview;  public class detailactivity extends appcompatactivity {      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_detail);         if (savedinstancestate == null) {             getsupportfragmentmanager().begintransaction()                     .add(r.id.container, new placeholderfragment())                     .commit();         }     }       @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.detail, menu);         return true;     }      @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();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             return true;         }          return super.onoptionsitemselected(item);     }      /**      * placeholder fragment containing simple view.      */     public static class placeholderfragment extends fragment {          public placeholderfragment() {         }          @override         public view oncreateview(layoutinflater inflater, viewgroup container,                                  bundle savedinstancestate) {             intent intent = getactivity().getintent();             view rootview = inflater.inflate(r.layout.content_detail, container, false);             if(intent != null && intent.hasextra(intent.extra_text)){                 string forecaststr = intent.getstringextra(intent.extra_text);                 ((textview) rootview.findviewbyid(r.id.detail_text)).settext(forecaststr);             }             return rootview;         }     } } 

forecastfragment.xml

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto">     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools" tools:context=".mainactivity">     <item android:id="@+id/action_refresh" android:title="@string/action_refresh"         android:orderincategory="100" app:showasaction="never" /> </menu> 

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools" tools:context=".mainactivity">     <item android:id="@+id/action_settings" android:title="@string/action_settings"         android:orderincategory="100" app:showasaction="never" /> </menu> 

details.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     tools:context="com.example.android.sunshine.app.mainactivity">     <item android:id="@+id/action_settings" android:title="@string/action_settings"         android:orderincategory="100" app:showasaction="never" /> </menu> 

in detailactivity don't see action bar. how fix that?

ps: how androidmanifest.xml looks

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.android.sunshine.app">      <uses-permission android:name="android.permission.internet" />      <application         android:allowbackup="true"         android:icon="@drawable/ic_launcher"         android:label="@string/app_name"         android:theme="@style/apptheme">         <activity             android:name=".mainactivity"             android:label="@string/app_name">             <intent-filter>                 <action android:name="android.intent.action.main" />                  <category android:name="android.intent.category.launcher" />             </intent-filter>         </activity>         <activity             android:name=".detailactivity"             android:label="@string/title_activity_detail"             android:parentactivityname=".mainactivity"             android:theme="@style/apptheme.noactionbar">             <meta-data                 android:name="android.support.parent_activity"                 android:value="com.example.android.sunshine.app.mainactivity" />         </activity>         <activity             android:name=".settingsactivity"             android:label="@string/title_activity_settings"             android:parentactivityname=".detailactivity"             android:theme="@style/apptheme">             <meta-data                 android:name="android.support.parent_activity"                 android:value="com.example.android.sunshine.app.detailactivity" />         </activity>     </application>  </manifest> 

you can try

goto resources folder->values->style.xml , define this

 <style name="apptheme" parent="theme.appcompat.light.darkactionbar">  </style> 

and goto manifest file , add android:theme="" attribute application tag


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -