Search code examples
androidmultithreadingsimpleadapter

can't define Adapter in a thread


i'm not copying all the code cause it's too long, but to be concise :

i have a fonction (recup_list_internet) which has a thread in it, which retrieve data from internet (an XML), decoding it, and assign each "node" to an element in my adapter.

When doing the decoding outside the Thread, everything works fine. So i modify this to be used inside the thread, create a void run() function in it, displaying my progressDialog, decoding, data is well retrieved, well assigned to my map (=new HashMap();) and here is where the problem appears

private void recup_list_internet()
{
final ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
final Context mContext=this.getBaseContext();


Thread t = new Thread()
{
    public void run()
    {/* the code here works fine, not displaying it to be more concise*/

    progressDialog.dismiss(); //works fine
    SimpleAdapter mSchedule = new SimpleAdapter (mContext, listItem, R.layout.affiche_boutique,new String[] {"img", "titre", "description","Prix","uniqueID"}, new int[] {R.id.img,R.id.titre, R.id.description,R.id.prix,R.id.uniqueID}); //works fine
    maListViewPerso.setAdapter(mSchedule); //doesn't work
    }
};
t.start();
}

here is my log cat :

11-04 19:20:33.070: E/recuperation phonster(546): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

It seems that i'm unable to "access" to maListViewPero while in my thread... (maListViewPerso is defined previously in my onCreate code :

public class DisplayInternet  extends Activity{
private ListView maListViewPerso;
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ceinture_lv);
    maListViewPerso = (ListView) findViewById(R.id.listviewperso);
    recup_list_internet();
}   

so where can i put this line for its to works ? "maListViewPerso.setAdapter(mSchedule);"

because i already try to declare mSchedule outside my thread (in final) but inside my Thread, i'm unable to access it (and so, i'm unable to use it after the "t.start()" line


Solution

  • Inside your thread, use:

    View.post(Runnable r)

    which basically says "hey, UI thread, execute this thing for me" - and put in the runnable all the code which must be executed in the UI thread - this is particularly useful when you have a thread retrieving data from the network (which must not run on the UI thread) but then must post the results on the UI (which must be done from the UI thread)

    example:

    view.post(new Runnable(){ 
        public void run(){
            //put all the code you want to be execute on the UI thread here
        }
    });