应用程序无法使用Slim Framework将数据发送到MySQL

时间:2018-12-24 13:27:54

标签: php android mysql sqlite slim

我构建了一个室内定位应用。我使用SQLiteOpenHelper来存储内部应用程序数据,并使用苗条的框架来构建MySQL数据库。我有如下图所示的读数,access_points和Kinect表:

MySQL table reading structure access_points structure

我想从我的应用程序中将读数和access_points数据发送到我的数据库,但不会发送任何数据。 当我尝试发送数据时,模拟器向我提供了此信息,但它返回了网络错误。

    D/Data Sent: {"building_id":"Abcd","readings":[{"name":"B","routers":{"f8:75:88:c8:04:00":"Solikin Valley","ac:f9:70:e6:e0:90":"HOUSE 277","0c:41:e9:71:12:c4":"Monica Merly House"},"values":{"f8:75:88:c8:04:00":-62,"ac:f9:70:e6:e0:90":-76,"0c:41:e9:71:12:c4":-64},"x":"2","y":"2"},{"name":"A","routers":{"f8:75:88:c8:04:00":"Solikin Valley","ac:f9:70:e6:e0:90":"HOUSE 277","0c:41:e9:71:12:c4":"Monica Merly House"},"values":{"f8:75:88:c8:04:00":-62,"ac:f9:70:e6:e0:90":-77,"0c:41:e9:71:12:c4":-72},"x":"1","y":"1"}],"friendly_wifis":[{"BSSID":"f8:75:88:c8:04:00","SSID":"Solikin Valley"},{"BSSID":"0c:41:e9:71:12:c4","SSID":"Monica Merly House"}]}
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
                          SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
Application terminated.

这是我的SQLite代码:

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "u236344269_indor.db";
public static final String AP_TABLE = "access_points";
public static final String READINGS_TABLE = "readings";
public static final String AP_CREATE = "CREATE TABLE 'access_points' "
        + "('building_id' TEXT NOT NULL ,'ssid' TEXT NOT NULL,'mac_id' TEXT NOT NULL )";
public static final String READINGS_CREATE = "CREATE TABLE 'readings' ('building_id' TEXT NOT NULL , "
        + "'position_id' TEXT NOT NULL , 'x' FLOAT NOT NULL, 'y' FLOAT NOT NULL, "
        + " 'ssid' TEXT NOT NULL , 'mac_id' TEXT NOT NULL , 'rssi' INTEGER NOT NULL )";

private HashMap hp;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(AP_CREATE);
    db.execSQL(READINGS_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + AP_TABLE);
    db.execSQL("DROP TABLE IF EXISTS " + READINGS_TABLE);
    onCreate(db);
}

public int deleteReading(String building_id, String position_id) {
    SQLiteDatabase db = getWritableDatabase();
    String[] args = new String[] { building_id, position_id };
    return db.delete(READINGS_TABLE, "building_id=? and position_id=?",
            args);

}


public boolean deleteBuilding(String building_id) {
    SQLiteDatabase db = getWritableDatabase();
    String[] args = new String[] { building_id };
    db.delete(AP_TABLE,"building_id=?",args);
    db.delete(READINGS_TABLE, "building_id=?", args);
    return true;

}

public ArrayList<String> getBuildings() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("select distinct building_id from "
            + READINGS_TABLE, null);
    ArrayList<String> result = new ArrayList<String>();
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        result.add(cursor.getString(0));
        cursor.moveToNext();
    }
    return result;

}

public ArrayList<Router> getFriendlyWifis(String building_id) {
    ArrayList<Router> result = new ArrayList<Router>();
    System.out.println(building_id);
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("select ssid,mac_id from " + AP_TABLE
            + " where building_id=?", new String[] { building_id });
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        result.add(new Router(cursor.getString(0), cursor.getString(1)));
        cursor.moveToNext();
    }
    return result;

}

public int deleteFriendlyWifis(String building_id) {
    SQLiteDatabase db = getWritableDatabase();
    String[] args = new String[] { building_id };
    return db.delete(AP_TABLE, "building_id=?", args);

}

