android - Pass data from listview to main activity -
i have main activity included button , textview. when click button, display listview , fill data listview. in listview, click item, want send item data textview in main activity. however, has crash. have no idea find problem , log (does not show). @ code , provide me solution?
mainactivity
btnmanage = (button) findviewbyid(r.id.btnmanage); btnmanage.settext(managelabel); btnmanage.setonclicklistener(new view.onclicklistener() { @override public void onclick(final view v) { intent intent = new intent(v.getcontext(), listviewactivity.class); intent.putextra("list_data", "hello"); v.getcontext().startactivity(intent); } });
in listviewactivity have
bundle bundle = getintent().getextras(); string data_string= bundle.getstring("list_data"); arraylist<string> data = new arraylist<string>(); data.add(data_string); listadapter = new arrayadapter<string>(this, r.layout.simplerow, data); // set arrayadapter listview's adapter. mainlistview.setadapter( listadapter ); //click 1 item public void onitemclick(adapterview<?> parent, view view, int position, long id) { string data_send = (string) mainlistview.getitematposition(position); intent intent = new intent(this, mainactivity.class); intent.putextra("data_send", data_send); startactivity(intent); }
in oncreate function in mainactivity, have
bundle bundle = getintent().getextras(); string data_activity =bundle.getstring("data_send");
the manifest file
<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=".listviewactivity" android:label="@string/app_name" android:screenorientation="portrait" />
in listviewactivity trying start mainactivity started hence error.
you need finish listviewactivity acivity goes previous activity mainactivity , pass data
in listviewactivity finish activity , pass data this
intent intent = new intent(); intent.putextra("data_send", data_send); setresult(result_ok, intent); finish();
in mainactivity start listviewactivity this
intent = new intent(getapplicationcontext(), listviewactivity.class); i.putextra("list_data", "hello"); startactivityforresult(i, 1);
also in mainactivity need data listviewactivity add
public void onactivityresult(int requestcode, int resultcode, intent data) { if (requestcode == 1) { if (resultcode == result_ok) { string data = data.getstringextra("data_send"); // whatever data string }}};
the if (requestcode == 1) {
number id give when start activity startactivityforresult(i, 1);
. if want same activity can startactivityforresult(i, 2);
, data check id 2
if (requestcode == 2) { ...
Comments
Post a Comment