Android的AsyncTask的方法,我不知道如何解决 [英] Android AsyncTask method that I dont know how to solve

查看:143
本文介绍了Android的AsyncTask的方法,我不知道如何解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调试我的计划,我注意到,我wasent能够在同一个线程中运行网络(我搜索这个错误,如2天,因为在虚拟设备中的应用程序的工作没有问题-.-)。所以,现在我知道我必须如何修复它,但我没有线索我怎么可以给一些parameteres是不是所有的字符串doInBackground方法。

我的方法需要一个网址的方法,这些我可以在doInBackground方法PARAMS [0],而params [1]据我所知访问。但是什么用namevaluepairs中的列表我怎么能访问,在doInBackground方法?

非常感谢你的帮助:)

这是我的类:

 进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.params.ClientPNames;
进口org.apache.http.client.params.CookiePolicy;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.os.AsyncTask;
进口android.util.Log;公共类JSONParser扩展的AsyncTask<弦乐,无效的JSONObject> {    静态InputStream为= NULL;
    静态的JSONObject jObj = NULL;
    静态JSON字符串=;    //构造
    公共JSONParser(){    }    //的Funktion嗯JSON澳大利亚einer URL祖holen
    //居wird EIN POST奥德EIN get请求gesendet
    公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
            清单<&的NameValuePair GT; PARAMS){        // HTTP请求ERSTELLEN
        尝试{            //Überprüfenwelche请求了Methode benutzt werden索尔
            如果(方法==POST){
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                httpClient.getParams()的setParameter(ClientPNames.COOKIE_POLICY,
                        CookiePolicy.BROWSER_COMPATIBILITY);
                HttpPost httpPost =新HttpPost(URL);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));                HTT presponse HTT presponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();            }否则如果(方法==GET){
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
                网址+ =? +中的paramString;
                HTTPGET HTTPGET =新HTTPGET(URL);                HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        //流在EIN字符串umwandeln
        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(!Fehler,Fehler炒面umwandeln冯流在字符串:+ e.toString());
        }        // JSON对象parsen
        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }        //达斯的JSONObjectzurückgeben
        返回jObj;    }    @覆盖
    受保护的JSONObject doInBackground(字符串... PARAMS){
        // TODO自动生成方法存根
        返回null;
    }
}


解决方案

我不认为你完全了解AsyncTasks的全部概念。当你想运行在后台线程的操作使用这些,这​​是完成这个任务的一个非常好的/灵活的方式。什么是真的对我很好,是 onPostExecute()执行主线程,因此它可以真正做一些强大的东西,一旦你的工作是在 doInBackground完成()。你应该记住,虽然因为 onPostExecute()在主线程上执行它,你不想在这里进行任何网络操作。

下面是一个AsyncTask的一个简单的例子:

 私有类myAsyncTask扩展的AsyncTask<弦乐,太虚,布尔> {    @覆盖
    在preExecute保护无效(){
        //才开始工作
    }    @覆盖
    保护布尔doInBackground(字符串参数... args){
        //在后台做的工作
        返回true;
    }    @覆盖
    保护无效onPostExecute(布尔成功){
        //工作完成..现在该怎么办?
    }
}

doInBackground()是你要去哪里在做大量的工作,所以我会尽量帮你出你想要的基本结构。我只是复制并粘贴您的code,我认为它应该去,所以这是不是100%gauranteed,但希望这将有助于揭开序幕,你想做什么:

 私有类JSONParser扩展的AsyncTask<弦乐,无效的JSONObject> {    静态InputStream为= NULL;
    静态的JSONObject jObj = NULL;
    静态JSON字符串=;    //变量传递:
    字符串URL;
    字符串的方法;
    清单<&的NameValuePair GT; PARAMS;    //构造
    公共JSONParser(URL字符串,字符串的方法,
        清单<&的NameValuePair GT; PARAMS){
        this.url =网址;
        this.method =方法;
        this.params =参数;
    }
    @覆盖
    受保护的JSONObject doInBackground(字符串参数... args){
        尝试{
            如果(方法==POST){
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                httpClient.getParams()的setParameter(ClientPNames.COOKIE_POLICY,
                        CookiePolicy.BROWSER_COMPATIBILITY);
                HttpPost httpPost =新HttpPost(URL);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));                HTT presponse HTT presponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();            }否则如果(方法==GET){
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
                网址+ =? +中的paramString;
                HTTPGET HTTPGET =新HTTPGET(URL);                HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }
        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(!Fehler,Fehler炒面umwandeln冯流在字符串:+ e.toString());
        }        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }        返回jObj;
    }    @覆盖
    保护无效onPostExecute(OBJ的JSONObject){
        //现在我们有你的JSONObject,玩弄它。
    }
}

编辑:

我忘了提,你也可以通过在 ARGS 这是一个字符串数组。您只需创建指定参数和通过它,当你打电话给你的AsyncTask:

 新JSONParser(URL,方法,则params).execute(参数);

和您可以访问ARGS在 doInBackground()

下面是一些AyncTask的更多信息: http://developer.android。 COM /参考/安卓/ OS / AsyncTask.html

I debugged my Program and I noticed that I wasent able to run Networking on the same Thread (I searched for this Error like 2 Days because in the Virtual Device the App worked without Problems -.- ). So now I know how I must fix it but I dont have a clue how I can give some parameteres that are not all String to the doinBackground Method.

My Method requires a url a method these i could access afaik with params[0] and params[1] in the doInBackground method. But whats with the List of NameValuePairs how can I access that in the doInBackground method?

Thank you very much for your help :)

This is my class:

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;
    }
}

解决方案

I don't think you fully understand the full concept of AsyncTasks. You use these when you want to run an operation in a background thread and this is a very nice/flexible way of accomplishing this task. What is really nice to me is onPostExecute() executes on the main thread, so it can really do some powerful things once your work is completed in doInBackground(). You should keep in mind though that because onPostExecute() does execute on the main thread, you do not want to perform any networking operations here.

Here is a simple example of an 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() is where you are going to be doing the bulk of your work, so I will try to help you out with the basic structure you want. I just copied and pasted your code where I thought it should go so this is not 100% gauranteed, but hopefully it will help kick off what you want to do:

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.
    }       
}

Edit:

I forgot to mention that you can also pass in args which is a string array. You can just create args and pass it in when you call your AsyncTask:

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

and you can access args in doInBackground()

Here is some more information on AyncTask: http://developer.android.com/reference/android/os/AsyncTask.html

这篇关于Android的AsyncTask的方法,我不知道如何解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