Pretty much step by step.
You will need the PHP code for your webservice which could look like this:
<?php
$response = array();
if (isset($_POST['param1']) &&
isset($_POST['param2']) &&
isset($_POST['param3'])) {
$param1 = $_POST['param1'];
$param2 = $_POST['param2'];
$param3 = $_POST['param3'];
require_once __DIR__ . '/db_config.php';
$host = DB_SERVER;
$db = DB_DATABASE;
$user = DB_USER;
$pass = DB_PASSWORD;
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT * FROM tblYourTable
WHERE ID = :id_STM
AND col2 >= :col2_STM
AND col3 >= :col3_STM
';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id_STM', $param1, PDO::PARAM_INT);
$stmt->bindParam(':col2_STM', $param2, PDO::PARAM_STR);
$stmt->bindParam(':col3_STM', $param3, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["success"] = 1;
$response["data"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["data1"] = $row["Col1"];
$data["data2"] = $row["Col2"];
$data["data3"] = $row["Col3"];
$data["data_N"] = $row["Col_N"];
array_push($response["data"], $data);
}
}
else {
$response["success"] = 0;
$response["message"] = "No data returned!!";
}
}
else {
$response["success"] = 0;
$response["message"] = "Parameters are not correct";
}
echo json_encode($response);
?>
adding your database connection data in a separate file.
The database query could look similar to this:
public String selectYourData(int id, String param2, double param2){
String res = "";
try {
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("param1", String.valueOf(id));
params.put("param2", String.valueOf(id));
params.put("param3", String.valueOf(id));
HttpRequestCommand http = new HttpRequestCommand();
res = http.makeHttpRequestJsonString("my_php_script.php", params);
JSONObject jObj = new JSONObject(res);
String success = jObj.getString("success");
if(success.contentEquals("1")){
}
else{
res = "MyWarningFlag"
}
}
catch (Exception ex){
Log.e(TAG, "selectData --- " + ex.getMessage());
}
return res;
}
But, in order for your select method to work you need a http request, which could be similar to this: (you will need to put in your own host data, connection data, passwords and so-forth to gain access to the webserver)
private static final String TAG = "YourClassNameHere"
public String makeHttpRequestJsonString(String phpScript, Map<String, String> params){
String json = "";
InputStream responseStream = null;
String logMess = "";
long startTime;
long stopTime;
long elapsedTime;
String host = "Http://yourWebSite.com/dir1/dir2/";
host =+ "/" + phpScript
URL url = new URL(host);
try {
startTime = System.currentTimeMillis();
StringBuilder postData = new StringBuilder();
for(Map.Entry<String, String> param : params.entrySet()){
param.getValue());
if(postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
postData.toString());
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
DataOutputStream request = new DataOutputStream(conn.getOutputStream());
request.write(postDataBytes);
request.flush();
request.close();
Integer replyCode = conn.getResponseCode();
logMess += " Reply Code: " + replyCode.toString();
responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
logMess += " elapsed Time : " + elapsedTime + " ms";
Log.e(TAG, "makeHttpRequestJsonString --- " + logMess);
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("
");
}
responseStreamReader.close();
json = stringBuilder.toString();
}
catch (UnsupportedEncodingException e) {
Log.e(TAG, "makeHttpRequestJsonString --- " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "makeHttpRequestJsonString --- " + e.getMessage());
}
return json;
}
And finally, kick-off the search from you activity from a background task:
class LoadServerData extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
String result = "";
int id = 1;
string param2 = "someValue";
double param3 = 1.1d;
try {
ServerData dataServer = new ServerData(YourActivityClassName.this);
result = dataServer.selectYourData(id, param2, param3);
}
catch (Exception ex) {
Log.e(TAG, "LoadServerData --- " + ex.getMessage());
}
return result;
}
protected void onPostExecute(String result) {
final String value = result;
if(result.isEmpty()) {
postEmptyList();
return;
}
runOnUiThread(new Runnable() {
public void run() {
ListData data;
Map<String, ListData> emailList = new LinkedHashMap<>();
try {
JSONObject object = new JSONObject(value);
JSONArray array = object.getJSONArray("YourRootElementInJson");
int len = array.length();
if(len > 0) {
for (int i = 0; i < len; i++) {
final JSONObject o = array.getJSONObject(i);
data = new ListData();
int userId = o.getInt("col1");
data.setUserId(userID);
String userName = o.getString("col2");
data.setUserName(userName);
String email = o.getString("col3");
data.setUserEmail(email);
emailList.put(userName, data);
}
}
}
catch (JSONException jex){
Log.e(TAG, " onPostExecute --- " + jex.getMessage());
}
doSometingWithData(array);
}
});
}
}