sql >> データベース >  >> RDS >> Mysql

Androidからmysqlサーバーにデータを送信する方法は?

    Androidからデータを渡し、そのデータをApiにフェッチし、挿入クエリを使用してデータベースに保存できるApiを作成する必要があります。 Android側では、以下のコードを実行する必要があります:

    getData()、PostData、DeleteData()のクラスPutUtility。パッケージ名を変更するだけです

    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;
    
        }
    

    そして、このクラスをこのように使用します。このクラスは自動的にインターネット接続を行い、サーバーからの応答を提供します:

        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"
    
                }
            }
    

    これで、ボタンをクリックしてこのサービスを呼び出し、以下のようにサービスにデータを挿入できます。

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

    これがお役に立てば幸いです

    編集:

    これは、データを挿入するための単純なPHPAPIです

    <?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; 
    
    }
    ?>
    


    1. SQLで3か月以上経過したレコードを表示する

    2. mysqlがトリガーでlast_insert_id()を取得する

    3. MySQLは過去の日付(1200など)をサポートしていますか?

    4. Laravelのユーザーごとに一意のランダム値を生成してデータベースに追加する方法