i have a problem to send List from Simple Adpater to layout, when i starting system sending my:

public class Lista extends ListActivity 
{
        HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        List<NameValuePair> nameValuePairs; 
        private static final String PREFERENCES_NAME = "myPreferences";
        private static final String PREFERENCES_TEXT_FIELDK = "key";

TextView result;
String text;

// XML node keys
static final String KEY_ITEM = "quote"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "date";
static final String KEY_DESC = "place";
static final String KEY_POLEC = "action";
private SharedPreferences preferences;
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.lista);
    preferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
    result = (TextView)findViewById(R.id.info);
    try {checksession();}catch(JSONException e){/* TODO Auto-generated catch block */ e.printStackTrace();}
}
public void checksession() throws JSONException
{ 
    // Create a new HttpClient and Post Header
    Thread thread = new Thread()
    {
        @Override
        public void run() 
        {
            try{
                httpclient=new DefaultHttpClient();
                httppost= new HttpPost(xxx); // make sure the url is correct.
                ......................
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                //Execute HTTP Post Request
                response=httpclient.execute(httppost);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                final String response = httpclient.execute(httppost, responseHandler);
                System.out.println("Response : " + response);
                runOnUiThread(new Runnable() 
                {
                public void run() 
                {
                    // p.dismiss();
                if (response != null && response.length()==6)
                {

                    //  result.setText("In System");
                    takeXML(); // takeXML XML
                }else{ result.setText("No login:"+response);}
                }
                });
            }catch(Exception e){
                //runOnUiThread(new Runnable() {public void run() {p.dismiss();}});
                result.setText("Error system");
                System.out.println("Exception : " + e.getMessage());
            }
        }
    };
    thread.start(); 
}

In this position code is OK. Now is code function takeXML:

    private void takeXML()
{
    new Thread(new Runnable() {
    public void run() 
    {
        try{ 
            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
            String adresxml="http://xxx.xml";
            XMLParser parser = new XMLParser(); 
            String xml = parser.getXmlFromUrl(adresxml); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element
            NodeList nl = doc.getElementsByTagName(KEY_ITEM);

            for (int i = 0; i < nl.getLength(); i++) 
            {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
                map.put(KEY_COST, parser.getValue(e, KEY_COST));
                // adding HashList to ArrayList
                // excel[i] = new ExcelFileClass() 

                menuItems.add(map);
            }
            Log.v("List","Array:"+menuItems);
            // Adding menuItems to ListView
            ListAdapter adapter = new SimpleAdapter(getBaseContext(), menuItems,R.layout.list_item,new String[] { KEY_NAME, KEY_COST, KEY_ID }, new int[] {R.id.name,R.id.cost, R.id.elements });

End now is the problem, in this place system sending me: "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." I try, I searching how to fix this. But, no idea for this.

            setListAdapter(adapter);
            ListView lv = getListView();
            lv.setOnItemClickListener(new OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
                {
                    ......  
                }
            });
        }catch(Exception e){
            //runOnUiThread(new Runnable() {public void run() {p.dismiss();}});
            result.setText("Error");
            System.out.println("Exception : " + e.getMessage());
        }
    }
}).start();
}
有帮助吗?

解决方案

You need to call the parts of code which modify the UI inside the main thread of the activity.

To do this use runOnUiThread to call setListAdapter(adapter):

runOnUiThread(new Runnable() {
   @Override
   public void run() {
        setListAdapter(adapter)
   }
});

Do the same with the result.setText("Error");.

EDIT:

private void takeXML()
{
new Thread(new Runnable() {
public void run() 
{
    try{ 
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
        String adresxml="http://xxx.xml";
        XMLParser parser = new XMLParser(); 
        String xml = parser.getXmlFromUrl(adresxml); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element
        NodeList nl = doc.getElementsByTagName(KEY_ITEM);

        for (int i = 0; i < nl.getLength(); i++) 
        {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
            map.put(KEY_COST, parser.getValue(e, KEY_COST));
            // adding HashList to ArrayList
            // excel[i] = new ExcelFileClass() 

            menuItems.add(map);
        }
        Log.v("List","Array:"+menuItems);
        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(getBaseContext(), menuItems,R.layout.list_item,new String[] { KEY_NAME, KEY_COST, KEY_ID }, new int[] {R.id.name,R.id.cost, R.id.elements });
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            setListAdapter(adapter)
            }
        });
        ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
            {
                ......  
            }
        });
    }catch(Exception e){
        //runOnUiThread(new Runnable() {public void run() {p.dismiss();}});
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText("Error");
            }
        });
        System.out.println("Exception : " + e.getMessage());
    }
  }
 }).start();
}

Hope it helps :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top