在线程内使用视图元素

时间:2014-02-20 22:02:26

标签: android multithreading httprequest

我正在尝试在Android中执行简单的HTTP请求。它必须在那里独立。但是我如何操作线程内的视图控件?

这就是我现在所拥有的:

public void saveData(final View v)
{
    Button btn = (Button) v.findViewById(R.id.button);
    btn.setText("Saving...");

    new Thread() {
        public void run()
        {
            HttpURLConnection connection = null;
            try {                   
                URL myUrl = new URL("http://example.com");
                connection = (HttpURLConnection)myUrl.openConnection();
                InputStream inputStream = connection.getInputStream();

                final String fResponse = IOUtils.toString(inputStream);

            }
            catch (MalformedURLException ex) {
                Log.e("aaa", "Invalid URL", ex);
            }
            catch (IOException ex) {
                Log.e("aaa", "IO Exception", ex);
            }
            finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }

           // How can I access v and btn here?     
           // btn.getText("Saved, thanks.");
           // btn.setText("Saved, thanks.");

        }

    }.start();
}

详细说明我正在努力实现的目标:

我有一个文本框和一个按钮。单击按钮后,我想从文本框中获取文本,在URL中使用,返回一个值,然后使用此值更新按钮文本。

2 个答案:

答案 0 :(得分:0)

如果您尝试直接从另一个此类线程访问您的视图,您将收到异常,因为必须在主线程上执行所有UI操作。

Android SDK为执行需要更新UI的后台任务提供的一种方法是AsyncTask

onPostExecute()返回后调用AsyncTask的{​​{1}}方法,并在UI线程上运行。

您的AsyncTask可能如下所示:

doInBackground()

答案 1 :(得分:0)

这是一个如何做到这一点的例子。

public class YourClass extends Activity {
    private Button myButton;
    //create an handler
    private final Handler myHandler = new Handler();

    final Runnable updateRunnable = new Runnable() {
        public void run() {
            //call the activity method that updates the UI
            updateUI();
        }
    };
    private void updateUI()
    {
      // ... update the UI     
    }

    private void doSomeHardWork()
    {
         //update the UI using the handler and the runnable
         myHandler.post(updateRunnable);
    }

    private OnClickListener buttonListener = new OnClickListener() {
        public void onClick(View v) {
            new Thread(new Runnable() {
                  doSomeHardWork();
            }).start();
        }
    };
}

如您所见,您需要使用另一个Runnable对象更新UI。这是一种做法。

另一种选择是通过runOnUiThread函数

runOnUiThread(new Runnable()
{
    @Override
    public void run() {
        updateActivity();
    }
});