Ahmed El-elaimy
Ahmed El-elaimy

Reputation: 35

how can I post a string variable from my android app to php script

I want a simple code to post a string variable from my android application to my php script.

php code:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "table";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$name=$_POST["name"];
$sql = "INSERT INTO t (name)
VALUES ('$name')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

I want a code to send my string to php and to be compatible with the php code, and I am sure that the php is working correctly.

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText text = (EditText) findViewById(R.id.x);
    Button btn = (Button) findViewById(R.id.b);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String name = text.getText().toString();

        }
    });
 }
}

Upvotes: 2

Views: 43

Answers (1)

Inducesmile
Inducesmile

Reputation: 2493

You can use Android Volley Post Method like below

String url = "PATH_TO YOUR_SERVER";

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>(){
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
            }
        },
        new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                // error
                Log.d("Error.Response", response);
            }
        }
) {
    @Override
    protected Map<String, String> getParams(){
        Map<String, String>  params = new HashMap<String, String>();
        params.put("NAME", name);
        return params;
    }
};
queue.add(postRequest);

Upvotes: 1

Related Questions