2017-10-08 7 views
-1

私は現在、mysqlデータベースにデータを追加する必要があるプロジェクトに取り組んでいます。私はホストとしてMicrosoft Azureを使用しており、すべて正常に動作しています。私が得る唯一の問題は、 'Post' Webリクエストを使用してデータを追加しようとすると、エラーは発生しませんが、何も追加されないということです。Webリクエストでmysqlデータベースにデータを追加します。Android

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

データベースへの接続が正常に動作していない。ここ

は再び一切のエラー、Androidのメーカーに私のコードです私は "正常に接続される"が、何もデータベースに追加されません。私は問題がどこから来ているのか分かりません。

希望すると、

ありがとうございました。

EDIT:

私は今ラヴィコードの使用しています: `文字列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ています...

+0

を拡張

クラスを使用すると、done' '得るのですか?AsinTaskクラスを使用して、それが動作するように取得するために管理しましたか – Ravi

+0

いいえ....クエリを実行しません.... –

+0

つまり、 'POST'で値を取得しているかどうかをデバッグする必要があります。 – Ravi

答えて

0

var_dump($POST)nullと表示された場合、リクエストが作成されるときに問題が発生します。

また、あなたのコードにリクエストタイプを指定していないことに気付きました。だから、おそらくちょうど指定する

conn.setRequestMethod("POST"); 

まだ動作しない場合、私のために働く以下のコードを使用してください。

// specify parameter and their value 
String urlParameters = "param1=a&param2=b&param3=c"; 

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); 
} 
+0

まだ動かない...私はlogcatsなどの情報を追加するための質問を編集しました。しかし、ありがとうございます –

+0

@AntoinedePommereauあなたは '='ここに署名してください ""&パスワード "+パスワード; '' – Ravi

+0

まだandroid.os.NetworkOnMainThreadExceptionエラーが発生します。私は実際にエラーがどこから来ているのか理解していません –

0

はsendFeedbackがAsyncTask {

@Override 
    protected String doInBackground(String[] params) { 
     // do above Server call here 


     ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
     postParameters.add(new BasicNameValuePair("Name", name)); 
     postParameters.add(new BasicNameValuePair("Email", email)); 
     postParameters.add(new BasicNameValuePair("Password", password)); 

     String responseString = null; 

     try 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://hitachipick.azurewebsites.net/SQLQuery.php"); 

      // no idea what this does :) 
      httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 

      // This is the line that send the request 
      HttpResponse response = httpclient.execute(httppost); 

      HttpEntity entity = response.getEntity(); 

      InputStream is = entity.getContent(); 
     } 
     catch (Exception e) 
     { 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 

     return""; 
    } 

    @Override 
    protected void onPostExecute(String message) { 
     //process message 
    } 


} 
関連する問題