0

我正在使用 HTTP 向我的 php 服务器脚本运行 POST。

当我尝试使用静态字符串时,我确实成功了,但我需要检索用户输入的数据。

尝试从用户输入中检索数据时。

索尼手机:运行时异常

在日食中:

Fatal Exception: AsycnTask #1 - java.lang.RunTimeException : An error occured while executing doInBackground()
at android.os.AsynkTask$3.FutureTask.finishCompletion(FutureTask.java:352)

主类:

case R.id.imageButtonServer:
    {
        textView = (TextView)findViewById(R.id.tvUserServerResponse);
        new HttpPostDemo().execute(textView);
        break;
    }

类 HttpPostDemo:

   public class HttpPostDemo extends AsyncTask<TextView, Void, String> 
{
    TextView textView;

    //Only present when trying to retrieve text from editText2 field//
    EditText editText2;


@Override
protected String doInBackground(TextView... params)     
{

    this.textView = params[0];
    BufferedReader inBuffer = null;
    String url = "http://myserver.com/android_java.php";
    String result = "fail";

            //This fails//
    String mail = editText2.getText().toString();

            //This runs//
    String mail = 'mail';

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("operanda", "5"));
        postParameters.add(new BasicNameValuePair("operandb", "6"));
        postParameters.add(new BasicNameValuePair("answer", "11"));
        postParameters.add(new BasicNameValuePair("mail", mail));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);

主.xml:

      <EditText
    android:id="@+id/editText2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Email Address"
    android:inputType="textEmailAddress" />
4

1 回答 1

0
  public class HttpPostDemo extends AsyncTask<TextView, Void, String> 
{
    TextView textView;

    //Only present when trying to retrieve text from editText2 field//
    EditText editText2; <- declared but not initialized

因为你没有初始化editText2;

所以在执行editText2.getText().toString();时会抛出一个NullPointerException.

我想你已经editText2在主要活动中检索了你的。然后只需将其作为参数传递给执行方法:

case R.id.imageButtonServer:
    {
        textView = (TextView)findViewById(R.id.tvUserServerResponse);
        new HttpPostDemo().execute(textView, editText2);
        break;
    }

并在doInBackground添加行:

this.editText2 = params[1];
于 2013-10-29T21:17:59.130 回答