如何在Android中获取EditText的更新值

时间:2014-08-02 10:17:56

标签: android android-asynctask

我是Android新手,在基本屏幕上工作,使用带有Android应用程序的网络服务。

我使用AsyncTask发布值并从webservice获取结果。它可以正常工作,直到显示返回的值。在点击时显示Toast消息时,我得到TextView resultReturned

的旧值
public class TestPost extends Activity{

private TextView result = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_screen);
    result = (TextView)findViewById(R.id.resultReturned);


    Button submit = (Button)findViewById(R.id.btnSubmit);

    submit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            String[] strPost = new String[]{"value1", "value2"};
            SendAsyncRequest asyncSend = new SendAsyncRequest();
            asyncSend.execute(strPost);
            // ResultView retains old value and gets correct value on second click
            String returned = result.getText().toString();
            Toast.makeText(getApplicationContext(), returned, Toast.LENGTH_LONG).show();    
        }
    }); 
  }

public class SendAsyncRequest extends AsyncTask<String, Void, String>{
    private String fetchedData = "";
    @Override
    protected String doInBackground(String... params  ) {
        // perform async task
        return fetchedData;
    }
    @Override
    protected void onPostExecute(String result) {
            setReturedValue(result);
    }

}
private void setReturedValue(String data){
    result.setText(data);
}

那么,如何获取TextView的更新文本值?

2 个答案:

答案 0 :(得分:1)

AsyncTask需要时间来获取请求的响应,在postExecute()方法中显示toast消息,就像这样,并从onclick中删除。

@Override
protected void onPostExecute(String result) {
    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();  
}

答案 1 :(得分:-1)

试试这个

submit.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String[] strPost = new String[]{"value1", "value2"};
        SendAsyncRequest asyncSend = new SendAsyncRequest();
        asyncSend.execute(strPost);
        // ResultView retains old value and gets correct value on second click
        String jsonResult;
        try {
            jsonResult=asyncSend.get();

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        Toast.makeText(getApplicationContext(), jsonResult, Toast.LENGTH_LONG).show();    
        }
});     

并在doInBackground()中返回您的Json字符串。