1

我正在尝试在 an 中反转地理编码AsyncTask以获取当前位置的地址。我想EditText在开始活动时将地址设置为默认值。我的问题是我无法在 中执行此操作onPostExecute(),但是,我可以在runOnUiThread()内部执行此操作doInBackground()。为什么是这样?

异步任务:

protected String doInBackground(Void ...params) {
    Geocoder geocoder = new Geocoder(AddSpot.this, Locale.getDefault());
    List<Address> addresses = null;
    try {
        // Call the synchronous getFromLocation() method by passing in the lat/long values.
        addresses = geocoder.getFromLocation(currentLat, currentLng, 1);
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    if (addresses != null && addresses.size() > 0)
    {
        Address address = addresses.get(0);
        // Format the first line of address (if available), city, and country name.
        final String addressText = String.format("%s, %s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getLocality(),
                address.getCountryName());
        System.out.println(addressText);
        return addressText;
    }
    return null;
}
protected void onPostExecute(String address) { 
    EditText addrField=(EditText)findViewById(R.id.addr);
    addrField.setText(address);
}

那是行不通的。但是,当我将 a 插入runOnUiThread其中时,它会起作用:

 if (addresses != null && addresses.size() > 0)
                {
                    Address address = addresses.get(0);
                    // Format the first line of address (if available), city, and country name.
                    final String addressText = String.format("%s, %s, %s",
                            address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                            address.getLocality(),
                            address.getCountryName());

                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            EditText addrField=(EditText)findViewById(R.id.addr);
                            addrField.setText(addressText); 
                        }
                    });
                    System.out.println(addressText);
                    return addressText;
                }

更新

经过一些调试后,无论我做什么,似乎都不会调用 onPostExecute 。

我尝试过的事情:

  • onPostExecute里面的日志信息:不出现
  • 删除 doInBackground 中的整个逻辑,如下所示return "hello": onPost 仍然不执行
4

1 回答 1

-1

您没有将@Override 放在 onPostExecute 之上。还必须在 UI 线程内创建 asynctask 对象。

编辑:您的编辑文本没有更新,因为它在后执行完成后立即被消耗。

1)编写EditText addrField;作为活动类的类变量。2) 在 onCreate() 中找到对它的引用。3) 在您的原件上onpostexecute应该只保留addrField.setText(address);

有我的课,从 onPostexecute 更新文本字段没有任何问题

