Sunday, 15 June 2014

Android app close with null exception -



Android app close with null exception -

this question has reply here:

nullpointerexception accessing views in oncreate() 8 answers

i have simple android app beingness built. have 2 buttons , 1 textview. build them graphically in fragment_main.xml. below total codes.

public class mainactivity extends actionbaractivity { textview tvout; button btnok; button btncancel; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.fragment_main); if (savedinstancestate == null) { getsupportfragmentmanager().begintransaction() .add(r.id.container, new placeholderfragment()) .commit(); } view.onclicklistener oclbtnok = new view.onclicklistener() { public void onclick(view v) { // alter text of textview (tvout) tvout.settext("button ok clicked"); } }; btnok.setonclicklistener(oclbtnok); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); homecoming 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(); if (id == r.id.action_settings) { homecoming true; } homecoming 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) { view rootview = inflater.inflate(r.layout.fragment_main, container, false); homecoming rootview; } } }

if comment part of codes works well.

view.onclicklistener oclbtnok = new view.onclicklistener() { public void onclick(view v) { // alter text of textview (tvout) tvout.settext("button ok clicked"); } }; btnok.setonclicklistener(oclbtnok);

even though utilize setcontentview(r.layout.main_activity); button , text view appears , quite puzzle why main_activity buttons , text view appears well.

you never assign values views. utilize findviewbyid references views id's gave them in xml layout.

setcontentview(r.layout.fragment_main); // views btnok = (button) findviewbyid(r.id.your_button_id); tvout = (textview) findviewbyid(r.id.another_id); btnok.setonclicklistener(...);

android

No comments:

Post a Comment