Saturday, March 19, 2016

Post message from Android app to server

This is just an example of how to automatically post a message to your server and have it mail to a specific email address using PHP's mail() function. This post was created to answer a Stack Overflow question. If you need any more help, or have questions, please post them on Stack Overflow.

Lets say you are building a car rental app where you want the app to message the car rental company on completion of the order. First, in your MainActivity class, you should save the user's name and other information to SharedPreferences or local SQL database. Assuming you have already saved the information into local variables, which you can find info on how to do that with Google, I'm going to skip that process. The important thing to notice here is the postMessage function. This is what is going to post the information to the server for emailing.

Add this to your build.gradle file's dependencies:
compile 'com.mcxiaoke.volley:library-aar:1.0.0'


Within your MainActivity's onCreate() method
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
 import android.app.ProgressDialog;
 import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.Toast;

 import com.android.volley.Request;
 import com.android.volley.Response;
 import com.android.volley.VolleyError;
 import com.android.volley.toolbox.StringRequest;

 import java.util.HashMap;
 import java.util.Map;

 public class NewComment extends AppCompatActivity 
  public String URL = "http://localhost/yourproject/sendmessage.php";
  public ProgressDialog pDialog;
  Button submitBtn;
  private String tstFirst = "John";
  private String tstLast = "Doe";
  private String tstCompany = "hertz";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.yourlayout);

   pDialog = new ProgressDialog(this);

   submitBtn = (Button)findViewById(R.id.button);


   submitBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     

     if (!cmttxt.isEmpty()) {
      //this is the important part where you would call your POST function
      //and add the variables for the user(firstname,lastname,rentalcompanyname)
      postComment(tstFirst, tstLast, tstCompany);
      
     } else {
      Toast.makeText(getApplicationContext(),
        "Please enter your details!", Toast.LENGTH_LONG)
        .show();
     }


    }
   });


  }

  
  //This is the important function you can call anywhere that would post the necessary
  //information to be sent to the rental company. You can add as many variable as you
  //need. For example, postMessage(String someString, String anotherString, String thirdString, String fourthString, and so
  //on); Just make sure you add those variables to the params section below.
  public void postMessage(final String fname, final String lname,
          final String cname) {
   pDialog.setMessage("Sending Message ...");
   showDialog();

   StringRequest strReq = new StringRequest(Request.Method.POST,
     URL, new Response.Listener<String>() {

    @Override
    public void onResponse(String response) {
     Log.d(AppConfig.TAG, "New Message Response: " + response.toString());
     hideDialog();
     
    }
   }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
     Log.e(AppConfig.TAG, "Message Error: " + error.getMessage());
     Toast.makeText(getApplicationContext(),
       error.getMessage(), Toast.LENGTH_LONG).show();
     hideDialog();
    }
   }) {

    @Override
    protected Map<String, String> getParams() {
     // Posting params to register url
     Map<String, String> params = new HashMap<String, String>();
     params.put("firstname",fname);
     params.put("lastname", lname);
     params.put("rent_name", cname);//name of rental company
     //other parameters would go here that you need posted to your server

     return params;
    }

   };

   // Adding request to request queue
   VolleyController.getInstance().addToRequestQueue(strReq, AppConfig.TAG);

  }

  public interface PostCommentResponseListener {
   public void requestStarted();
   public void requestCompleted();
   public void requestEndedWithError(VolleyError error);
  }

  private void showDialog() {
   if (!pDialog.isShowing())
   pDialog.show();
  }

  private void hideDialog() {
   if (pDialog.isShowing())
   pDialog.dismiss();
  }
 }

And this will be your PHP code on your server:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php

// receiving the post params
    $name = $_POST['firstname'];
    $email = $_POST['lastname'];
    $company = $_POST['rent_name'];
 $email = null;
 
   if($company == hertz){
   $email = "some.email@mail.com";
   }

         $to = $email;
         $subject = "This is subject";
         
         $message = "<b>This is HTML message.</b>";
         $message .= "<h1>This is headline.</h1>";
         
         $header = "From:abc@somedomain.com \r\n";
         $header .= "Cc:afgh@somedomain.com \r\n";
         $header .= "MIME-Version: 1.0\r\n";
         $header .= "Content-type: text/html\r\n";
         
         $retval = mail ($to,$subject,$message,$header);
         
         if( $retval == true ) {
            echo "Message sent successfully...";
         }else {
            echo "Message could not be sent...";
         }
      ?>

Install XAMPP to test the PHP server code locally. For more info on PHP mail() function, go here.