Android - 将数据从Android SQLite DB发布到localhost服务器上的MySQL数据库

时间:2017-02-07 01:45:04

标签: android mysql sqlite localhost

我正在做一些任务,我需要在localhost服务器上启用SQLite DB数据同步到MySQL数据库。单击按钮时,需要“收集”来自SQLite的数据,转换为JSON并发送到localhost MySQL DB并插入其中。我创建了一个处理该工作的Activity,根据学院的例子制作了一些PHP,并且运行了wamp服务器,我在其中创建了需要存储数据的数据库。 在我的localhost数据库中名为employes_db,其中的表名为employes。 这是我做的android studio的代码:

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”我收到“错误” - &gt;注意:未定义的索引:第9行的C:\ wamp64 \ www \ employes_db \ register.php中的id&lt; - 其余列(名称,姓氏,年龄,公司,wtype)的错误相同。 愿有人帮忙,我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

Undefined index: id表示$_POST['id']不存在。第一个错误是您使用$_POST来检索数据,而是使用$_GET。第二个是使用$_GET来检索数据,您可以像这样访问您的网址: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);
}