public boolean addFriendlyWifis(String building_id, ArrayList<Router> wifis) {
    deleteFriendlyWifis(building_id);
    SQLiteDatabase db = getWritableDatabase();
    for (int i = 0; i < wifis.size(); i++) {
        ContentValues cv = new ContentValues();
        cv.put("building_id", building_id);
        cv.put("ssid", wifis.get(i).getSSID());
        cv.put("mac_id", wifis.get(i).getBSSID());
        db.insert(AP_TABLE, null, cv);
    }
    System.out.println("Adding done");
    return true;
}

public ArrayList<String> getPositions(String building_id) {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("select distinct position_id from "
                    + READINGS_TABLE + " where building_id=?",
            new String[] { building_id });
    ArrayList<String> result = new ArrayList<String>();
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        result.add(cursor.getString(0));
        cursor.moveToNext();
    }
    return result;
}

public boolean addReadings(String building_id, PositionData positionData) {
    Log.v("Just Before db : ", positionData.toString());
    deleteReading(building_id, positionData.getName());

    SQLiteDatabase db = getWritableDatabase();
    for (Map.Entry<String, Integer> e : positionData.getValues().entrySet()) {
        ContentValues cv = new ContentValues();
        cv.put("building_id", building_id);
        cv.put("position_id", positionData.getName());
        cv.put("ssid",positionData.routers.get(e.getKey()));
        cv.put("mac_id",e.getKey());
        cv.put("rssi", e.getValue());
        cv.put("x", positionData.getX());
        cv.put("y", positionData.getY());
        Log.v(e.getKey(), e.getValue().toString());
        db.insert(READINGS_TABLE, null, cv);
    }
    System.out.println("Adding done");
    return true;

}

public boolean updateDatabase(JSONArray buildings) throws JSONException {
    Gson gson=new Gson();

    for(int i=0;i<buildings.length();i++){
        JSONObject building=buildings.getJSONObject(i);
        String building_id=building.getString("building_id");

        ArrayList<PositionData> readings= null;
        ArrayList<Router> friendlyWifis=null;



        try {
            Log.d("Readings",building.get("readings").toString());

            readings = gson.fromJson(building.get("readings").toString(),new TypeToken<ArrayList<PositionData>>() {
            }.getType());
            friendlyWifis=gson.fromJson(building.get("friendly_wifis").toString()
                    ,new TypeToken<ArrayList<Router>>() {
                    }.getType());
            deleteBuilding(building_id);
            for(int j=0;j<readings.size();j++){
                addReadings(building.getString("building_id"),readings.get(j));
            }
            addFriendlyWifis(building.getString("building_id"),friendlyWifis);

        } catch (JSONException e) {
            return false;
        }



    }
    return true;

}


public ArrayList<PositionData> getReadings(String building_id) {
    HashMap<String, PositionData> positions = new HashMap<String, PositionData>();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("select distinct * from " + READINGS_TABLE
            + " where building_id='" + building_id + "'", null);
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        String position_id = cursor.getString(1);
        Router router = new Router(cursor.getString(4), cursor.getString(5));
        Log.v(cursor.getString(4), cursor.getInt(6) + "");
        if (positions.containsKey(position_id)) {

            positions.get(position_id).addValue(router, cursor.getInt(6));
        } else {
            PositionData positionData = new PositionData(
                    cursor.getString(1), cursor.getString(2), cursor.getString(3));
            positionData.addValue(router, cursor.getInt(6));
            positions.put(position_id, positionData);
        }
        cursor.moveToNext();

    }
    System.out.println("Reading done");
    ArrayList<PositionData> result = new ArrayList<PositionData>();
    for (Map.Entry<String, PositionData> e : positions.entrySet())
        result.add(e.getValue());
    return result;

}

这是我的php代码:

    <?php
require 'vendor/autoload.php';

$app = new \Slim\Slim();

$app->response->headers->set('Content-Type', 'application/json');

