0

我想做一個android應用程序來寫一些MySQL數據庫上的數據,但它不起作用,我爲此做了一個Java類,我認爲問題來自於此。這裏是我的代碼:如何連接到我的MySQL數據庫與Android應用程序?

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

?> 

謝謝您的幫助!

+0

您的webservice/Api是否正確? –

+0

發佈你的'register.php'代碼。 –

+0

我認爲代碼將會發生在你的catch異常中,因爲沒有任何事情發生。嘗試查看堆棧跟蹤或創建一些日誌。 – Mike

回答

0

我的類PutUtility爲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"]; 
+0

它可以幫助你bro? –

+0

抱歉,我正在吃它完美的作品! !!非常感謝你非常非常!:) :) :) – Fred

+0

歡迎bro。:) :) :) –

相關問題