1

我正在尝试将AsyncTask内部的地理编码反转以获取当前位置的地址。我想在开始活动时将EditText设置为默认地址。我的问题是,我无法在onPostExecute()中做到这一点,但是,我可以在runOnUiThread()doInBackground()以内做到这一点。为什么是这样?为什么我无法使用AsyncTask中的Geocoder更新onPostExecute中的EditText?

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

UPDATE

一些调试后,它看起来onPostExecute永远不会完全没有不管我做什么所谓。

事情我已经尝试:内onPostExecute

  • 日志信息:没有出现
  • 删除整个逻辑里面doInBackground所以它是这样的return "hello":onPOST等仍然不执行
+0

一切似乎都很好。你如何开始这个'AsynsTask'。可能是你正在调用'new MyAsyncTask()。doInBackground();'。是这样吗? – 2013-03-11 21:38:53

+0

嗯。不,我正在调用execute:S – 2013-03-11 22:02:57

+0

“我无法做到这一点”和“不起作用”并不是对您的症状进行特别详实的描述。 – CommonsWare 2013-03-11 23:02:22

回答

-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:在未来,而oavoid的问题,不要把在任何部分尝试UI操作{}

相关问题