更改来自 webrequest ASYNCTASK Android 应用程序的文本框中的文本

Change text in textbox from webrequest ASYNCTASK Android Application

我正在尝试更新 Android 应用程序的 XML 文件中的文本框,但不知道如何在 MainActivity Class 之外访问它。我是 Android 应用程序的新手,我必须为学校开展一个项目,其中 Android 应用程序将通过 HttpRequest 与 Raspberry Pi 进行通信。我正在尝试从 raspberry pi 发出 httpget 请求,并从 Pi 获取值并在 Android 应用程序的屏幕上更新它。我只是不知道如何从另一个 class 更新文本框。我真的很困惑=/任何帮助表示赞赏。谢谢

变量 HttpStuff 是我要更新的文本框。当我按下按钮时,它应该调用 webrequest class 并获取响应,然后在 postExecute() 方法上我希望它用结果更新文本框。

这是我尝试实现的代码:

public class MainActivity extends ActionBarActivity {

TextView HttpStuff;
Button refreshButton;
Button Connect;
EditText ipText;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    refreshButton = (Button)findViewById(R.id.refreshbutton);
    Connect = (Button)findViewById(R.id.connect);
    ipText = (EditText)findViewById(R.id.raspberryiptext);
    HttpStuff = (TextView) findViewById(R.id.datadisplay);



    Connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {
                Toast.makeText(MainActivity.this, "Connecting....", Toast.LENGTH_SHORT).show();
                RequestTask httpget = new RequestTask();
                httpget.execute("http://" + ipText.getText());
                //setContentView(R.layout.activity_main);
                //HttpStuff.setText(response);
            } catch (Exception d) {
                //Toast.makeText(MainActivity.this, "Failed!!", Toast.LENGTH_SHORT).show();
                //setContentView(R.layout.ip_configuration);
            }
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

class RequestTask 扩展了 AsyncTask {

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = "";
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            out.close();
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        //TODO Handle problems..
    }
    return responseString;
}

@Override
protected void onPostExecute(String result) {

MainActivity test = new MainActivity();
    test.HttpStuff.setText(result);


}

当您创建 activity 的新实例时,您不会影响真正的 activity 对象(由 android 系统管理),因为它们被处理作为虚拟机的 2 个不同对象;

解决方案 1:将 TextView public 设为静态,然后在 onPostExecute 方法中以这种方式访问​​它:

MainActivity.HttpStuff.setText(result)

解决方案 2:添加一个 Context 对象作为 RequestTask 中的字段 class 并作为构造函数中的参数,如下所示:

public class RequestTask extends AsyncTask...{
    private Context context;
    //.........
    public RequestTask(Context context){
        this.context = context;
    }
    //.........
    //Now in the onPostExecute, just use the Context object to grab the view
    public void onPostExecute(String result){
       TextView httpStuff = (TextView) context.findViewById(R.id.datadisplay);
       httpStuff.setText(result);
    }

您也可以直接将 TextView 作为参数而不是 Context 对象传递,但是使用 Context 会更好,尤其是当您要在外部任务中处理多个视图时 class。