andriod sqlite to mySql don't insert to my database.

wave
jaturathep
2,453
สังคมนักพัฒนาระบบ (Community)
andriod sqlite to mySql don't insert to my database.

ผมไม่สามารถ insert  ข้อมูลผ่าน Json ได้ ช่วยผมดู function php หน่อยครับ ผมเพิ่งเริ่มเขียนโปรแกรมครับ

db_function.php

<?php

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        include_once './db_connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {
        
    }
    /**
     * Storing new high
     * returns high details
     */
    public function storeHigh($Id,$Code,$High,$Date) {
        // Insert user into database
        $result = mysql_query("INSERT INTO high (`id`, `code_tree`, `high_tree`, `date_high`) VALUES (NULL,'$Code','$High','Date')");
    
        if ($result) {
            return true;
        } else {
            if( mysql_errno() == 1062) {
                // Duplicate key - Primary Key Violation
                return true;
            } else {
                // For other errors
                return false;
            }            
        }
    }
    /**
     * Getting all high
     */
    public function getAllHigh() {
        $result = mysql_query("select id,code_tree,high_tree,date_high FROM high");
        return $result;
    }
}

?>

inserthigh.php

<?php
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions(); 
//Get JSON posted by Android Application
$json = $_POST["highJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storeHigh($data[$i]->_ID,$data[$i]->code_tree,$data[$i]->high_tree,$data[$i]->date_high);
	//Based on inserttion, create JSON response
	if($res){
		$b["_id"] = $data[$i]->_ID;
		$b["status"] = 'yes';
		array_push($a,$b);
	}else{
		$b["_id"] = $data[$i]->_ID;
		$b["status"] = 'no';
		array_push($a,$b);
	}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>

DatabaseCoconut.java


public class DatabaseCoconut extends SQLiteOpenHelper {
    private static final String DB_NAME = "CoconutStoring";
    private static final int DB_VERSION = 1;

    public static final String KEY_ID = "_ID";
    public static final String COL_CODE_TREE = "code_tree";

    public static final String TABLE_NAME_HIGH = "High";
    public static final String COL_HIGH_TREE = "high_tree";
    public static final String COL_DATE_HIGH = "date_high";
    public static final String COL_STATUS_HIGH = "updateStatus";

    public DatabaseCoconut(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {

        String query;
        query = "CREATE TABLE High ( _Id INTEGER PRIMARY KEY, code_tree VARCHAR, high_tree INTEGER, date_high DATE, updateStatus TEXT)";
        db.execSQL(query);

    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       // db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME_HIGH);
        String query;
        query = "DROP TABLE IF EXISTS High";
        db.execSQL(query);
        onCreate(db);
    }
    /**
     * Get list of High from SQLite DB as Array List
     * @return
     */
    public ArrayList<HashMap<String, String>> getAllUsers() {
        ArrayList<HashMap<String, String>> wordList;
        wordList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM "+ TABLE_NAME_HIGH ;
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(KEY_ID, cursor.getString(0));
                map.put(COL_CODE_TREE, cursor.getString(1));
                map.put(COL_HIGH_TREE, cursor.getString(2));
                map.put(COL_DATE_HIGH, cursor.getString(3));
                wordList.add(map);
            } while (cursor.moveToNext());
        }
        database.close();
        return wordList;
    }

    /**
     * Compose JSON out of SQLite records
     * @return
     */

    public String composeJSONfromSQLite(){
        ArrayList<HashMap<String, String>> wordList;
        wordList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM "+ TABLE_NAME_HIGH +" where updateStatus = '"+"no"+"'";
        //String selectQuery = "SELECT  * FROM "+ TABLE_NAME_HIGH ;
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(KEY_ID, cursor.getString(0));
                map.put(COL_CODE_TREE, cursor.getString(1));
                map.put(COL_HIGH_TREE, cursor.getString(2));
                map.put(COL_DATE_HIGH, cursor.getString(3));
                wordList.add(map);
            } while (cursor.moveToNext());
        }
        database.close();
        Gson gson = new GsonBuilder().create();
        //Use GSON to serialize Array List to JSON
        return gson.toJson(wordList);
    }

    /**
     * Get Sync status of SQLite
     * @return
     */
    public String getSyncStatus(){
        String msg = null;
        if(this.dbSyncCount() == 0){
            msg = "SQLite and Remote MySQL DBs are in Sync!";
        }else{
            msg = "DB Sync needed\n";
        }
        return msg;
    }

    /**
     * Get SQLite records that are yet to be Synced
     * @return
     */
    public int dbSyncCount(){
        int count = 0;
        String selectQuery = "SELECT  * FROM High where updateStatus = '"+"no"+"'";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        count = cursor.getCount();
        database.close();
        return count;
    }

    /**
     * Update Sync status against each User ID
     * @param id
     * @param status
     */
    public void updateSyncStatus(String id, String status){
        SQLiteDatabase database = this.getWritableDatabase();
        String updateQuery = "Update High set updateStatus = '"+ status +"' where "+ KEY_ID+"="+"'"+ id +"'";
        Log.d("query",updateQuery);
        database.execSQL(updateQuery);
        database.close();
    }
}

