How to send data from android to mysql server?

孤街醉人 提交于 2019-12-03 20:45:27

You need to write Api where you can pass the data from android and and fetch that data in Api and store in database using insert query. On android side you have to do below code:

My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name

package fourever.amaze.mics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


public class PutUtility {

    private Map<String, String> params = new HashMap<>();
    private static HttpURLConnection httpConnection;
    private static BufferedReader reader;
    private static String Content;
    private StringBuffer sb1;
    private StringBuffer response;

    public void setParams(Map<String, String> params) {
        this.params = params;
    }

    public void setParam(String key, String value) {
        params.put(key, value);
    }

    public String getData(String Url) {


        StringBuilder sb = new StringBuilder();

        try {
            // Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

            // Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();



            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception ex) { }
        }

        return response.toString();
    }


    public String postData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            value = params.get(key);


            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
            // Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

            // Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }


        return response.toString();
    }


    public String putData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            try {
                value = URLEncoder.encode(params.get(key), "UTF-8");
                if (value.contains("+"))
                    value = value.replace("+", "%20");

                //return sb.toString();


                // Get the server response

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
            // Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

            // Send PUT data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("PUT");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(false);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            ;
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb1.append(line + " ");
            }

            // Append Server Response To Content String
            Content = sb.toString();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }
        // Send PUT data request
        return Url;

    }


    public String deleteData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {

            try {
                // Defined URL  where to send data

                URL url = new URL(Url);

                URLConnection conn = null;
                conn = url.openConnection();

                // Send POST data request
                httpConnection = (HttpURLConnection) conn;
                httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConnection.setRequestMethod("DELETE");
                httpConnection.connect();


                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String line = null;

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb1.append(line + " ");
                }

                // Append Server Response To Content String
                Content = sb.toString();


            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }



        }
        return Url;

    }

And use this class like this. this class Automatically do internet connection and give you response from server :

    private class ServiceLogin extends AsyncTask<String, Void, String> {

            ProgressDialog mProgressDialog;
            private String res;

            @Override
            protected void onPreExecute() {
                mProgressDialog = ProgressDialog.show(LoginActivity.this,
                        "", "Please wait...");
            }

            @Override
            protected String doInBackground(String... params) {
                res = null;
                PutUtility put = new PutUtility();

                put.setParam("UserId", params[0].toString());
                put.setParam("Latitude", params[1].toString());
                put.setParam("Longitude", params[2].toString());
                put.setParam("DateTime", params[3].toString());

                try {
                    res = put.postData("INSERT URL of API HERE");
                    Log.v("res", res);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return res;

            }

            protected void onPostExecute(String res) {
                //"Here you get response from server in res"

            }
        }

Now you can call this service on button click and insert data in service like below:

new ServiceLogin().execute(pass four parameters here);

Hope this helps you

EDIT:

This is simple PHP Api for insert data

<?php include('connection.php');

$return_arr = array();

 $UserId=($_POST['UserId']);
 $Latitude=($_POST['Latitude']);
 $Longitude=($_POST['Longitude']);
$DateTime=($_POST['DateTime']);


        $user_register_sql1 = "INSERT INTO `activity`(`Id`,`UserId`, `Latitude`,`Longitude`,`DateTime`) values (NULL,'".$UserId."','".$Latitude."','".$Longitude."','".$DateTime."')"; 
             mysql_query($user_register_sql1);
             $row_array['errorcode1'] = 1; 

}
?>

You need an api in the server side which will accept json request as POST and it will save data in your Mysql database. You can take any android library like Retrofit and Volley to do request from android side.

Using Retrofit

let's say your pojo is:

public class User {
    private String id;
    private String latitude;
    private String longitude;
public User(String id, String latitude,String longitude) {
    this.id = id;
    this.latitude = latitude;
    this.longitude = longitude
   }
}

Our endpoint would look like the following:

@POST("/users/new")
Call<User> createUser(@Body User user);

Retrofit will take care of JSON yourself. You should have something like:

User user = new User(123, "33.43", "34.34");
Call<User> call = apiService.createuser(user);
call.enqueue(new Callback<User>() {
  @Override
  public void onResponse(Call<User> call, Response<User> response) {

  }

  @Override
  public void onFailure(Call<User> call, Throwable t) {

  }

Here you are using traditional methods to send data To do this way follow below steps.

1) in your build.gradle file add this

useLibrary 'org.apache.http.legacy'

 compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
    compile('org.apache.httpcomponents:httpmime:4.3') {
        exclude module: "httpclient"}

2) create json parser

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

@SuppressWarnings("deprecation")
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            //Log.d("defaultHttpClient" ,"IN");
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            //Log.d("url" ,url);
            HttpPost httpPost = new HttpPost(url);
            //Log.d("params" ,params.toString());
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            //Log.d("httpPost" , new UrlEncodedFormEntity(params).toString());
            HttpResponse httpResponse = httpClient.execute(httpPost);
            //Log.e("Entry", "1");
            HttpEntity httpEntity = httpResponse.getEntity();
            //Log.e("Entry", "2");
            is = httpEntity.getContent();
            //Log.e("Entry", "3");  
        } catch (UnsupportedEncodingException e) {
            //Log.e("UnsupportedEncodingException", "UnsupportedEncodingException");
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            //Log.e("ClientProtocolException", "ClientProtocolException");
            e.printStackTrace();
        } catch (IOException e) {
            //Log.e("IOException", "IOException");
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            //Log.e("Entry", "4");
            while ((line = reader.readLine()) != null) {
                //Log.e("line", line);
                sb.append(line + "\n");
            }
            //Log.e("Entry", "5");
            is.close();
            //Log.e("Entry", "6");
            json = sb.toString();
            //Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            if(json.length()>0){
                jObj = new JSONObject(json);
            }else{
                jObj = new JSONObject();
            }
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

