1

AsyncTask現在の場所のアドレスを取得するために、内部のジオコードを逆ジオコーディングしようとしています。EditTextアクティビティを開始するときに、をデフォルトとしてアドレスに設定したいと思います。私の問題はonPostExecute()、でこれを行うことができないことですが、runOnUiThread()内部でそれを行うことができますdoInBackground()。どうしてこれなの?

AsyncTask:

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);
}

それは機能しません。しかし、私がそれに固執する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

onPostExecute の上に @Override を配置しませんでした。また、UI スレッド内で asynctask オブジェクトを作成する必要があります。

EDIT : 編集テキストは更新されません。これは、ポスト実行が終了した直後に消費されるためです。

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 : 将来の問題を回避するために、try{} のどの部分にも UI 操作を配置しないでください。

于 2013-06-28T12:59:57.267 に答える