Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

networking - networkOnMainThread Exception Android

I'm trying to access a server so I can receive a JSON String. But apparently in Ice Cream Sandwich you can't do network operations in the main thread, but the AsyncTask class is confusing me and not working. Here's what I have so far:

//up in main code
Void blah = null;
URI uri = "kubie.dyndns-home.com/R2Bar2/ingredients.php";
new DownloadFilesTask().execute(uri , blah, blah);


private class DownloadFilesTask extends AsyncTask<URI, Void, Void> {
        protected Void doInBackground(URI... uri) {
            HttpClient client = new DefaultHttpClient();
            String json = "";
            int duration = Toast.LENGTH_SHORT;
            try {
                HttpResponse response = null;
                BufferedReader rd = null;
                String line = "";
                HttpGet request = new HttpGet(uri);
            } catch (URISyntaxException e1) {

            }
return null;
        }

        protected void onProgressUpdate(Integer... progress) {

        }

        protected void onPostExecute(Long result) {

        }

It's not liking my HttpGet request = new HttpGet(uri) It says to change uri to URI, but it already is! I've tried changing all parameters to Void, but my app just force closes.

Anyone know how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

But apparently in Ice Cream Sandwich you can't do network operations in the main thread

You can, but it will give you a warning in LogCat. And you should not do network operations on the main application thread, as it will freeze your UI and possibly give you an "Application Not Responding" (ANR) dialog.

but the AsyncTask class is confusing me and not working

In your current code, you are not actually executing the HttpGet request.

It's not liking my HttpGet request = new HttpGet(uri) It says to change uri to URI, but it already is!

No, it is not.

The ... after URI in your doInBackground() declaration means that this method accepts a variable number of arguments. Your uri parameter is, in effect, a URI[]. If you are only ever calling execute() with one URI, you get at that URI via uri[0], not uri.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...