Android HTTPPOST会出现错误处理和暂停问题

时间:2013-09-16 02:09:30

标签: php android

我为Android编写应用程序非常非常新,所以我希望这不会浪费时间给别人。我也很确定我的代码不是很好,所以尽量不要笑。

我正在尝试将我的应用中的值发送到远程PHP表单。虽然我有什么似乎可以正常工作将信息发送到表单,我无法弄清楚如果应用程序没有连接到互联网我不应该发送任何东西,我应该如何处理错误,所以我不知道如何让它显示一个toast或错误消息,通知用户该消息从未发送过,为什么。

我还不确定当显示发送确认或错误时如何暂停所有内容约3-4秒。我花了最近4个小时在这些事情上苦苦挣扎,浏览stackoverflow和其他一些论坛试图找到一些代码示例给我“AH HA!”那一刻,但没有这样的运气。

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

我的整个代码如下:

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) {

        }
    }

}

}

2 个答案:

答案 0 :(得分:0)

你可以通过在catch块中为ClientProtocolException和IOException添加代码来实现这一点,不是吗?使用如下所示的代码来显示对话框,或者你可以使用android toast ...

    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();
        }
    });
}

答案 1 :(得分:0)

好吧,我想我已经弄清楚它崩溃的原因。显然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);
     }
});

我希望这至少可以帮助其他人!