android - Starting Map Activity from Nav Drawer -
i trying develop map activity initiated navigation drawer. have read this query .
my code :-
mainactivity.java
package com.tadrish.last; import android.graphics.bitmapfactory; import android.os.bundle; import android.support.v4.widget.drawerlayout; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.view.menu; import android.view.menuitem; import android.widget.toast; import android.content.intent; public class mainactivity extends appcompatactivity implements navigationdrawercallbacks { /** * fragment managing behaviors, interactions , presentation of navigation drawer. */ private navigationdrawerfragment mnavigationdrawerfragment; private toolbar mtoolbar; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mtoolbar = (toolbar) findviewbyid(r.id.toolbar_actionbar); setsupportactionbar(mtoolbar); mnavigationdrawerfragment = (navigationdrawerfragment) getfragmentmanager().findfragmentbyid(r.id.fragment_drawer); // set drawer. mnavigationdrawerfragment.setup(r.id.fragment_drawer, (drawerlayout) findviewbyid(r.id.drawer), mtoolbar); // populate navigation drawer mnavigationdrawerfragment.setuserdata("john doe", "johndoe@doe.com", bitmapfactory.decoderesource(getresources(), r.drawable.avatar)); } @override public void onnavigationdraweritemselected(int position) { // update main content replacing fragments switch(position) { case 0: intent = new intent(this, mapactivity.class); startactivity(a); break; case 1: break; case 2: break; default: break; } toast.maketext(this, "menu item selected -> " + (position +1), toast.length_short).show(); } @override public void onbackpressed() { if (mnavigationdrawerfragment.isdraweropen()) mnavigationdrawerfragment.closedrawer(); else super.onbackpressed(); } @override public boolean oncreateoptionsmenu(menu menu) { if (!mnavigationdrawerfragment.isdraweropen()) { // show items in action bar relevant screen // if drawer not showing. otherwise, let drawer // decide show in action bar. getmenuinflater().inflate(r.menu.main, menu); return true; } return super.oncreateoptionsmenu(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(); //noinspection simplifiableifstatement if (id == r.id.action_settings) { return true; } return super.onoptionsitemselected(item); } }
mapactivity.java
package com.tadrish.last; 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.util.hashmap; import java.util.list; import org.json.jsonobject; import android.os.asynctask; import android.os.bundle; import android.support.v4.app.fragmentactivity; import android.text.editable; import android.text.textwatcher; import android.util.log; import android.view.menu; import android.view.view; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.autocompletetextview; import android.widget.listview; import android.widget.simpleadapter; import com.google.android.gms.maps.cameraupdate; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.markeroptions; public class mapactivity extends fragmentactivity{ autocompletetextview atvplaces; downloadtask placesdownloadtask; downloadtask placedetailsdownloadtask; parsertask placesparsertask; parsertask placedetailsparsertask; googlemap googlemap; final int places=0; final int places_details=1; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_map); // getting reference autocompletetextview atvplaces = (autocompletetextview) findviewbyid(r.id.atv_places); atvplaces.setthreshold(1); // adding textchange listener atvplaces.addtextchangedlistener(new textwatcher() { @override public void ontextchanged(charsequence s, int start, int before, int count) { // creating downloadtask download google places matching "s" placesdownloadtask = new downloadtask(places); // getting url google places autocomplete api string url = getautocompleteurl(s.tostring()); // start downloading google places // causes execute doinbackground() of downloadtask class placesdownloadtask.execute(url); } @override public void beforetextchanged(charsequence s, int start, int count, int after) { // todo auto-generated method stub } @override public void aftertextchanged(editable s) { // todo auto-generated method stub } }); // setting item click listener autocompletetextview dropdown list atvplaces.setonitemclicklistener(new onitemclicklistener() { @override public void onitemclick(adapterview<?> arg0, view arg1, int index, long id) { listview lv = (listview) arg0; simpleadapter adapter = (simpleadapter) arg0.getadapter(); hashmap<string, string> hm = (hashmap<string, string>) adapter.getitem(index); // creating downloadtask download places details of selected place placedetailsdownloadtask = new downloadtask(places_details); // getting url google places details api string url = getplacedetailsurl(hm.get("reference")); // start downloading google place details // causes execute doinbackground() of downloadtask class placedetailsdownloadtask.execute(url); } }); } private string getautocompleteurl(string place){ // obtain browser key https://code.google.com/apis/console string key = "key=aizasyare2p8bfaquezyog-dn5aj0otmb6wtfci"; // place be searched string input = "input="+place; // place type searched string types = "types=geocode"; // sensor enabled string sensor = "sensor=false"; // building parameters web service string parameters = input+"&"+types+"&"+sensor+"&"+key; // output format string output = "json"; // building url web service string url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters; return url; } private string getplacedetailsurl(string ref){ // obtain browser key https://code.google.com/apis/console string key = "key=aizasyare2p8bfaquezyog-dn5aj0otmb6wtfci"; // reference of place string reference = "reference="+ref; // sensor enabled string sensor = "sensor=false"; // building parameters web service string parameters = reference+"&"+sensor+"&"+key; // output format string output = "json"; // building url web service string url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters; return url; } /** method download json data url */ private string downloadurl(string strurl) throws ioexception{ string data = ""; inputstream istream = null; httpurlconnection urlconnection = null; try{ url url = new url(strurl); // creating http connection communicate url urlconnection = (httpurlconnection) url.openconnection(); // connecting url urlconnection.connect(); // reading data url istream = urlconnection.getinputstream(); bufferedreader br = new bufferedreader(new inputstreamreader(istream)); stringbuffer sb = new stringbuffer(); string line = ""; while( ( line = br.readline()) != null){ sb.append(line); } data = sb.tostring(); br.close(); }catch(exception e){ log.d("exception :", e.tostring()); }finally{ istream.close(); urlconnection.disconnect(); } return data; } // fetches data url passed private class downloadtask extends asynctask<string, void, string>{ private int downloadtype=0; // constructor public downloadtask(int type){ this.downloadtype = type; } @override protected string doinbackground(string... url) { // storing data web service string data = ""; try{ // fetching data web service data = downloadurl(url[0]); }catch(exception e){ log.d("background task",e.tostring()); } return data; } @override protected void onpostexecute(string result) { super.onpostexecute(result); switch(downloadtype){ case places: // creating parsertask parsing google places placesparsertask = new parsertask(places); // start parsing google places json data // causes execute doinbackground() of parsertask class placesparsertask.execute(result); break; case places_details : // creating parsertask parsing google places placedetailsparsertask = new parsertask(places_details); // starting parsing json string // causes execute doinbackground() of parsertask class placedetailsparsertask.execute(result); } } } /** class parse google places in json format */ private class parsertask extends asynctask<string, integer, list<hashmap<string,string>>>{ int parsertype = 0; public parsertask(int type){ this.parsertype = type; } @override protected list<hashmap<string, string>> doinbackground(string... jsondata) { jsonobject jobject; list<hashmap<string, string>> list = null; try{ jobject = new jsonobject(jsondata[0]); switch(parsertype){ case places : placejsonparser placejsonparser = new placejsonparser(); // getting parsed data list construct list = placejsonparser.parse(jobject); break; case places_details : placedetailsjsonparser placedetailsjsonparser = new placedetailsjsonparser(); // getting parsed data list construct list = placedetailsjsonparser.parse(jobject); } }catch(exception e){ log.d("exception",e.tostring()); } return list; } @override protected void onpostexecute(list<hashmap<string, string>> result) { switch(parsertype){ case places : string[] = new string[] { "description"}; int[] = new int[] { android.r.id.text1 }; // creating simpleadapter autocompletetextview simpleadapter adapter = new simpleadapter(getbasecontext(), result, android.r.layout.simple_list_item_1, from, to); // setting adapter atvplaces.setadapter(adapter); break; case places_details : hashmap<string, string> hm = result.get(0); // getting latitude parsed data double latitude = double.parsedouble(hm.get("lat")); // getting longitude parsed data double longitude = double.parsedouble(hm.get("lng")); // getting reference supportmapfragment of activity_main.xml supportmapfragment fm = (supportmapfragment) getsupportfragmentmanager().findfragmentbyid(r.id.map); // getting googlemap supportmapfragment googlemap = fm.getmap(); latlng point = new latlng(latitude, longitude); cameraupdate cameraposition = cameraupdatefactory.newlatlng(point); cameraupdate camerazoom = cameraupdatefactory.zoomby(5); // showing user input location in google map googlemap.movecamera(cameraposition); googlemap.animatecamera(camerazoom); markeroptions options = new markeroptions(); options.position(point); options.title("position"); options.snippet("latitude:"+latitude+",longitude:"+longitude); // adding marker in google map googlemap.addmarker(options); break; } } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); return true; } }
navigationdrawerfragment.java
package com.tadrish.last; import android.app.activity; import android.app.fragment; import android.content.sharedpreferences; import android.content.res.configuration; import android.graphics.bitmap; import android.graphics.bitmapshader; import android.graphics.canvas; import android.graphics.colorfilter; import android.graphics.paint; import android.graphics.pixelformat; import android.graphics.rect; import android.graphics.rectf; import android.graphics.shader; import android.graphics.drawable.drawable; import android.os.bundle; import android.preference.preferencemanager; import android.support.v7.app.actionbardrawertoggle; import android.support.v4.widget.drawerlayout; import android.support.v7.widget.linearlayoutmanager; import android.support.v7.widget.recyclerview; import android.support.v7.widget.toolbar; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.imageview; import android.widget.textview; import java.util.arraylist; import java.util.list; public class navigationdrawerfragment extends fragment implements navigationdrawercallbacks { /** * remember position of selected item. */ private static final string state_selected_position = "selected_navigation_drawer_position"; /** * per design guidelines, should show drawer on launch until user manually * expands it. shared preference tracks this. */ private static final string pref_user_learned_drawer = "navigation_drawer_learned"; /** * pointer current callbacks instance (the activity). */ private navigationdrawercallbacks mcallbacks; /** * helper component ties action bar navigation drawer. */ private actionbardrawertoggle mactionbardrawertoggle; private drawerlayout mdrawerlayout; private recyclerview mdrawerlist; private view mfragmentcontainerview; private int mcurrentselectedposition = 0; private boolean mfromsavedinstancestate; private boolean muserlearneddrawer; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // read in flag indicating whether or not user has demonstrated awareness of // drawer. see pref_user_learned_drawer details. sharedpreferences sp = preferencemanager.getdefaultsharedpreferences(getactivity()); muserlearneddrawer = sp.getboolean(pref_user_learned_drawer, false); if (savedinstancestate != null) { mcurrentselectedposition = savedinstancestate.getint(state_selected_position); mfromsavedinstancestate = true; } } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view = inflater.inflate(r.layout.fragment_navigation_drawer, container, false); mdrawerlist = (recyclerview) view.findviewbyid(r.id.drawerlist); linearlayoutmanager layoutmanager = new linearlayoutmanager(getactivity()); layoutmanager.setorientation(linearlayoutmanager.vertical); mdrawerlist.setlayoutmanager(layoutmanager); mdrawerlist.sethasfixedsize(true); final list<navigationitem> navigationitems = getmenu(); navigationdraweradapter adapter = new navigationdraweradapter(navigationitems); adapter.setnavigationdrawercallbacks(this); mdrawerlist.setadapter(adapter); selectitem(mcurrentselectedposition); return view; } public boolean isdraweropen() { return mdrawerlayout != null && mdrawerlayout.isdraweropen(mfragmentcontainerview); } public actionbardrawertoggle getactionbardrawertoggle() { return mactionbardrawertoggle; } public drawerlayout getdrawerlayout() { return mdrawerlayout; } @override public void onnavigationdraweritemselected(int position) { selectitem(position); } public list<navigationitem> getmenu() { list<navigationitem> items = new arraylist<navigationitem>(); items.add(new navigationitem("map", getresources().getdrawable(r.drawable.ic_action_map))); items.add(new navigationitem("item 2", getresources().getdrawable(r.drawable.ic_menu_check))); items.add(new navigationitem("item 3", getresources().getdrawable(r.drawable.ic_menu_check))); return items; } /** * users of fragment must call method set navigation drawer interactions. * * @param fragmentid android:id of fragment in activity's layout. * @param drawerlayout drawerlayout containing fragment's ui. * @param toolbar toolbar of activity. */ public void setup(int fragmentid, drawerlayout drawerlayout, toolbar toolbar) { mfragmentcontainerview = getactivity().findviewbyid(fragmentid); mdrawerlayout = drawerlayout; mdrawerlayout.setstatusbarbackgroundcolor(getresources().getcolor(r.color.myprimarydarkcolor)); mactionbardrawertoggle = new actionbardrawertoggle(getactivity(), mdrawerlayout, toolbar, r.string.drawer_open, r.string.drawer_close) { @override public void ondrawerclosed(view drawerview) { super.ondrawerclosed(drawerview); if (!isadded()) return; getactivity().invalidateoptionsmenu(); // calls onprepareoptionsmenu() } @override public void ondraweropened(view drawerview) { super.ondraweropened(drawerview); if (!isadded()) return; if (!muserlearneddrawer) { muserlearneddrawer = true; sharedpreferences sp = preferencemanager .getdefaultsharedpreferences(getactivity()); sp.edit().putboolean(pref_user_learned_drawer, true).apply(); } getactivity().invalidateoptionsmenu(); // calls onprepareoptionsmenu() } }; // if user hasn't 'learned' drawer, open introduce them drawer, // per navigation drawer design guidelines. if (!muserlearneddrawer && !mfromsavedinstancestate) { mdrawerlayout.opendrawer(mfragmentcontainerview); } // defer code dependent on restoration of previous instance state. mdrawerlayout.post(new runnable() { @override public void run() { mactionbardrawertoggle.syncstate(); } }); mdrawerlayout.setdrawerlistener(mactionbardrawertoggle); } private void selectitem(int position) { mcurrentselectedposition = position; if (mdrawerlayout != null) { mdrawerlayout.closedrawer(mfragmentcontainerview); } if (mcallbacks != null) { mcallbacks.onnavigationdraweritemselected(position); } ((navigationdraweradapter) mdrawerlist.getadapter()).selectposition(position); } public void opendrawer() { mdrawerlayout.opendrawer(mfragmentcontainerview); } public void closedrawer() { mdrawerlayout.closedrawer(mfragmentcontainerview); } @override public void onattach(activity activity) { super.onattach(activity); try { mcallbacks = (navigationdrawercallbacks) activity; } catch (classcastexception e) { throw new classcastexception("activity must implement navigationdrawercallbacks."); } } @override public void ondetach() { super.ondetach(); mcallbacks = null; } @override public void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putint(state_selected_position, mcurrentselectedposition); } @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); // forward new configuration drawer toggle component. mactionbardrawertoggle.onconfigurationchanged(newconfig); } public void setuserdata(string user, string email, bitmap avatar) { imageview avatarcontainer = (imageview) mfragmentcontainerview.findviewbyid(r.id.imgavatar); ((textview) mfragmentcontainerview.findviewbyid(r.id.txtuseremail)).settext(email); ((textview) mfragmentcontainerview.findviewbyid(r.id.txtusername)).settext(user); avatarcontainer.setimagedrawable(new roundimage(avatar)); } public view getgoogledrawer() { return mfragmentcontainerview.findviewbyid(r.id.googledrawer); } public static class roundimage extends drawable { private final bitmap mbitmap; private final paint mpaint; private final rectf mrectf; private final int mbitmapwidth; private final int mbitmapheight; public roundimage(bitmap bitmap) { mbitmap = bitmap; mrectf = new rectf(); mpaint = new paint(); mpaint.setantialias(true); mpaint.setdither(true); final bitmapshader shader = new bitmapshader(bitmap, shader.tilemode.clamp, shader.tilemode.clamp); mpaint.setshader(shader); mbitmapwidth = mbitmap.getwidth(); mbitmapheight = mbitmap.getheight(); } @override public void draw(canvas canvas) { canvas.drawoval(mrectf, mpaint); } @override protected void onboundschange(rect bounds) { super.onboundschange(bounds); mrectf.set(bounds); } @override public void setalpha(int alpha) { if (mpaint.getalpha() != alpha) { mpaint.setalpha(alpha); invalidateself(); } } @override public void setcolorfilter(colorfilter cf) { mpaint.setcolorfilter(cf); } @override public int getopacity() { return pixelformat.translucent; } @override public int getintrinsicwidth() { return mbitmapwidth; } @override public int getintrinsicheight() { return mbitmapheight; } public void setantialias(boolean aa) { mpaint.setantialias(aa); invalidateself(); } @override public void setfilterbitmap(boolean filter) { mpaint.setfilterbitmap(filter); invalidateself(); } @override public void setdither(boolean dither) { mpaint.setdither(dither); invalidateself(); } public bitmap getbitmap() { return mbitmap; } } }
whenever open app automatically starts @ map , no navigation drawer not available. rest of code adapted here , here
please me out...or point out other info need provide
Comments
Post a Comment