Android Handler无法访问GUI元素

时间:2012-03-03 05:20:09

标签: android multithreading android-layout

我觉得有点愚蠢地问这个问题,因为我有另一个应用程序,这个工作正常或至少我认为它是相同的。我肯定需要另外一套眼睛,因为对我而言,它看起来应该有效。我的代码如下:

public class InventorySystemActivity extends Activity {
private EditText barcode;
private EditText proddesc;
private EditText quantity;
public String scan_result;
public int which;
private InventorySystemDB db;
public Item singleItem;
public Item[] itemList;
private Thread t;
Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case 1:
            barcode.setText(scan_result);
            proddesc.setText(singleItem.name);
            quantity.setText(singleItem.quantity);
            break;
        case 3:
            updateUI();
            pd.dismiss();
        }
    }
};
public static Intent in = new Intent("com.google.zxing.client.android.SCAN");
private ProgressDialog pd;
private Thread dbt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.db = new InventorySystemDB(this);
    try {
        this.db.createDataBase();
        this.db.openDataBase();
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.dbt = new Thread(this.db);
    setContentView(R.layout.main);
    Button scan = (Button) findViewById(R.id.scan);
    scan.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivityForResult(in, 0);
        }
    });
    Button search = (Button) findViewById(R.id.searchbutton);
    search.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            pd.show();
            which = 1;
            scan_result = barcode.getText().toString();
            dbt.start();
        }
    });
    barcode = (EditText) findViewById(R.id.barcodenum);
    proddesc = (EditText) findViewById(R.id.proddesc);
    quantity = (EditText) findViewById(R.id.prodquantity);
    pd = new ProgressDialog(this);
    pd.setMessage("Loading data...");
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            scan_result = intent.getStringExtra("SCAN_RESULT");
            barcode.setText(scan_result);
        } else if (resultCode == RESULT_CANCELED) {

        }
    }
}
private void updateUI() {
    barcode.setText(singleItem.upc);
    proddesc.setText(singleItem.name);
    quantity.setText("0");
}

}

我的所有主题都是它需要UPC号并从几个网站中提取信息。代码将消息发送到处理程序就好了,我使用线程和处理程序制作了一些这样的应用程序,不知道为什么我现在有这个问题。无论如何,我可以解除ProgressDialog,但我无法更新任何UI对象。这一切看起来都很好,所以我真的需要更多的眼睛。谢谢你们。

1 个答案:

答案 0 :(得分:0)

您需要在 runOnUIThread()

中进行用户界面更改