我目前正在開發一個項目,我必須將數據添加到mysql數據庫。我使用Microsoft Azure作爲我的主機,一切工作正常。我得到的唯一問題是,當我嘗試使用「發佈」Web請求添加數據時,我沒有收到任何錯誤,但沒有添加任何內容。使用web請求將數據添加到mysql數據庫Android
這是我在Android Studio代碼,再沒有任何錯誤:
package com.example.antoinedepommereau.livre;
public class Login extends AppCompatActivity {
public static Dialog mydiag;
public static Button SignUpButton;
public static EditText firstnameTxt;
public static EditText lastnameTxt;
public static EditText emailsignupTxt;
public static EditText passwordsignupTxt;
public static EditText confirmpasswordTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login);
Button LoginButton = (Button) findViewById(R.id.btn_login);
final TextView SignUpText = (TextView) findViewById((R.id.link_signup));
final EditText emailTxt = (EditText)findViewById(R.id.input_email);
final EditText passwordTxt = (EditText)findViewById(R.id.input_password);
SignUpText.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
showDialog();
}
});
LoginButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if("".equals(emailTxt.getText().toString())){
emailTxt.setError("Email adress is required!");
return; }
if("".equals(passwordTxt.getText().toString())){
passwordTxt.setError("Password is required!");
return;
}
/* Intent startActivitylivre = new Intent(Login.this, livremain.class);
startActivity(startActivitylivre);*/
}
});
}
private void showDialog()
{
final Dialog mydiag = new Dialog(this);
//set the title
mydiag.setTitle("Sign Up");
//inflate the layout
mydiag.setContentView(R.layout.fragment_sign_up);
mydiag.show();
SignUpButton = (Button) mydiag.findViewById(R.id.btn_signup);
firstnameTxt = (EditText)mydiag.findViewById(R.id.login_firstname);
lastnameTxt = (EditText)mydiag.findViewById(R.id.login_lastname);
emailsignupTxt = (EditText)mydiag.findViewById(R.id.login_email);
passwordsignupTxt = (EditText)mydiag.findViewById(R.id.login_password);
confirmpasswordTxt = (EditText)mydiag.findViewById(R.id.login_passwordconfirm);
SignUpButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if ("".equals(firstnameTxt.getText().toString())) {
firstnameTxt.setError("Your first name is required!");
return;
}
if ("".equals(lastnameTxt.getText().toString())) {
lastnameTxt.setError("Your last name is required!");
return;
}
if ("".equals(emailsignupTxt.getText().toString())) {
emailsignupTxt.setError("You must enter a valid email adress!");
return;
}
/* if(passwordsignupTxt.getText().toString() != confirmpasswordTxt.getText().toString()){
confirmpasswordTxt.setError("Passwords are not matching");
return;
}*/
try {
getText();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Url expection!", Toast.LENGTH_LONG).show();
}
}
});
}
public void getText() throws UnsupportedEncodingException{
String name = firstnameTxt.getText().toString();
String email = emailsignupTxt.getText().toString();
String password = confirmpasswordTxt.getText().toString();
String data = URLEncoder.encode("Name", "UTF-8")
+ "=" + URLEncoder.encode(name, "UTF-8");
data += "&" + URLEncoder.encode("Email", "UTF-8") + "="
+ URLEncoder.encode(email, "UTF-8");
data += "&" + URLEncoder.encode("Password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://hitachipick.azurewebsites.net/SQLQuery.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
confirmpasswordTxt.setText(text);
}
}
然後我的PHP代碼:
<?php
$servername = "eu-cdbr-azure-north-e.cloudapp.net";
$username = "bdbad7b3d3b2da";
$password = "39d98912";
try
{
$conn = new PDO("mysql:host=$servername;dbname=Hitachi",$username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "connected succesfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if (isset($_POST['Name']) && isset($_POST['Email']) &&
isset($_POST['Password'])){
//Insert new contact into database
$query = $conn->prepare('INSERT INTO contact_info (contact_name,
contact_email, contact_password) VALUES (:name, :email, :password)');
$query->execute([
':name' => $_POST['Name'],
':email' => $_POST['Email'],
':password' => $_POST['Password']
]);
echo"done";
}
?>
到數據庫的連接工作正常因爲我得到「連接成功」,但沒有添加到數據庫中。我不知道問題來自哪裏。
希望你能幫助,
感謝您的幫助。
編輯:
現在,我使用拉維的代碼:`字符串urlParameters = 「NAME =」 +名字+ 「&電子郵件= 」+電子郵件+「 &密碼」 +密碼;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String request = "http://hitachipick.azurewebsites.net/SQLQuery.php";
URL url = new URL(request);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}`
但它仍然沒有工作....我添加了一個抓來查看錯誤日誌貓:
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
at java.net.InetAddress.getAllByName(InetAddress.java:752)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:209)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:163)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:105)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:489)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:465)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:503)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:130)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:261)
at com.example.antoinedepommereau.livre.Login.getText(Login.java:173)
at com.example.antoinedepommereau.livre.Login$3.onClick(Login.java:134)
at android.view.View.performClick(View.java:6261)
at android.widget.TextView.performClick(TextView.java:11185)
at android.view.View$PerformClick.run(View.java:23752)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
我很堅持,, pleasse hellpp ...
你去上班'done'? – Ravi
否....它不執行查詢.... –
這意味着您需要調試您是否在'POST'中獲得價值 – Ravi