【问题标题】:Variable not updated on AsyncTask变量未在 AsyncTask 上更新
【发布时间】:2016-05-11 11:48:30
【问题描述】:

正如标题所说,我的变量在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 是根据从数据库获取的数据(HTTP 连接、JSON 结果...)创建的,结果是非常可接受的 JSON 输出;这里没有问题,只是如果我尝试在 Main 上使用 Sectors 并没有更新。 我不知道我是否真的了解 onPostExecute;或者有问题! 谢谢

【问题讨论】:

  • 我认为您对异步执行 asynctask 的概念感到困惑。如果您在调试模式下运行代码并在各种方法中放置断点,您会看到它是如何安排的。

标签: android arrays json android-asynctask


【解决方案1】:

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

试试这个:

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
        }

    }

希望对您有所帮助。

【讨论】:

  • ohk :) 你正在重新调整 myArray 而不是 null 对吗?
  • 如果你做到了,我做到了,这就是复制/过去 :(
  • 我知道。只是想确认解决您知道的问题。你能添加你更新的sn-p吗?
  • @Override protected ArrayList&lt;paire&gt; doInBackground(String... strings) { /* * LOT OF BLABLA ABOUT CREATING myArray * */ return myArray; }
  • 在这里调试并检查你的数组 return myArray;它是否有价值?因为一切看起来都很好。如果您使用更新的 sn-p 更新您的问题,那将非常有帮助。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你应该再次仔细阅读 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
    }
    }
    

    【讨论】:

    • code Error:(164, 20) error: incompatible types: ArrayList&lt;Search.paire&gt; cannot be converted to Void 只是在回报的行
    • 是的;还有codeprotected ArrayList&lt;paire&gt; doInBackground(String... strings),但执行 Rech 后的大小始终为 0 :(
    • 你能检查 doInBackground 执行后,myArray.size() > 0 与否
    • 是的,它是 14;正如我所说,在 onPostExecute 中打印 Sector 的大小告诉我 14 !
    • 我又改了答案,你能再检查一次吗?
    【解决方案4】:
    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;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2020-01-22
      • 2011-12-17
      • 1970-01-01
      相关资源
      最近更新 更多