变量未在AsyncTask上更新

时间:2016-05-11 11:48:30

标签: android arrays json android-asynctask

如标题所示,我的变量未在AsyncTask onPostExecute()

上更新

这是代码

public class Search extends AppCompatActivity {

ArrayList<paire> Sectors = new ArrayList<paire>();//paire is my proper class
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    Rechercher rech = new Rechercher();
    rech.execute();
    //PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF 0

    /*
    *
    *
    BLA BLA BLA BLA
    *
    *
    */
}

 public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{

    @Override
    protected ArrayList<paire>doInBackground(String... strings) {
        /*
        *
        Process of creating the arrayList myArray

        *
        */
        onPostExecute(myArray);//I put this desesperatly xD it doesn't change anything

        return myArray;
    }
    protected void onPostExecute(ArrayList<paire>myArray) {
        for (int u = 0; u < myArray.size(); u ++){
                paire r = myArray.get(u);
                Sectors.add(r);
            }
        //PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
    }

}
}

myArray是根据从dataBase获得的数据(HTTP连接,JSON结果...)创建的,结果是一个非常可接受的JSON输出;这里没有问题,如果我尝试在Main上使用它,Sectors就不会更新。 我不知道我是否真的理解onPostExecute;或者有问题! 谢谢

4 个答案:

答案 0 :(得分:1)

onPostExcecute会自动调用,只需在doBackground中返回您的数组,并在AsyncTask<String, Void, ArrayList<paire>>中传递ArrayList而不是void,并将doInBackground的返回类型更改为ArrayList<paire> < / p>

试试这个:

public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{

        @Override
        protected ArrayList<paire> doInBackground(String... strings) {
            /*
            *
            Process of creating the arrayList myArray

            *
            */
            //onPostExecute(myArray); // remove this line no need to add . this will call automatically.
            return myArray;
        }
        protected void onPostExecute(ArrayList<paire> myArray) {
            for (int u = 0; u < s.size(); u ++){
                Sectors.set(u, s.get(u));
            }
            //PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
        }

    }
希望这有帮助。

答案 1 :(得分:0)

这座建筑物没有错误吗?我不相信你可以从doInBackground调用onPostExecute而我在代码中的任何地方都没有看到有一个名为&#34; s&#34;的变量。但是s.size()是控制for循环迭代次数的原因。所以在当前的代码中,永远不会调用Sectors.set。

答案 2 :(得分:0)

你应该再次仔细阅读asyncTask。 修改asynTask如下所示

public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{

@Override
protected Void doInBackground(String... strings) {
    /*
    *
    Process of creating the arrayList myArray

    *
    */
    /* don't need to call this function, asynctask will call it automatically
        onPostExecute(myArray);
    */
    return myArray;
}
protected void onPostExecute(ArrayList<paire>myArray) {

    if (Selector.size() > 0) {
        Selector.clear();
    }
    for (int u = 0; u < s.size(); u ++){
        Sectors.add(s.get(u));
    }
            //PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
}
}

答案 3 :(得分:0)

package caci.elmouchir;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;

import android.util.Log;
import android.widget.*;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Search extends AppCompatActivity {

    private void setSectors(String[] lesSec){
        Spinner sec = (Spinner) findViewById(R.id.spinnerSecteur);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lesSec);
        sec.setAdapter(adapter);

        sec.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    ArrayList<paire> Sectors = new ArrayList<paire>();
    ArrayList<paire> Branchs = new ArrayList<paire>();
    ArrayList<paire> SBranchs = new ArrayList<paire>();
    ArrayList<paire> Activities = new ArrayList<paire>();





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        String Code = "X.XX.XX.XXX";
        Rechercher rech = new Rechercher();
        rech.execute();
        Log.e("log_tag", Integer.toString(Sectors.size()));
        //Log.e("log_tag", Integer.toString(Sectors.size()));






        Button search = (Button)findViewById(R.id.buttonSearch);
        search.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                EditText motcle = (EditText)findViewById(R.id.editMotCle);
                if (motcle.getText().toString().isEmpty())
                    motcle.setError("Entrez un mot clé");
            }
        });

        /*
        *
        *
        *
        *
        C O N N E X I O N                   A              L A                B A S E               D E                  D O N N E E S
        *
        *
        *
        *
        */


    }


    public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{

        @Override
        protected ArrayList<paire> doInBackground(String... strings) {
            String result = "";
            ArrayList<paire> s = new ArrayList<paire>();
            try{

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://192.168.1.145/test/getActivities.php");
                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                //convert response to string
                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();

                result=sb.toString();
                //Log.e("log_tag", result);
                try{

                    JSONArray jArray = new JSONArray(result);

                    ArrayList<paire> b = new ArrayList<paire>();
                    ArrayList<paire> sous = new ArrayList<paire>();
                    ArrayList<paire> a = new ArrayList<paire>();

                    for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = (JSONObject)jArray.getJSONObject(i);
                        if (json_data.getString("friendly_url").toString().length() == 2){
                            paire p = new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString());
                            s.add(p);


                        }
                        else if(json_data.getString("friendly_url").toString().length() == 3){
                            b.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
                        }
                        else if(json_data.getString("friendly_url").toString().length() == 4){
                            sous.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
                        }
                        else{
                            a.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
                        }}
                    //Log.e("log_tag", Integer.toString(s.size()));

                   // onPostExecute(s, b, sous, a);



                }catch(JSONException e){
                    Log.e("log_tag", "Error parsing data "+e.toString());
                }

            }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
            }


            return s;
        }
        protected void onPostExecute(ArrayList<paire>s) {
            /*Sectors = s;
            Branchs = b;
            SBranchs = sous;
            Activities = a;*/


                for (int u = 0; u < s.size(); u ++){
                    paire r = s.get(u);
                    Sectors.add(r);
                }
            Log.e("log_tag", "loool: "+Integer.toString(Sectors.size()));

        }

    }


    public class paire{
        String title;
        String url;
        paire(String p, String u){
            this.title = p;
            this.url = u;
        }
        String getTitle(){
            return this.title;
        }
        String getUrl(){
            return this.url;
        }
    }
}