0

我对为 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) {

        }
    }

}

}
4

2 回答 2

0

您可以通过在 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();
        }
    });
}
于 2013-09-16T02:18:12.857 回答
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);
     }
});

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

于 2013-09-17T17:49:25.313 回答