Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...