【问题标题】:Android AsyncTask method that I dont know how to solve我不知道如何解决的Android AsyncTask方法
【发布时间】:2012-10-26 19:11:17
【问题描述】:

我调试了我的程序,我注意到我无法在同一个线程上运行网络(我搜索了这个错误,比如 2 天,因为在虚拟设备中应用程序正常工作 -.- )。所以现在我知道我必须如何修复它,但我不知道如何将一些不全是字符串的参数提供给 doinBackground 方法。

我的方法需要一个 url 方法,我可以在 doInBackground 方法中使用 params[0] 和 params[1] 访问 afaik。但是 NameValuePairs 列表是怎么回事,如何在 doInBackground 方法中访问它?

非常感谢您的帮助:)

这是我的课:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class JSONParser extends AsyncTask<String, Void, JSONObject>{

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // Funktion um JSON aus einer URL zu holen
    // Es wird ein POST oder ein GET Request gesendet
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // HTTP Request erstellen
        try {

            // Überprüfen welche Request Methode benutzt werden soll
            if(method == "POST"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                        CookiePolicy.BROWSER_COMPATIBILITY);
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Stream in ein String umwandeln
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Fehler!", "Fehler mein umwandeln von Stream in String: " + e.toString());
        }

        // JSON Object parsen
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // Das JSONObject zurückgeben
        return jObj;

    }

    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        return null;
    }
}

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    我认为您并不完全理解 AsyncTasks 的完整概念。当您想在后台线程中运行操作时使用这些,这是完成此任务的一种非常好/灵活的方式。对我来说真正好的是onPostExecute() 在主线程上执行,所以一旦你的工作在doInBackground() 中完成,它确实可以做一些强大的事情。您应该记住,因为onPostExecute() 确实在主线程上执行,所以您不想在此处执行任何网络操作。

    这是一个简单的 AsyncTask 示例:

    private class myAsyncTask extends AsyncTask<String, Void, Boolean> {
    
        @Override
        protected void onPreExecute() {
            // before we start working
        }   
    
        @Override
        protected Boolean doInBackground(String... args) {
            //do work in the background
            return true;
        }
    
        @Override
        protected void onPostExecute(Boolean success) {
            // the work is done.. now what?
        }       
    }
    

    doInBackground() 是您完成大部分工作的地方,因此我将尝试帮助您完成所需的基本结构。我只是将您的代码复制并粘贴到我认为应该去的地方,所以这不是 100% 保证的,但希望它会帮助您开始您想做的事情:

    private class JSONParser extends AsyncTask<String, Void, JSONObject> {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // variables passed in:
        String url;
        String method;
        List<NameValuePair> params;
    
        // constructor
        public JSONParser(String url, String method, 
            List<NameValuePair> params) {
            this.url = url;
            this.method = method;
            this.params = params;
        }
    
    
        @Override
        protected JSONObject doInBackground(String... args) {
            try {
                if(method == "POST"){
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                            CookiePolicy.BROWSER_COMPATIBILITY);
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                } else if(method == "GET"){
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
    
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Fehler!", "Fehler mein umwandeln von Stream in String: " + e.toString());
            }
    
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            return jObj;
        }
    
        @Override
        protected void onPostExecute(JSONObject obj) {
            // Now we have your JSONObject, play around with it.
        }       
    }
    

    编辑:

    我忘了提到你也可以传入args,它是一个字符串数组。您可以在调用 AsyncTask 时创建 args 并传入它:

    new JSONParser(url, method, params).execute(args);
    

    你可以在doInBackground()访问args

    这里有更多关于 AyncTask 的信息:http://developer.android.com/reference/android/os/AsyncTask.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-31
      • 2023-04-08
      • 1970-01-01
      • 2022-01-25
      • 2022-10-15
      • 2022-06-15
      • 2023-02-03
      • 1970-01-01
      相关资源
      最近更新 更多