MainActivity.Java

public void syncSQLiteMySQLDB(){
        //Create AsycHttpClient object
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        ArrayList<HashMap<String, String>> hightList =  mHelper.getAllUsers();
        if(hightList.size()!=0){
            if(mHelper.dbSyncCount() != 0){
                prgDialog.show();
                params.put("highJSON", mHelper.composeJSONfromSQLite());
                client.post("http://www.coconutstoring.com/inserthigh.php",params ,new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(String response) {
                        System.out.println(response);
                        prgDialog.hide();
                        try {
                            //JSONArray arr = new JSONArray(response);
                            JSONArray arr = new JSONArray(new String(response));
                            System.out.println(arr.length());
                            for(int i=0; i<arr.length();i++){
                                JSONObject obj = (JSONObject)arr.get(i);
                                System.out.println(obj.get("id"));
                                System.out.println(obj.get("status"));
                                mHelper.updateSyncStatus(obj.get("id").toString(),obj.get("status").toString());
                            }
                            Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Throwable error,
                                          String content) {
                        // TODO Auto-generated method stub
                        prgDialog.hide();
                        if(statusCode == 404){
                            Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                        }else if(statusCode == 500){
                            Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                        }else{
                            Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }else{
                Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
            }
        }else{
            Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
        }


    }

 

นี้ครับ  D/mylog: json = {{{[{"_id":"1","status":"yes"},{"_id":"2","status":"yes"},{"_id":"3","status":"yes"}]

ผมเช็คจาก logcat จากตัว android ครับ เป็น Json ที่ php ส่งกลับมาครับ 

MainActivity.Java

catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
Log.d("mylog", "json = " + response.toString());
                        }

 

7 ความคิดเห็น

  • มานพ กองอุ่น

  • jaturathep

  • Resha Valentine

ขอข้อมูลอีกนิดครับ ตอน php มัน echo json ออกมา หน้าตายังไง เอาแค่ ตัวอย่างก็ได้ครับ

นี้ครับ  D/mylog: json = {{{[{"_id":"1","status":"yes"},{"_id":"2","status":"yes"},{"_id":"3","status":"yes"}]

ผมเช็คจาก logcat จากตัว android ครับ เป็น Json ที่ php ส่งกลับมาครับ 

MainActivity.Java

catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
Log.d("mylog", "json = " + response.toString());
                        }


 

ทำไม มันไปตก JSON Exception อ่ะครับ

ลองเปลี่ยนจาก

 JSONObject obj = (JSONObject)arr.get(i);
เป็น 
JSONObject obj = jsonArray.getJSONObject(i);

 

obj.get("id")

เป็น

 

ดูครับ 

obj.optString("id").toString();

ลองเปลี่ยนแล้ว ได้เหมือนเดิมครับ  แต่ผมมาไล่มา json นี้ D/mylog: json = {{{[{"_id":"1","status":"yes"},{"_id":"2","status":"yes"},{"_id":"3","status":"yes"}]  หน้าจะมาจากมาจาก inserthigh.php ซึ่งถ้าใน function นี้ ตัวดาต้าเบส ก็หน้าจะ insert database ให้ถูกไหมครับ แต่พอผมเข้าไปเช็คใน phpMyadmin ไม่มีค่าเพิ่มเข้ามาในตารางครับ

{
//Store User into MySQL DB
$res = $db->storeHigh($data[$i]->_ID,$data[$i]->code_tree,$data[$i]->high_tree,$data[$i]->date_high);
	//Based on inserttion, create JSON response
	if($res){
		$b["_id"] = $data[$i]->_ID;
		$b["status"] = 'yes';
		array_push($a,$b);

 

 

ผมอ่านคำถามผิด โทษทีครับ

ประเด็นคือ php ใช่มะ

ลองเปลี่ยน 

 

 

  $result = mysql_query("INSERT INTO high (`id`, `code_tree`, `high_tree`, `date_high`) VALUES (NULL,'$Code','$High','Date')");
    

 

เป็น 

แล้วดู ผลลัพภ์ว่าทำไม ใส่ไม่ได้อีกทีครับ ลอง debug ดูว่า php มันบอกอะไร

  $result = mysql_query("INSERT INTO high (`id`, `code_tree`, `high_tree`, `date_high`) VALUES (NULL,'$Code','$High','Date')") or die( mysql_error());
    

ซึ่ง โอกาส เป็นไปได้ คือ 

1.  field ช่อง id อ่ะครับ เราตั้งเป็น Primary แต่ไม่ set เป็น Auto Increment ไว้

2. field ช่อง date_high ตั้งเป็นแบบวันที่ แต่ คำสั่ง  Date ให้เปลี่ยนจาก ,'Date') เป็น  ,DATE) ดูอ่ะครับ

 

ชอบคุณสำหรับคำแนะนำ ครับผม

เท่าที่ดูน่าจะผิดที่ 'Date' ครับ

$result = mysql_query("INSERT INTO high (`id`, `code_tree`, `high_tree`, `date_high`) VALUES (NULL,'$Code','$High','Date')");

ลองแก้ 'Date' เป็น '$Date' ครับ