android - I can't get data from edittext in fragment after I replace fragment -
i have 2 fragment edittext, data first edittext gets after call second fragment can't data edittext in second fragment. logcat said me data second edittext void.
this first fragment class
package com.example.n; import android.annotation.targetapi; import android.app.fragment; import android.os.build; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.edittext; @targetapi(build.version_codes.honeycomb) public class fragmentadd extends fragment { edittext et1; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.frag_add, container, false); et1 = (edittext) rootview.findviewbyid(r.id.edittext); return rootview ; } }
this second fragment class
package com.example.n; import android.annotation.targetapi; import android.app.fragment; import android.os.build; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.edittext; @targetapi(build.version_codes.honeycomb) public class fragmentadd2 extends fragment { edittext et2; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.frag_add2, container, false); et2 = (edittext) rootview.findviewbyid(r.id.edittext2); return rootview ; } public string getedittext(){ /*fragmentadd2 fragmentadd3 = new fragmentadd2(); string data = fragmentadd3.et2.gettext().tostring();*/ string data = et2.gettext().tostring(); return data; } }
this part of main class
@targetapi(build.version_codes.honeycomb) public void onclick(view view){ fragmentadd fragmentadd = new fragmentadd(); string data = fragmentadd.et1.gettext().tostring(); } @targetapi(build.version_codes.honeycomb) public void onclick(view view){ fragmentadd2 fragmentadd2 = new fragmentadd2(); string data = fragmentadd2.et2.gettext().tostring(); } *logcat* java.lang.illegalstateexception: not execute method of activity caused by: java.lang.reflect.invocationtargetexception @ java.lang.reflect.method.invoke(native method) @ java.lang.reflect.method.invoke(method.java:372) caused by: java.lang.nullpointerexception: attempt invoke virtual method 'android.text.editable android.widget.edittext.gettext()' on null object reference
the correct way of accessing fragment method activity is
examplefragment fragment = (examplefragment) getfragmentmanager().findfragmentbyid(r.id.example_fragment); fragment.methodname();
or
examplefragment fragment = (examplefragment) getfragmentmanager().findfragmentbytag("your tag"); fragment.methodname();
"your tag" tag passed in parameter when added or replaced fragment
.
Comments
Post a Comment