Jignesh Ansodariya
Jignesh Ansodariya

Reputation: 12685

called from wrong Thread Exception

Please look at my code..

public class BseDemo extends Activity {
    final String feedUrlString = "http://www.bseindia.com/sensex/xml-data/sensexrss.xml";
    Uri uri;
    TextView tvs,tvd;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        Bse b = new Bse();
        b.start();


    }
    class Bse extends Thread{
        public void run(){
            try {
                tvs = (TextView)findViewById(R.id.text);
                tvd = (TextView)findViewById(R.id.diff);
                URL url = new URL(feedUrlString);
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                Document doc = docBuilder.parse (new InputSource(url.openStream()));
                doc.getDocumentElement ().normalize ();
                Element e =  doc.getDocumentElement();
                NodeList nl = e.getElementsByTagName("title");
                Node bse = nl.item(2);
                String sen  = bse.getFirstChild().getNodeValue();
                tvs.setText(sen.substring(0, sen.indexOf("*")));
                tvd.setText(sen.substring(sen.indexOf("*")+1));
                tvd.setBackgroundResource(R.drawable.plus);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}

I have code mentioned above and I am getting Exception CalledFromWrongTreadException please give some solution.

Upvotes: 1

Views: 4468

Answers (3)

Mark Mooibroek
Mark Mooibroek

Reputation: 7696

Try to implement a AsyncTask to get the String from the document ( in the doInBackground ) then use the onPostExecute to set the Text on the TextViews.

Is is the best method on doing background logic without blocking the UI thread.

Upvotes: 5

sparkymat
sparkymat

Reputation: 10028

You cannot update the UI from a non-UI Thread (the UI thread is the thread which calls onCreate of an Activity). To achieve what you are trying to do, you will need to use a Handler to post a message from the current thread to the UI thread. Look at this answer for how to do this: android: displaying progress dialog when waiting for connection

Upvotes: 1

Nicola Montecchio
Nicola Montecchio

Reputation: 477

try to look into runUIThread(...) function

that exception usually happens when you edit some UI components from other threads than the "main" one; I guess the problem is in:

tvs.setText(sen.substring(0, sen.indexOf("*")));
tvd.setText(sen.substring(sen.indexOf("*")+1));
tvd.setBackgroundResource(R.drawable.plus);

Upvotes: 4

Related Questions