|
|
|
Android - จะดึงข้อมูลจาก Database บน server ลง SQLite ยังไงครับ |
|
|
|
|
|
|
|
ในบทความะมีการอ่าน PHP / MySQL ให้เป็น JSON น่ะครับ จากนั้น Loop เอาไป Insert ได้ไม่ยาก
|
|
|
|
|
Date :
2014-03-17 14:08:01 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ประมาณนี้ะครับ
Insert
final Database myDb = new Database(this);
String url = "http://travelthailand.incasible.com/mobile_selectDB.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("PoiID", c.getString("poi_id"));
map.put("PoiName", c.getString("poi_name"));
map.put("PoiDetail", c.getString("poi_detail"));
map.put("PoiLat", c.getString("poi_latitude"));
map.put("PoiLng", c.getString("poi_longitude"));
MyArrList.add(map);
long flg1 = myDb.InsertData(PoiID, PoiName, PoiDetail, PoiLat, PoiLng);
if(flg1 > 0)
{
Toast.makeText(CreateDatabase.this,"Insert(1) Data Successfully",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(CreateDatabase.this,"Insert(1) Data Failed.",
Toast.LENGTH_LONG).show();
}
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PHP
<?
include "connect.php";
$strSQL = "SELECT * FROM tb_poi";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
while($objResult = mysql_fetch_array($objQuery)){
$output[]=$objResult;
}
print(json_encode($output));
mysql_close($objConnect);
?>
InsertData
public long InsertData(String strPoiID, String strPoiName, String strPoiDetail, String strPoiLat, String strPoiLng) {
// TODO Auto-generated method stub
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("poi_id", strPoiID);
Val.put("poi_name", strPoiName);
Val.put("poi_detail", strPoiDetail);
Val.put("poi_latitude", strPoiLat);
Val.put("poi_longitude", strPoiLng);
long rows = db.insert(TABLE_POI, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
|
|
|
|
|
Date :
2014-03-17 15:56:00 |
By :
gungsakab |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ประมาณนี้แหละครับ เกือบได้แล้ว
|
|
|
|
|
Date :
2014-03-17 16:11:55 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 05
|