2

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

        }
    });
 }
}
1

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, you can add it to your code. If you did not understand it I will suggest you read Google doc here -developer.android.com/training/volley/simple.html
Are you asking them to implement it for you?
This answer give enough context to answer your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.