Spinner在多次asynctask后丢失内容

时间:2014-01-16 08:55:26

标签: android json android-listview android-asynctask spinner

我有关于asynctask和spinner的问题。我有一个微调器,一个列表视图和2个按钮。

  1. 我是通过点击第一个按钮(带有json
    来数据绑定微调器) asynctask服务)Spinner正确显示数据,没问题

  2. 之后我点击另一个按钮进行数据绑定列表视图
    (使用asynctask的json服务)。列表视图显示数据
    没错,

  3. 但是现在当我点击微调器时,微调器没有数据,它会丢失数据。 它只显示我填写之前选择的最后一项 列表视图。

  4. 我正在使用asynctask类,就像这个BackgroundTast.java

    public class BackGroundTask extends AsyncTask<String, String, JSONObject> {
    
        List<NameValuePair> postparams = new ArrayList<NameValuePair>();
        String URL = null;
        String method = null;
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        public BackGroundTask(String url, String method, List<NameValuePair> params) {
            this.URL = url;
            this.postparams = params;
            this.method = method;
        }
    
        @Override
        protected JSONObject doInBackground(String... params) {
            // TODO Auto-generated method stub
            // Making HTTP request
            try {
                // Making HTTP request
                // check for request method
    
                if (method.equals("POST")) {
                    // request method is POST
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(URL);
                    httpPost.setEntity(new UrlEncodedFormEntity(postparams));
    
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                } else if (method == "GET") {
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    /*
                     * String paramString = URLEncodedUtils .format(postparams,
                     * "utf-8"); URL += "?" + paramString;
                     */
                    String paramString = "";
                    int i = 0;
                    for (i = 0; i < postparams.size(); i++) { // foreach loop
                        NameValuePair nm = postparams.get(i);
                        if (i == 0)
                            paramString += nm.getValue();
                        else
                            paramString += "/" + nm.getValue();
    
                    }
                    if (i > 0)
                        URL += "/" + paramString;
                    Log.w("myApp", URL);
                    HttpGet httpGet = new HttpGet(URL);
    
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }
    
                // read input stream returned by request into a string using
                // StringBuilder
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "utf-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
    
                // create a JSONObject from the json string
                jObj = new JSONObject(json);
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // return JSONObject (this is a class variable and null is returned if
            // something went bad)
            return jObj;
    
        }
    }
    

    我正在使用此函数来数据绑定微调器

    private BackGroundTask bgt;
    Spinner dropdown1;
    Button button_UseSelectedItem;
    ArrayList<sobject2> arrayListem = new ArrayList<sobject2>();
    public void buildCountryDropDown() {
        // EditText textbx = (EditText)findViewById(R.id.editText1);
        // Building post parameters, key and value pair
        List<NameValuePair> apiParams = new ArrayList<NameValuePair>();
        apiParams.add(new BasicNameValuePair("idx", "BL"));
        arrayListem.clear();
        bgt = new BackGroundTask(
                "http://10.200.1.167/json/Service1.svc/GetAllCustomers3",
                "GET", apiParams);
        try {
            JSONObject countryJSON = bgt.execute().get();
            // Getting Array of countries
            JSONArray countries = countryJSON
                    .getJSONArray("GetAllCustomers3Result");
            // looping through All countries
    
            arrayListem.add(new sobject2("seçim yapınız", "-1"));
    
            for (int i = 0; i < countries.length(); i++) {
    
                JSONObject c = countries.getJSONObject(i);
    
                sobject2 yeniDeger = new sobject2(c.optString("ad"),
                        c.optString("id"));
    
                arrayListem.add(yeniDeger);
            }
    
            dropdown1 = (Spinner) findViewById(R.id.dropdown1);
            ArrayAdapter<sobject2> myAdapter = new ArrayAdapter<sobject2>(this,
                    android.R.layout.simple_spinner_item, arrayListem);
            dropdown1.setAdapter(myAdapter);
    
    
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    
    }
    

    我正在填写我的列表视图

        private BackGroundTask bgt_listview;
    ListView listview1;
    AlertsAdapter arrayAdapter2;
    ArrayList<alertx> arrayListem2 = new ArrayList<alertx>();
    
    public void buildListView(String paramx) {
        // EditText textbx = (EditText)findViewById(R.id.editText1);
        // Building post parameters, key and value pair
        List<NameValuePair> apiParams = new ArrayList<NameValuePair>();
        apiParams.add(new BasicNameValuePair("idx", paramx));
        arrayListem.clear();
        bgt_listview = new BackGroundTask(
                "http://10.200.1.167/json/Service2.svc/getOrders", "GET",
                apiParams);
    
        try {
            JSONObject countryJSON = bgt_listview.execute().get();
            // Getting Array of countries
            JSONArray countries = countryJSON
                    .getJSONArray("getOrdersParamResult");
            // looping through All countries
    
            for (int i = 0; i < countries.length(); i++) {
    
                JSONObject c = countries.getJSONObject(i);
    
                alertx yeniDeger = new alertx(c.optString("CustomerID"),
                        c.optString("OrderID"));
    
                arrayListem2.add(yeniDeger);
            }
    
            listview1 = (ListView) findViewById(R.id.listem1);
            arrayAdapter2 = new AlertsAdapter(this, R.layout.listitems,
                    arrayListem2);
            listview1.setAdapter(arrayAdapter2);
    
            /*----------------------------------------------------------------*/
    
            /**********************************************************************************/
    
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    
    }
    

    这些是buttonevents

        public void butonEventt(View view) {
        buildCountryDropDown();
    }
    
    public void butonEventtListe(View view) {
        buildListView("BLO");
    }
    

    首先我点击butonEventt for spinner,然后点击butonEventtListe for listview.But spinner在点击第二个按钮后丢失了它的内容。 感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

我认为这与您使用异步任务周围的事件错误有关。

单击“开”按钮,清除列表,并告知从Web资源加载异步任务。

但是你马上继续并使用结果重新填充列表。但是,由于它是异步任务,主线程不会等待它完成。因此无法保证已访问Web资源,并且及时返回列表。

所以你基本上是清理列表,然后不再添加任何内容。

要添加到列表中的代码应位于异步任务的onPostExecute()方法内。这是doinBackground()中实现的任何事情应该传递到UI线程的地方。

阅读android Docs以获取此基本示例。