$app->post('/submit/?', function () {

    $data = isset($_REQUEST['data'])?$_REQUEST['data']:null;

    if($data){
        $data = json_decode($data);

        Reading::where('building_id','=', $data->building_id)->delete();
        AccessPoint::where('building_id','=', $data->building_id)->delete();

        foreach ($data->readings as $reading) {
            foreach ($reading->values as $mac => $rssi) {
                $new_reading = new Reading;
                $new_reading->building_id = $data->building_id;
                $new_reading->position_id = $reading->name;
                $new_reading->ssid = $reading->routers->$mac;
                $new_reading->mac_id = $mac;
                $new_reading->rssi = $rssi;
                $new_reading->x = $x;
                $new_reading->y = $y;
                $new_reading->save();
            }
        }

        foreach ($data->friendly_wifis as $wifi) {
            $new_access_point = new AccessPoint;
            $new_access_point->building_id = $data->building_id;
            $new_access_point->ssid = $wifi->SSID;
            $new_access_point->mac_id = $wifi->BSSID;
            $new_access_point->save();
        }

        echo json_encode(['result'=>'success'], JSON_PRETTY_PRINT);
    }else{
        echo json_encode(['result'=>'fail'], JSON_PRETTY_PRINT);
    }
});


$app->get('/?', function () {

    $buildings = Reading::groupBy('building_id')->get(['building_id']);

    $responses = array();

    foreach ($buildings as $building) {
        $building_id = $building->building_id;

        $readings = Reading::where('building_id','=',$building_id)->get();
        $access_points = AccessPoint::where('building_id','=',$building_id)->get();



        foreach($readings as $reading){
            $positions[$reading->position_id]['values'][$reading->mac_id]=$reading->rssi;
            $positions[$reading->position_id]['x'][$reading->mac_id]=$reading->x;
            $positions[$reading->position_id]['y'][$reading->mac_id]=$reading->y;
            $positions[$reading->position_id]['routers'][$reading->mac_id]=$reading->ssid;      

        }

        $positions_list= array();
        foreach ($positions as $name => $data) {
            $new_position=array(
                'name'=>(string)$name,
                'routers'=>$data['routers'],
                'values'=>$data['values'],
                'x'=>$data['x'],
                'y'=>$data['y'],
                );

         array_push($positions_list,$new_position);

        }

        $access_points_list=array();
        foreach ($access_points as $access_point) {
            $new_access_point=array(
                'BSSID'=>$access_point['mac_id'],
                'SSID'=>$access_point['ssid'],

                );
            array_push($access_points_list,$new_access_point);
        }


        $building_response = array(
            'building_id' => $building_id, 
            'readings' => $positions_list,
            'friendly_wifis' => $access_points_list,
            );

        array_push($responses,$building_response);

    }
    echo json_encode($responses);
    return;

});



$app->run();

这是我的提交功能:

public class Submit extends AsyncTask<String, Integer, JSONObject> {
    private String baseUrl = Config.BASE_URL;
    Context context;
    public Submit(Context context){
        this.context=context;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            return postData(params[0]);
        } catch (IOException e) {
            return null;
        }


    }

    protected void onPostExecute(JSONObject json) {

        if (json == null)
        {
            Toast.makeText(context, "Network Error", Toast.LENGTH_LONG).show();
        }
        else {

            try {
                if (json.get("result").equals("success")) {
                    Toast.makeText(context, "Success", Toast.LENGTH_LONG).show();



                } else {
                    Toast.makeText(context, "Failure", Toast.LENGTH_LONG).show();



                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(context, "Network/Server Error", Toast.LENGTH_LONG).show();
            }
        }


    }


    protected void onProgressUpdate(Integer... progress) {

    }

    public JSONObject postData(String jsonData) throws IOException {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(baseUrl + "submit");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifiManager.getConnectionInfo();

            String mac = info.getMacAddress();
            Log.d("Data Sent", jsonData);
            nameValuePairs.add(new BasicNameValuePair("mac", mac));
            nameValuePairs.add(new BasicNameValuePair("data",jsonData));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            JSONObject json = null;
            if (response == null)
                return null;
            else {
                try {
                    json = new JSONObject(EntityUtils.toString(response.getEntity()));
                } catch (JSONException e) {

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return json;

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            return null;
        }
    }

}

0 个答案:

没有答案