3) create on class named as UserFunctions

    public class UserFunctions {
        private JSONParser jsonParser;
        Context ctx ;


        // constructor
        public UserFunctions(Context context){
            ctx = context;
            jsonParser = new JSONParser();
        }

    // create on function to send the value to server and get the json response back
    public JSONObject sendDataToSever(String val1, String val2,String val3){
        JSONObject json = null;
        try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("val1", val1));
                params.add(new BasicNameValuePair("val2", val2));
                params.add(new BasicNameValuePair("val3", val3));
                json = jsonParser.getJSONFromUrl(Constants.BASE_URL, params);
           } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return json;
    }
  }

4) in you main activityclass

// befor onCreate add 
UserFunctions uf;
ProgressDialog pDialog;
JSONObject DATA_JSON;

// in onCreate method

uf = new UserFunctions(Mainactivity.this);

// after getting the location lat and long call AsyncTask to send data to server.

// call asynctask like this here and write the aasyncctask functionality in the end of the class

new LoadWebPageTask().execute();  // calling async task

5) LoadWebPageTask asnc task

private class LoadWebPageTask extends AsyncTask {

protected void onPreExecute() { 
            pDialog = new ProgressDialog(
                    Mainactivity.this);
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

       protected Void doInBackground(Void... unused) {
            runOnUiThread(new Runnable() {
                public void run() {
                    DATA_JSON = uf.sendDataToSever(val1, val2,val3);

                }
            }); 
            return (null);
        }

        protected void onPostExecute(Void unused) {
            // closing progress dialog
            pDialog.dismiss();
           // do your own logics here
        }
    }

This will send data to the server as post method you can process this as post method by using $_POST[];

Please try like this. May this will help you.

For the server side

1) create on Database class

<?php
class Database{

    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "db_name";
    private $username = "root";
    private $password = "password";



    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

2) create another class to write all DB functionalities here name as Common

<?php
class Common{
    // database connection
    private $conn;  

    // getErrors
    public $error = array();

    public function __construct($db){
        $this->conn = $db;
    }

    // Save error to file
    function save_error($err){
        try {

            if(!is_dir("ERROR")){mkdir("ERROR");}

            $filename = "ERROR/".$this->getDate().".txt";

            if (!$handle = fopen($filename, 'a')) {echo "Cannot open file ($filename)"; return;}

            // Write $somecontent to our opened file.
            if (fwrite($handle, $err."\r\n") === FALSE) {echo "Cannot write to file ($filename)";return;}   

            fclose($handle);
        } catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }
    }

    // used for the 'created'
    function getTimestamp(){
        date_default_timezone_set('Asia/Calcutta');
        return  date('Y-m-d H:i:s');
    }

    // used for the 'created'
    function getDate(){
        date_default_timezone_set('Asia/Calcutta');
        return  date('Y-m-d');
    }

// create function to insert data into db

function syncLocalAppData($_tableName, $colName, $values){
        try{

            $query = " REPLACE INTO  ".$_tableName." (".$colName.") VALUES (".$values."); ";
            //echo $query;
            //exit;

            $stmt = $this->conn->prepare( $query );


            if($stmt->execute()){
                return true;
            }else{
                save_error("\r\nQRY : " . $stmt->queryString . " \r\n ERR CODE : " . $stmt->errorCode() . " \r\n ERR  : " .  json_encode($stmt->errorInfo()));
                 return false;
            }           

        } catch (Exception $e){
            save_error("\r\nOTHR : " . $e->getMessage());
            return false;
        }
    }
}

?>

3) create on php file to process the post data userApi.php

<?php
$_errAry = array("status"=>400, "success"=>"false", "message"=>"Can't Service your request ","data"=>array()); // error reprting json
$_sucAry = array("status"=>200, "success"=>"true", "message"=>"","data"=>array()); // sccess rrespose json


nclude_once 'database.php';

// get database connection
$database = new Database();
$db = $database->getConnection();



// instantiate Common Objects
include_once 'objects/common.class.php';

$_tbl=""; $_cols="";  $_ord=""; 
$_whr="  ";


if(isset($_POST["val1"],$_POST["val2"],$_POST["val3"])){

$val1=$_POST["val1"];
$val2=$_POST["val2"];
$val3=$_POST["val3"];

$tableName="yourTableName";
$ColNameString="your coma separated coloumns name";
$ValueString="'".$val1."','".$val2."','".$val3."';
$_comm = new Common($db);
            $return=$_comm-> syncLocalAppData($tableName,$ColNameString,$ValueString);
if($return){
        $_op = $_sucAry;
        $_op["data"]=array("status"=>true),
        echo json_encode($_op);
        exit(0);
}else{
        $_op = $_sucAry;
        $_op["success"]= "false";
        $_op["message"]="cant process your request,
        echo json_encode($_op);exit(0);
}
}

Should i have to create a activity class same as i created user class?

Yes.

The easiest solution is convert your activity object into a JSON object. Send it via a post request with your HTTP lib (I would recommend using OKHttp http://square.github.io/okhttp/). And finally write a php script wich will handle the request, get the object from the JSON and save it into your database.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!