2017-02-07 103 views
0

我正在做一些分配,并且需要在本地主机服务器上启用SQLite DB数据同步到MySQL数据库。点击按钮时,来自SQLite的数据需要被“收集”,转换为JSON并发送到本地MySQL数据库并插入到那里。我做了一个Activity来处理这个工作,根据学院的例子做了一些PHP,并且让wamp服务器运行在我创建需要存储数据的数据库的地方。 在我的本地主机数据库上被命名为employes_db,并且内部的表被命名为employes。 下面是Android Studio中的代码,我提出:Android - 在本地主机服务器上发布从Android SQLite数据库到MySQL数据库的数据

package com.EmDatabase; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Toast; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

public class DataSyncManager extends Activity { 

Database db; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.sync_options); 
    db = new Database(this); 
    db.getWritableDatabase(); 
} 

public void syncToServer(View v) throws JSONException { 
    List<Employe> employes = db.selectAll(); 
    JSONObject objEmployes = new JSONObject(); 
    JSONArray employesData = new JSONArray(); 
    for (Employe employe : employes) { 
     int id = employe.getId(); 
     String name = employe.getName(); 
     String surname = employe.getSurname(); 
     int age = employe.getAge(); 
     String company = employe.getCompany(); 
     String wtype = employe.getWorktype(); 
     JSONObject empData = new JSONObject(); 
     empData.put("id", id); 
     empData.put("name", name); 
     empData.put("surname", surname); 
     empData.put("age", age); 
     empData.put("company", company); 
     empData.put("worktype", wtype); 
     employesData.put(empData); 
    } 
    objEmployes.put("all_employes", employesData); 
    String result = objEmployes.toString(); 
    System.out.println(result); 
    UploadJsonStringTask task = new UploadJsonStringTask(); 
    task.execute(
      new String[] { "http://10.0.2.2/employes_db/register.php", result} 
    ); 
} 

public void syncFromServer(View v) { 

} 

private class UploadJsonStringTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     String response = ""; 
     Map<String,String> queries = new HashMap<String, String>(1); 
     queries.put("all_employes", params[1]); 
     try { 
      response += postHttpContent(params[0],queries); 
     } catch (IOException e) { 
      Log.e("error", e.toString()); 
     } 
     return response; 
    } 
    @Override 
    protected void onPostExecute(String result) { 
     Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); 
    } 

    public String postHttpContent(String urlString, Map<String, String> queries) throws IOException { 
     String response = ""; 
     URL url = new URL(urlString); 
     HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); 
     httpConnection.setDoInput(true); 
     httpConnection.setDoOutput(true); 
     httpConnection.setUseCaches(false); 
     httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

     String postData = ""; 
     for (String key : queries.keySet()) { 
      postData += "&" + key + "=" + queries.get(key); 
     } 
     postData = postData.substring(1); 
     DataOutputStream postOut = new DataOutputStream(httpConnection.getOutputStream()); 
     postOut.writeBytes(postData); 
     postOut.flush(); 
     postOut.close(); 

     int responseCode = httpConnection.getResponseCode(); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      String line; 
      BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); 
      while ((line = br.readLine()) != null) { 
       response += line; 
      } 
     } else { 
      response = ""; 
      throw new IOException(); 
     } 
     return response + " *** Uploaded!"; 
    } 
} 

public void goBack(View v) { 
    Intent in= new Intent(DataSyncManager.this,MainActivity.class); 
    startActivity(in); 
} 

}

这里是PHP文件,我做了,并插入到wampserver/WWW/employes_db(register.php):

<?php 
$id = 0; 
$name = ""; 
$surname = ""; 
$age = 0; 
$company = ""; 
$worktype = ""; 
$conn = new mysqli("localhost","root","","employes_db"); 
$conn->query("insert into employes values (null,'".$_POST['id']."','".$_POST['name']."','".$_POST['surname']."','".$_POST['age']."','".$_POST['company']."','".$_POST['worktype']."')"); 
if(!$conn->error) echo "{status:0}"; else echo "{status:-1}"; 
?> 

