Search code examples
javaandroidjsonhttp-postsend

Send POST data from Android application to PHP MySQL


I am trying to send a data to WampServer. I am using the HttpUrlConnection, and I don't know how to send data - maybe in JSON form or XML. I have used the content values to hold values of variables that I want to send but I don't know how to send them to POST method in PHP script.

This is the PHP code:

<?php 

if(isset($_POST['txtname'])&&isset($_POST['txtemail']))
{
    require ('config.php');
    $con=mysqli_connect($servername,$username,$password,$db);
    $txtname=$_POST['txtname'];
    $txtemail=$_POST['txtemail'];
    mysqli_query($con,"insert into users (name,email) values('$txtname','$txtemail') ");
    echo "Inserted";
}

?>

And this is the Java code:

package com.subhi.addtoserver;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

   public EditText name,email;
    Button add;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name=(EditText)findViewById(R.id.name);
        email=(EditText)findViewById(R.id.email);
        add=(Button)findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                InsertData task1 = new InsertData();
                String name1, email1;
                name1 = name.getText().toString();
                email1 = email.getText().toString();
                task1.execute("http://192.168.1.100/add/index.php", name1, email1);

            }
        });
    }


    private class InsertData extends AsyncTask<String,Void,Boolean>
    {
        ProgressDialog dialog=new ProgressDialog(MainActivity.this);

        @Override
        protected Boolean doInBackground(String... urls) {

            for (String url: urls)
            {

                try {                      

                    ContentValues contentValues=new ContentValues();
                    contentValues.put("txtname",urls[1]);
                    contentValues.put("txtemail",urls[2]);

                    URL url1 =new URL(urls[0]);
                    HttpURLConnection urlConnection=(HttpURLConnection)url1.openConnection();
                    urlConnection.connect();

                } catch (MalformedURLException e) {
                    Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();;
                    e.printStackTrace();
                    return  false;
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();;
                    e.printStackTrace();
                    return false;
                }

            }

            return true;
        }

        @Override
        protected void onPreExecute() {

            dialog.setMessage("Sending Data....");
            dialog.show();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result==true)
            {

                Toast.makeText(getApplicationContext(),"Insert Success",Toast.LENGTH_LONG).show();;
            }
            else {
                Toast.makeText(getApplicationContext(),"Insert Fail",Toast.LENGTH_LONG).show();;
            }
            dialog.dismiss();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Solution

  • This is how you should send.

    echo json_encode(array("txtname"=>$txtname, "txtemail"=>'$txtemail'));
    

    And Client side in android. I hope you know, how to get the values from json.