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

时间:2015-09-28 03:42:24

标签: java android android-asynctask httpwebrequest

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

变量HttpStuff是我想要更新的文本框。当我按下按钮时,它应该调用webrequest类并获取响应,然后在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);
}

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


}

1 个答案:

答案 0 :(得分:2)

当您创建活动的新实例时,您不会影响真实活动对象(由android系统管理),因为它们被虚拟机视为2个不同的对象; < / p>

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

MainActivity.HttpStuff.setText(result)

解决方案2:在RequestTask类中将Context对象添加为字段,并在构造函数中添加如下参数:

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会更好,尤其是当您想要在外部任务类上处理多个视图时。