使用AsyncTask并使用结果填充TextViews,Buttons

时间:2015-01-31 22:40:13

标签: android json android-asynctask textview

我有一个问题要问你。似乎周围有类似的问题,但对我没有用。我使用AsynkTask来解析JSON odject,然后我想用结果来提供TextViews和Buttons等一些组件。虽然我花了几个小时测试一些例子但我无法让它工作。 起初我在doInBackground()中进行了解析:

public class PostDataAsyncTask extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            // do stuff before posting data
        }

        @Override
        protected String doInBackground(String... params) {
            String postResponse = "";
            try {
                // url where the data will be posted
                String postReceiverUrl = "http://server.com/Json/consumer.php";
                Log.v(TAG, "postURL: " + postReceiverUrl);

                // HttpClient
                HttpClient httpClient = new DefaultHttpClient();

                // post header
                HttpPost httpPost = new HttpPost(postReceiverUrl);

                // add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("ConsumerID", "52"));

                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // execute HTTP post request
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity resEntity = response.getEntity();
                // Convert response to String
                String result = EntityUtils.toString(response.getEntity());
                // TEST
                //postResponse = EntityUtils.toString(resEntity).trim();
                // CONVERT RESPONSE STRING TO JSON Object
                JSONObject json = new JSONObject(result);
                // Get the JSONArray "Consumer"
                JSONArray ja = json.getJSONArray("Consumer");
                //List<String> detailsList = new ArrayList<String>();
                // Creating the array that will hold the json items
                String[] info = new String[ja.length()];
                // Loop through all fields
                for (int i = 0; i < ja.length(); i++) {

                    JSONObject c = ja.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString("userid");
                    String fname = c.getString("userfullname");
                    String tel1 = c.getString("tel1");
                    String email = c.getString("email");
                    String address = c.getString("address");
                    String county = c.getString("county");
                    String country = c.getString("country");
                    String rpoints = c.getString("RedeemPoints");
                    String level = c.getString("Level");
                    // Add JSON object into the ArrayList
                    //detailsList.add(name);
                    // show the values in our logcat
                    Log.v(TAG, "User ID: " + id + "\n"+ "Username: "+ fname + "\n"+ "Redeem points: "+rpoints);
                }

                //Log.v(TAG, "Testing response: " +  postResponse);


            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return postResponse;
        }

        @Override
        protected void onPostExecute(String postResponse) {
            // do stuff after posting data
            if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
                //listener.onFailedLogin(postResponse);
                Toast.makeText(getBaseContext(),
                        "Response is empty", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getBaseContext(),
                        "Got results!!", Toast.LENGTH_LONG).show();
                //name.setText(fname);

            }
        }
    }

哪个没用,所以我尝试在on this再次显示在onPostExecute()中进行解析而没有运气......:

public class PostDataAsyncTask extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            EditText name = (EditText) findViewById(R.id.name);
            // do stuff before posting data
        }

        @Override
        protected String doInBackground(String... params) {
            String result = "";
            try {
                // url where the data will be posted
                String postReceiverUrl = "http://server.com/Json/consumer.php";
                Log.v(TAG, "postURL: " + postReceiverUrl);

                // HttpClient
                HttpClient httpClient = new DefaultHttpClient();

                // post header
                HttpPost httpPost = new HttpPost(postReceiverUrl);

                // add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("ConsumerID", "52"));

                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // execute HTTP post request
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity resEntity = response.getEntity();
                // Convert response to String
                postResponse = EntityUtils.toString(resEntity).trim();


                //Log.v(TAG, "Testing response: " +  postResponse);


            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return postResponse;
        }

        @Override
        protected void onPostExecute(String result) {
            // do stuff after posting data
            if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
                //listener.onFailedLogin(postResponse);
                Toast.makeText(getBaseContext(),
                        "Response is empty", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getBaseContext(),
                        "Got results!!", Toast.LENGTH_LONG).show();
                // TEST
                //postResponse = EntityUtils.toString(resEntity).trim();
                // CONVERT RESPONSE STRING TO JSON Object
                try {
                    JSONObject json = new JSONObject(result);
                    // Get the JSONArray "Consumer"
                    JSONArray ja = json.getJSONArray("Consumer");
                    //List<String> detailsList = new ArrayList<String>();
                    // Creating the array that will hold the json items
                    String[] info = new String[ja.length()];
                    // Loop through all fields
                    for (int i = 0; i < ja.length(); i++) {

                        JSONObject c = ja.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString("userid");
                        String fname = c.getString("userfullname");
                        String tel1 = c.getString("tel1");
                        String email = c.getString("email");
                        String address = c.getString("address");
                        String county = c.getString("county");
                        String country = c.getString("country");
                        String rpoints = c.getString("RedeemPoints");
                        String level = c.getString("Level");
                        name.setText(fname);
                        // Add JSON object into the ArrayList
                        //detailsList.add(name);
                        // show the values in our logcat
                        Log.v(TAG, "User ID: " + id + "\n"+ "Username: "+ fname + "\n"+ "Redeem points: "+rpoints);
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

你不能这样做。你需要使用&#34; publishProgress&#34;并且必须在onProgressUpdate中执行实现。