public class AddToCheckActivity extends Activity {
    // All static variables
    private ProgressDialog pd = null;
    // XML node keys
    TextView active;
    String addId = "";
    JSONObject json = null;
    ListView list;
    String not_id, not_section, not_street, not_sqTotal, not_sqLiving,
            not_sqKitchen, not_flat, not_floor, not_floors, not_text,
            user_phone1, user_phone2, user_contact, not_region, not_district,
            not_settle, not_price, not_photo, not_date, not_date_till, not_up,
            not_premium, not_status, region_title, district_title,
            settle_title, section_title, not_priceFor;
    LinearLayout lin;
    ImageView photo1;
    ImageView photo2;
    ImageView photo3;
    Activity app;
    ArrayList<String> photo_ids = new ArrayList<String>();
    TextView address;
    TextView date;
    TextView date_till;
    TextView description;
    TextView district;
    TextView flat;
    TextView floor;
    TextView floors;
    TextView id;
    TextView phone1;
    TextView phone2;
    TextView premium;
    TextView region;
    TextView section;
    TextView settle;
    TextView sqKitchen;
    TextView sqLiving;
    TextView sqTotal;
    TextView uped;
    TextView price;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aadd_addtocheck);
        app = this;
        lin = (LinearLayout) findViewById(R.id.lin);
        address = (TextView) findViewById(R.id.tv_atc_address);
        date = (TextView) findViewById(R.id.tv_atc_date);
        date_till = (TextView) findViewById(R.id.tv_atc_date_till);
        description = (TextView) findViewById(R.id.tv_atc_description);
        district = (TextView) findViewById(R.id.tv_atc_dstrict);
        flat = (TextView) findViewById(R.id.tv_atc_flat);
        floor = (TextView) findViewById(R.id.tv_atc_floor);
        floors = (TextView) findViewById(R.id.tv_atc_floors);
        id = (TextView) findViewById(R.id.tv_atc_id);
        phone1 = (TextView) findViewById(R.id.tv_atc_phone1);
        phone2 = (TextView) findViewById(R.id.tv_atc_phone2);
        premium = (TextView) findViewById(R.id.tv_atc_premium);
        region = (TextView) findViewById(R.id.tv_atc_region);
        section = (TextView) findViewById(R.id.tv_atc_section);
        settle = (TextView) findViewById(R.id.tv_atc_settle);
        sqKitchen = (TextView) findViewById(R.id.tv_atc_sqKitchen);
        sqLiving = (TextView) findViewById(R.id.tv_atc_sqLiving);
        sqTotal = (TextView) findViewById(R.id.tv_atc_sqTotal);
        uped = (TextView) findViewById(R.id.tv_atc_uped);
        price = (TextView) findViewById(R.id.tv_atc_price);
        Bundle ex = getIntent().getExtras();
        Log.d("Gues: ", "1");
        Button back_button = (Button) findViewById(R.id.back_btn);
        back_button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {

                Intent i = new Intent(getApplicationContext(),
                        ChooserActivity.class);
                startActivity(i);
                finish();
            }
        });
        pd = new ProgressDialog(app);
        pd.setOwnerActivity(app);
        pd.setTitle("Идет загрузка...");
        pd.setCancelable(true);
        if (ex != null) {
            addId = ex.getString("add_id");
            Log.d("Gues: ", "2");
            not_id = not_priceFor = not_section = not_street = not_sqTotal = not_sqLiving = not_sqKitchen = not_flat = not_floor = not_floors = not_text = user_phone1 = user_phone2 = user_contact = not_region = not_district = not_settle = not_price = not_photo = not_date = not_date_till = not_up = not_premium = not_status = region_title = district_title = settle_title = section_title = "";
            Log.d("Gues: ", "3");
            GetAdd addvert = new GetAdd();
            addvert.execute();
        }

    }

    public void onClickBtnAtcDelete(View v) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                UserFunctions u = new UserFunctions();
                u.deleteAdd(not_id);

            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
        startActivity(i);
        finish();
    }

    public void btnAtcEdit(View v) {
        Intent i = new Intent(getApplicationContext(), AddSaveActivity.class);

        final BitmapDrawable bitmapDrawable1 = (BitmapDrawable) photo1
                .getDrawable();
        final Bitmap yourBitmap1 = bitmapDrawable1.getBitmap();
        ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
        yourBitmap1.compress(Bitmap.CompressFormat.PNG, 90, stream1);
        byte[] imm1 = stream1.toByteArray();

        final BitmapDrawable bitmapDrawable2 = (BitmapDrawable) photo2
                .getDrawable();
        final Bitmap yourBitmap2 = bitmapDrawable2.getBitmap();
        ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
        yourBitmap2.compress(Bitmap.CompressFormat.PNG, 90, stream2);
        byte[] imm2 = stream2.toByteArray();

        final BitmapDrawable bitmapDrawable3 = (BitmapDrawable) photo3
                .getDrawable();
        final Bitmap yourBitmap3 = bitmapDrawable3.getBitmap();
        ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
        yourBitmap3.compress(Bitmap.CompressFormat.PNG, 90, stream3);

        byte[] imm3 = stream3.toByteArray();
        i.putExtra("photo1", imm1);
        i.putExtra("photo2", imm2);
        i.putExtra("photo3", imm3);
        i.putStringArrayListExtra("photo_ids", photo_ids);
        i.putExtra("not_id", not_id);
        i.putExtra("not_section", not_section);
        i.putExtra("not_street", not_street);
        i.putExtra("not_sqTotal", not_sqTotal);
        i.putExtra("not_sqLiving", not_sqLiving);
        i.putExtra("not_sqKitchen", not_sqKitchen);
        i.putExtra("not_flat", not_flat);
        i.putExtra("not_floor", not_floor);
        i.putExtra("not_floors", not_floors);
        i.putExtra("not_text", not_text);
        i.putExtra("not_phone1", user_phone1);
        i.putExtra("not_phone2", user_phone2);
        i.putExtra("not_region", not_region);
        i.putExtra("not_district", not_district);
        i.putExtra("not_settle", not_settle);
        i.putExtra("not_price", not_price);
        i.putExtra("not_date", not_date);
        i.putExtra("not_date_till", not_date_till);
        i.putExtra("region_title", region_title);
        i.putExtra("district_title", district_title);
        i.putExtra("section_title", section_title);
        i.putExtra("settle_title", settle_title);
        i.putExtra("not_priceFor", not_priceFor);
        startActivity(i);

    }

    public void onClickAtcGoToChooser(View v) {
        Intent i = new Intent(getApplicationContext(), MyAddActivity.class);

        startActivity(i);

        finish();
    }

    class GetAdd extends AsyncTask<Integer, Void, JSONObject> {
        // private ProgressDialog pd = null;
        private int op = 0;

        @Override
        protected void onPreExecute() {
            // pd = new ProgressDialog(app);
            // pd.setOwnerActivity(app);
            // pd.setTitle("Идет загрузка...");
            // pd.setCancelable(true);
            pd.show();
        }

        @Override
        protected JSONObject doInBackground(Integer... params) {
            // TODO Auto-generated method stub
            UserFunctions u = new UserFunctions();
            // json = u.getNewAdd(addId);
            return u.getNewAdd(addId);
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            pd.dismiss();
            active = (TextView) findViewById(R.id.tv_atc_active);

            photo1 = (ImageView) findViewById(R.id.imageP1);
            photo2 = (ImageView) findViewById(R.id.imageP2);
            photo3 = (ImageView) findViewById(R.id.imageP3);
            ImageLoader imi = new ImageLoader(app.getApplicationContext());
            if (result != null && result.has("not_id")) {
                try {

                    Log.d("Gues: ",
                            "5_1 to status " + result.getString("not_status"));

                    // active.setText(json.getString("not_status")+"");
                    not_status = ("" + result.getString("not_status"));
                    not_region = ("" + result.getString("not_region"));
                    not_district = ("" + result.getString("not_district"));
                    not_settle = ("" + result.getString("not_settle"));
                    not_section = ("" + result.getString("not_section"));
                    not_street = (result.getString("not_street"));
                    not_date = (result.getString("not_date"));
                    not_price = (result.getString("not_price"));
                    not_date_till = (result.getString("not_date_till"));
                    not_text = (result.getString("not_text"));
                    district_title = (result.getString("district_title"));
                    not_flat = (result.getString("not_flat"));
                    not_floor = (result.getString("not_floor"));
                    not_floors = (result.getString("not_floors"));
                    not_id = (result.getString("not_id"));
                    user_phone1 = (result.getString("user_phone1"));
                    user_phone2 = (result.getString("user_phone2"));
                    not_premium = (result.getString("not_premium"));
                    region_title = (result.getString("region_title"));
                    section_title = (result.getString("section_title"));
                    settle_title = (result.getString("settle_title"));
                    not_sqKitchen = (result.getString("not_sqKitchen"));
                    not_sqTotal = (result.getString("not_sqTotal"));
                    not_sqLiving = (result.getString("not_sqLiving"));
                    not_up = (result.getString("not_up"));
                    LinearLayout l = (LinearLayout) findViewById(R.id.appDetail);
                    if (Integer.parseInt(not_section) == 1981
                            || Integer.parseInt(not_section) == 1982) {
                        l.setVisibility(View.GONE);
                    }
                    not_priceFor = (result.getString("not_priceFor"));
                    String link1, link2, link3;
                    link1 = link2 = link3 = "";
                    JSONArray ar = result.getJSONArray("not_photos");
                    JSONArray pp = result.getJSONArray("photo_ids");
                    Log.d("ATC photo_ids", "-" + pp.length());
                    Log.d("ATC result", result.toString());
                    Log.d("ATC result pp", pp.toString());
                    Log.d("ATC result ppelement", pp.getString(0).toString());
                    for (int i = 0; i < pp.length(); i++) {
                        Log.d("ATC photo_ids pos", "-" + i);
                        Log.d("ATC result ppelement iter", pp.getString(i)
                                .toString());
                        photo_ids.add(pp.getString(i).toString());
                    }
                    // String[] ph = new String[3];
                    // for (int i =0; i< 3;i++){
                    // ph[i]=ar.getJSONObject(i).toString();
                    // }
                    imi.DisplayImage(ar.getString(0).toString(), photo1);
                    imi.DisplayImage(ar.getString(1).toString(), photo2);
                    imi.DisplayImage(ar.getString(2).toString(), photo3);
                    Log.d("Gues: ", "5_5");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                        }
                    });
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (Integer.parseInt(not_status) == 0) {
                    active.setText("Неактивно");
                } else {
                    active.setText("Активно");
                }
                address.setText("Улица: " + not_street);
                date.setText("Создано: " + not_date);
                date_till.setText("Действительно до: " + not_date_till);
                description.setText("Подробности объявления: " + "\n"
                        + not_text);
                district.setText("Город/поселок: " + district_title);
                if (Integer.parseInt(not_section) == 1981
                        || Integer.parseInt(not_section) == 1982) {
                    flat.setText("Машиномест: " + not_flat);
                } else
                    flat.setText("Количество комнат: " + not_flat);
                floor.setText("Этаж: " + not_floor);
                floors.setText("Этажность: " + not_floors);
                id.setText("ID: " + not_id + " ");
                phone1.setText("Телефон: " + user_phone1);
                phone2.setText("Телефон: " + user_phone2);
                if (Integer.parseInt(not_premium) == 0) {
                    premium.setText("Обычное");
                } else {
                    premium.setText(" Примиумное");
                }
                region.setText("Регион: " + region_title);
                section.setText("В рубрике: " + section_title);
                settle.setText("Район: " + settle_title);
                sqKitchen.setText("Площадь кухни: " + not_sqKitchen);
                sqTotal.setText("Общая площадь: " + not_sqTotal);
                sqLiving.setText("Жилая площадь: " + not_sqLiving);
                if (Integer.parseInt(not_up) == 0) {
                    uped.setText("");
                } else {
                    uped.setText(" Поднятое ");
                }
                String priceT = "";
                if (Integer.parseInt(not_priceFor) == 1)
                    priceT = "за все";
                else if (Integer.parseInt(not_priceFor) == 2)
                    priceT = "за кв.м";
                else if (Integer.parseInt(not_priceFor) == 3)
                    priceT = "за месяц";
                else if (Integer.parseInt(not_priceFor) == 4)
                    priceT = "в сутки";
                else if (Integer.parseInt(not_priceFor) == 5)
                    priceT = "в час";
                else if (Integer.parseInt(not_priceFor) == 6)
                    priceT = "за кв.м./месяц";
                else if (Integer.parseInt(not_priceFor) == 7)
                    priceT = "за сотку";
                price.setText("Цена: " + not_price + " грн. " + priceT);
                lin.setVisibility(View.VISIBLE);

            } else {
                error();
            }

        }
    }
}

PS : 为避免日后出现问题,请勿将 UI 操作放在 try{} 的任何部分

于 2013-06-28T12:59:57.267 回答