android - Modifying textviews reliant on threaded API calls? -
public view getview(int position, view convertview, viewgroup parent) { layoutinflater inflater = layoutinflater.from(getcontext()); view theview = inflater.inflate(r.layout.match_layout, parent, false); matchid = getitem(position); textview championname = (textview) theview.findviewbyid(r.id.championnametext); new thread( new runnable() { public void run() { selectedmatch = riotapi.getmatch(matchid); log.i(tag, string.valueof(selectedmatch)); // <-- returns matches } }).start(); championname.settext(string.valueof(selectedmatch.getduration())); // log.i(tag, string.valueof(selectedmatch)); <-- returns nulls return theview; }
i've been running problem after problem trying make first app. understanding i'm not allowed api calls in main thread, tried using seperate thread. problem is, takes few seconds api return data, selectedmatch null when try update text view, giving me null pointer exceptions. proper way handle this?
edit: workaround i've found far putting empty while loop waiting thread finish first, seems inefficient. appreciate more input.
public view getview(int position, view convertview, viewgroup parent) { layoutinflater inflater = layoutinflater.from(getcontext()); view theview = inflater.inflate(r.layout.match_layout, parent, false); matchid = getitem(position); textview championname = (textview) theview.findviewbyid(r.id.championnametext); new thread( new runnable() { public void run() { selectedmatch = riotapi.getmatch(matchid); log.i(tag, string.valueof(selectedmatch)); // <-- returns matches } }).start(); while (selectedmatch == null) { } championname.settext(string.valueof(selectedmatch.getduration())); // log.i(tag, string.valueof(selectedmatch)); <-- returns nulls return theview; }
try using runonuithread():
new thread( new runnable() { public void run() { selectedmatch = riotapi.getmatch(matchid); ((youractivity)getcontext()).runonuithread(new runnable(){ public void run(){ championname.settext(string.valueof(selectedmatch.getduration())); } }); } }).start();
Comments
Post a Comment