如何使用Android应用程序连接到我的MySQL数据库?

时间:2017-02-15 10:42:57

标签: java android android-layout android-studio android-fragments

我正在尝试做一个Android应用程序在MySQL数据库上写一些数据,但它不起作用我为此做了一个Java类,我认为问题来自于此。这是我的代码:

public class BackgroundTask extends AsyncTask<String, Void, String> {

    Context ctx;

    BackgroundTask(Context ctx) {this.ctx = ctx;}

@Override
    protected String doInBackground(String... params) {
        String reg_url = "http://localhost:8080/project/register.php";
        String method = params[0];
        if (method.equals("register")) {

            String name = params[1];
            String password = params[2];
            String contact = params[3];
            String country = params[4];

            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream os = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
                        URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(contact, "UTF-8") + "&" +
                        URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                os.close();
                InputStream IS = httpURLConnection.getInputStream();
                IS.close();
                return "Registration success";


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

}

实际上我想要的是在我的数据库中保存名称,密码,联系人和国家/地区。问题是:“注册成功”永远不会返回它始终为空。但我不知道为什么。当我尝试编译它看起来没有错误,我可以看到该应用程序。 非常感谢你的帮助!

编辑:这是register.php:

<?php

require "init.php";

$u_name=$_POST["name"];
$u_password=$_POST["password"];
$u_contact=$_POST["contact"]";
$u_country=$_POST["country"];

$sql_query="insert into users values('$u_name', '$u_password', '$u_contact', '$u_country');";

//mysqli_query($connection, $sql_query));


if(mysqli_query($connection,$sql_query))
{

//echo "data inserted";

}

else{

//echo "error";

}



?>

还有init.php:

<?php

$db_name = "project";
$mysql_user = "root";
$server_name = "localhost";

$connection = mysqli_connect($server_name, $mysql_user, "", $db_name);

if(!$connection){

    echo "Connection not successful";
}
else{

    echo "Connection successful";
}

?>

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我的类PutData用于getData(),PostData,DeleteData()。你只需要更改包名称

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;

    }
}

并像这样使用这个类

 @Override
        protected String doInBackground(String... params) {

            res = null;
            PutUtility put = new PutUtility();

            put.setParam("ueid", params[0]);
            put.setParam("firm_no", params[1]);
            put.setParam("date_incorporation", params[2]);
            put.setParam("business_name", params[3]);
            put.setParam("block_no", params[4]);

            try {

                    res = put.postData(
                            "Api URL here");

                Log.v("res", res);
            } catch (Exception objEx) {
                objEx.printStackTrace();
            }

            return res;
        }


@Override
        protected void onPostExecute(String res) {

            try {

            } catch (Exception objEx) {
                mProgressDialog.dismiss();
                objEx.printStackTrace();
            }
        }

请使用此。希望它也能帮助你。  如果这是问题,请检查

$u_contact=$_POST["contact"]"

这是我认为兄弟的问题。替换为

$u_contact=$_POST["contact"];