开发者

Android fetching xml from aspx web service

I'm trying to fetch an xml from a web service from android application. I'm running this code but the error message is 'The application has stopped unexpectedly. Please try again'. I'm not sure that it's an application exception because every peace of code is in try block. What is the mistake?

    public class AndroidTest extends Activity {

             private static final String URL = "http://webservice.url/is/here.aspx";
             TextView v;

            public void onCreate(Bundle savedInstanceState) {
            try {
                super.onCreate(savedInstanceState);
                v = new TextView(this);
                setContentView(v);
                new Obtainer().execute();
            } catch (Exception ex) {
                Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).sho开发者_开发百科w();
            }
        }

        private class Obtainer extends AsyncTask<Void, Void, Void> {

            protected Void doInBackground(Void... params) {
                BufferedReader in = null;
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpGet request = new HttpGet();
                    request.setURI(new URI(URL));
                    HttpResponse response = client.execute(request);
                    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    StringBuffer sb = new StringBuffer("");
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    in.close();
                    v.setText(sb.toString());
                } catch (Exception ex) {
                    Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
                }
                return null;
            }
        }
    }

EDIT: now it throws an exception android.os.NetworkOnMainThreadException although this class (Obtainer) was created to fix it.


The answer was very easy - we cannot run show method of Toast in the non ui thread and we cannot work with TextView in it also.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