我有几个问题:
- 如何在Android中同步这些数据库? - 同步是否可以双向进行?如果我在Android中更改数据库数据,我能否相应地在Web服务器上进行更改,反之亦然?
我正在为老年人设计基本的GUI,以便他们可以使用Android手机。我的Web应用程序应该将联系人和提醒添加到Android应用程序中的数据库中,但是当我手动在Android应用程序中添加联系人或提醒时,我也希望在我的Web应用程序中看到它们(双向同步)。
谢谢! :)
Create a PHP file to query data from your table name
<?php
//To Connect to your Data base
mysql_connect("localhost","root","");
mysql_select_db("YourDataBaseName");
// To execute a query from Your table
$sql=mysql_query("SELECT * FROM `Your_Table_Name");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
// Convert to Json format
print(json_encode($output));
// mysql_close();
?>
Name your PHP file as your table Name for example : MyTableName.php
Put this file in your root server directory : for example in Wamp server the www directory
Test the return data using a browser, using your URL like www.localhost/MyTableName.php, normally you will have all your query content in Json format.
* -> Android端:*
Download this class 'ClientHTTP' https://www.dropbox.com/s/odpaus1tjhd9orv/ClientHTTP.java
Add Internet Permission in your manifest.
Inside the click of your button Synchronize put :
String lReturn=_myClientHtpp.readFromUrl(www.localhost/MyTableName.php);
// It will return a json format (Like navigator)
//Code to Clear your data from Sqlite data base TABLE ....
try {
// Create your Json Array
JSONArray lList=new JSONArray(lReturn);
// Iterate the json arry to get each Json object
for (int i = 0; i < lList.length(); i++) {
JSONObject lObject=lList.getJSONObject(i);
String lLogin=lObject.getString("Login");
String lPWD=lObject.getString("PassWord");
//Code to Insert in Sqlite data base .....
}
} catch (JSONException e) {
e.printStackTrace();
}
更新
* -> PHP端:
<?php
//Connect to Database
mysql_connect("localhost","root","");
mysql_select_db("YourDataBase");
$sql= mysql_query("INSERT INTO YourTableName (Login,PassWord) VALUES ('".$_REQUEST['PARAM_Login']."','".$_REQUEST['PARAM_PWD']."')");
if($sql==1){
echo "true";
}else{
echo "false";
}
// mysql_close();
?>
Inside the click of your 'Add' button write :
// List of params
ArrayList<NameValuePair> lListOfParams=new ArrayList<NameValuePair>();
// Param login
BasicNameValuePair PARAM_Login=new BasicNameValuePair("PARAM_Login", "test from Android");
// Param PWD
BasicNameValuePair PARAM_PWd=new BasicNameValuePair("PARAM_PWD", "Test from Android");
// Add params to List
lListParams.add(PARAM_Login);
lListParams.add(PARAM_PWd);
// Execute the post method from your ClientHttp class
boolean lIsInsert=_myClientHtpp.SendToUrl("www.localhost/insert.php", lListOfParams);
if(lIsInsert)
Toast.makeText(this, "Insert Success", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Insert Error", Toast.LENGTH_LONG).show();
If your have your own server replace localhost per your domain name.
If you are using emulator , replace your localhost domaine name per
your actual IP address for example the query URL becomes :
192.168.1.2/MyTableName.php