Android HTTPPOST 在错误处理和暂停方面存在问题


Android HTTPPOST issues with error handling and pausing

我对为Android编写应用程序非常非常陌生,所以我希望这不会被视为浪费其他人的时间。我也非常确定我的代码不是很好,所以尽量不要笑。

我正在尝试将值从我的应用程序发送到远程 PHP 表单。虽然我所拥有的似乎在将信息发送到表单方面工作得很好,但如果应用程序没有连接到互联网并且我无法发送任何内容,我无法弄清楚我应该如何处理错误,所以我不确定如何让它显示 Toast 或错误消息以通知用户该消息从未发送以及原因。

我也不确定在显示已发送的确认或错误时如何将所有内容暂停约 3-4 秒。在过去的 4 个小时里,我一直在为这些事情而苦苦挣扎,并浏览了 stackoverflow 和其他一些论坛,试图找到一些代码示例来给我"啊哈!"时刻,但没有这样的运气。

我希望有人可以帮助我或指出我做错了什么。谢谢!

我的整个代码如下:

package net.testapp.commenter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class suptest extends Activity implements OnClickListener{
private EditText name, email, phone, comment;
private Button postbutton;
private ProgressBar pbfirst;
private RelativeLayout pbdark, pbsent;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.suptest);
    // stuff in the layout
    name=(EditText)findViewById(R.id.editText1);
    email=(EditText)findViewById(R.id.editText2);
    phone=(EditText)findViewById(R.id.editText3);
    comment=(EditText)findViewById(R.id.editText4);
    postbutton=(Button)findViewById(R.id.sendButton);
    pbfirst=(ProgressBar)findViewById(R.id.progressBar1);
    pbdark=(RelativeLayout)findViewById(R.id.pbdark);
    pbsent=(RelativeLayout)findViewById(R.id.pbsent);
    // hide some stuff up front
    pbfirst.setVisibility(View.GONE);
    pbdark.setVisibility(View.GONE);
    pbsent.setVisibility(View.GONE);
    // post button listener thingy
    postbutton.setOnClickListener(this);
// Go back button
Button goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }
});
};
// clicking the send button
public void onClick(View v) {
        if(email.getText().toString().length()<1){
        // TODO LEARN HOW TO APPLY THIS TO OTHER FIELDS AS WELL
        // Remind user to fill in text fields
        Toast.makeText(this, "Please fill in all fields.", Toast.LENGTH_LONG).show();
        }else{
            //show my progress bar and dark fullscreen layout for "Sending" text to overlay
            pbdark.setVisibility(View.VISIBLE);
            pbfirst.setVisibility(View.VISIBLE);
            new MyAsyncTask().execute();        
        }
} 
// Where all the http post magic happens
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub
        postData(); 
        return null;
    }
    protected void onPostExecute(Double result){
        //make progress bar and dark background for "Sending" test vanish
        pbfirst.setVisibility(View.GONE);
        pbdark.setVisibility(View.GONE);
        //make sent confirmation appear
        pbsent.setVisibility(View.VISIBLE);
        // TODO FIGURE OUT HOW TO PAUSE ON SENT CONFIRMATION MESSAGE JUST LONG ENOUGH TO READ IT BEFORE FINISH()
        finish();
    }
    protected void onProgressUpdate(Integer... progress){
        pbfirst.setProgress(progress[0]);
    }
    public void postData() {
        // Strings for the layout stuff
        String  namer = name.getText().toString();
        String  emailer = email.getText().toString();
        String  phoner = phone.getText().toString();
        String  commenter = comment.getText().toString();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.mysite.net/commentform.php");
        try {
            // talk to the PHP script
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("name", namer));
            nameValuePairs.add(new BasicNameValuePair("email", emailer));
            nameValuePairs.add(new BasicNameValuePair("number", phoner));
            nameValuePairs.add(new BasicNameValuePair("comments", commenter));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // execute the http post
            @SuppressWarnings("unused")
            HttpResponse response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
    }
}
}

您可以通过在 ClientProtocolException 和 IOException 的 catch 块中添加代码来做到这一点,不是吗? 使用如下所示的代码来显示对话框,或者您可以只使用 android toasts...

    public void showDialog(final Activity activity, final String title, final String message) {
    activity.runOnUiThread(new Runnable() {
        public void run() {
            // 1. Instantiate an AlertDialog.Builder with its constructor
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            // 2. Chain together various setter methods to set the dialog
            // characteristics
            builder.setMessage(message).setTitle(title);
            // 3. Get the AlertDialog from create()
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });
}
好的,

我想我设法弄清楚了它崩溃的原因。显然,AsyncTask 是一个不同的线程,无法操纵 UI 的东西,所以我不得不把它放在我的捕获中以显示错误消息等等......

runOnUiThread(new Runnable() {
  public void run() {
    //And now for my one line of code to display the error message
     pber2.setVisibility(View.VISIBLE);
     }
});

我希望这至少在未来对其他人有所帮助!