Reputation: 185
We try to get data from a server in an android app. For the fetching query the user shall be able to choose the condition by what the data is filtered. Somehow, we end up getting no output when we do it as we tried, although the value that is entered is passed into the table correctly. When we tried it with a fix value for the variable everything works fine, only using it variable doesn‘t work, but why not? Isn‘t it possible to do it like this? We‘ve been told as well, that the code is not secure, but it would be nice to get it working anyway, so thanks for the advice!
<?php
$con = new mysqli($server, $user, $password, $db);
if(isset($_POST['number'])){
$query = "INSERT INTO Table (number) VALUES ('$_POST[number]')";
}
$var = $_POST['number'];
$query = "SELECT * FROM Table WHERE number = '$var'";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
mysqli_close($con);
?>
The code we used:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
GetData();
InsertData(TempName);
JSON_DATA_WEB_CALL();
}
});
}
public void GetData() {
TempName = name.getText().toString();
}
public void InsertData(final String a) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String NameHolder = a;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", NameHolder));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ServerURL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(a);
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(ServerURL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_ID));
GetDataAdapter2.setName(json.getString(JSON_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
Upvotes: 0
Views: 67
Reputation: 484
First, in your php file, try to use
die(var_dump($_POST))
to check if your post application has been correctly!
This is my Activity's code:
@Override
protected List<MyModel> doInBackground(Void... params) {
Logger.log(Logger.INFO, "DOWNLOAD STARTED!");
try {
//I have a Service Class called ConnectionService, that do the verifications and conenction!
if (connectionService.isConnected && connectionService.hasInternet) {
//Creating my json to send via POST to my wbs in php.
JSONObject data = new JSONObject();
data.put("my_attribute", "AttributeTest");
JSONObject newData = new JSONObject().accumulate("data", data);
return connectionService.downloadInfo(newData);
}
return null;
} catch (Exception e) {
Message.showLongMessage(getApplicationContext(), getString(R.string.error_no_connection));
Logger.log(Logger.ERROR, e.getMessage());
}
return null;
}
This is my ConnectionService class:
public List downloadInfo(JSONObject dataJson) {
try {
return checkDownloadConnection(connectPost(dataJson));
} catch (IOException | JSONException e) {
e.printStackTrace();
Logger.log(Logger.ERROR, e.getMessage());
}
return null;
}
private JSONObject connectPost(JSONObject dataJson) {
JSONObject jsonObject = null;
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL("my_url_to_my_php_file").openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
OutputStream os = connection.getOutputStream();
os.write(dataJson.toString().getBytes("UTF-8"));
os.flush();
if (connection.getResponseCode() == 200) {
jsonObject = new JSONObject(Utils.bytesToString(connection.getInputStream()));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
Logger.log(Logger.ERROR, e.getMessage());
}
if (connection != null) {
connection.disconnect();
}
return jsonObject;
}
public List checkDownloadConnection(JSONObject connectionJson) throws JSONException, IOException {
if (connection == null) {
return null;
}
//connectionJson will return a result from my php json_encode(die(var_dump($obj)))
//with status and data "$result = ['status' => true/false, 'message' => 'my message if occur some error', 'data' => $myData];
String status = String.valueOf(connectionJson.getString("status"));
if (status.equals(STATUS_FALSE)) {
Logger.log(Logger.ERROR, String.valueOf(connectionJson.getString("message")));
return null;
}
return hydrateObjects(connectionJson.getJSONArray("data"));
//this is another function, that i hydrate my info downloaded, you won't need it for your logic.
}
My Utils.bytesToString function:
public static String bytesToString(InputStream is) throws IOException {
byte[] buf = new byte[1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
buffer.write(buf, 0, bytesRead);
}
String out = new String(buffer.toByteArray());
return out;
}
I hope you understand. :)
Upvotes: 1
Reputation: 1723
Your variable $_POST[number] not posted correctly.
Try the following tutorial to post your data from android app to PHP code.
https://www.androidcode.ninja/android-http-client/
Hope it works for you.
Upvotes: 0