当我启动应用程序时,在SQLite数据库中插入一行,比命中同步按钮,并打开“localhost/employes_db/register.php”我得到“错误” - >注意:未定义的索引:id在C:\ wamp64 \ www \ employes_db \ register.php第9行< - 同样的错误对于休息列(姓名,年龄,公司,wtype)。 有人可以帮忙,我的错误在哪里?

回答

1

Undefined index: id表示$_POST['id']不存在。第一个错误是您使用$_POST来检索数据,请使用$_GET。第二个是要使用$_GET检索数据,您必须像这样访问您的URL:localhost/register.php?id=myID


在你的情况,你通过HTTPPost发送数据,因此只需使用file_get_contents('php://input')让你的JSON字符串,解码您收到的JSON数据(json_decode($myJSONString)),并将其发送到您的第二个数据库。

编辑
如果我理解正确你的问题,你可以做这样的:

// get all employees from your first database and write them into a JSONArray 

List<Employe> employes = db.selectAll(); 
JSONObject objEmployes = new JSONObject(); 
JSONArray employesData = new JSONArray(); 
for (Employe employe : employes) { 
    int id = employe.getId(); 
    String name = employe.getName(); 
    String surname = employe.getSurname(); 
    int age = employe.getAge(); 
    String company = employe.getCompany(); 
    String wtype = employe.getWorktype(); 
    JSONObject empData = new JSONObject(); 
    empData.put("id", id); 
    empData.put("name", name); 
    empData.put("surname", surname); 
    empData.put("age", age); 
    empData.put("company", company); 
    empData.put("worktype", wtype); 
    employesData.put(empData); 
} 

// open connection 
URL url = new URL("yourUrl.com/yourPhpScript.php"); 
url.openConnection(); 

// send JSONArray to your second database 
String dataToSend = employesData.toString(); 
OutputStream os = urlConnection.getOutputStream(); 
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
writer.write(dataToSend); 
writer.flush(); 
writer.close(); 

PHP脚本:

<?php 
// connect to database 
$link = mysqli_connect($hostname, $username, $password); 
mysqli_select_db($link, "myDatabase"); 

// get the JSONArray the app sends 
$contents = file_get_contents('php://input'); 

$jsonArray = json_decode($contents, true); 
$jsonCount = count($jsonArray); 

for ($i = 0; $i < $jsonCount; $i++) { 
    $item = $jsonArray[$i]; 
    $itemName = utf8_decode($item['name']); 
    // parse the other json attributes here like the one above 

    $query = "INSERT INTO employees VALUES('$itemName', 'addOtherValuesHere...')"; 
    mysqli_query($link, $query); 
} 
+0

我需要使用POST insted的因为我从我的数据库传输数据,所以我不会发送一个,两个或三个数据但更多,并且它依赖于我在点击同步按钮之前插入数据库的数据量。 你可以解释一下如何设置file_get_contents ...在我的情况下,以及在哪里,请注意我对PHP不太好,我只使用我在学院中找到的示例编写了我的任务代码。 – Mystiq

+1

@Mystiq我添加了示例代码,多数民众赞成我如何解决你的问题,希望它可以帮助你,我正确理解你 – Tyrmos

+0

我用你的PHP脚本,但保持我的代码从应用程序,因为当我把url.openConnection();它变红了,就像没有办法......我进一步了,但现在我又得到了一个“警告”......这里是: 注意:未定义变量:localhost在C:\ wamp64 \ www \ employes_db \ register .php on line 3 同样适用于root用户,也适用于密码...以及以下警告: 警告:mysqli_connect():(HY000/1045):拒绝用户'@'localhost'的访问(使用密码: NO)在第3行的C:\ wamp64 \ www \ employes_db \ register.php中 您对此有何想法? – Mystiq

相关问题