Issue
I am trying to make a simple app with two buttons each of which would execute a PHP script on my DB, on localhost. So far i have the php script working as intended (tested in browser):
<?php
require 'Connect.php'; // connects to DB
$query = "UPDATE tracker_database
SET tracker_logged_in = '1'
WHERE tracker_username = 'tracker01'";
if(mysqli_query($conn, $query))
{
echo'Success';
} else {
echo'not executed';
}
?>
here I have the app's OnClickListener
public void addListenerOnExeBtn() {
btn_exe = (Button) findViewById(R.id.btn_exe);
btn_exe.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
String link = "http://10.0.3.2/path/to/my/script.php"; //using this IP for Genymotion emulator
new updateData().execute(link);
Toast.makeText(MainActivity.this, "Executed", Toast.LENGTH_LONG).show();
}
}
);
}
And as far as I understand you need to use AsyncTask to access the scripts
private class updateData extends AsyncTask <String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
So my problem is that when I run my app and click the btn_exe it prints out the Toast "Executed" but when I refresh my DB there are no changes, and yes I put the
<uses-permission android:name="android.permission.INTERNET"/>
in my AndroidManifest.xml. I can't find anything wrong in the logcat, no errors, nothing. Anyone has any ideas?
Solution
Ok, so I managed to fix the problem and it was in the updateData method, here is the fixed version if anyone has the same problem:
public class updateData extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
try {
URL url;
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
}else{
InputStream err = conn.getErrorStream();
}
return "Done";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(conn != null) {
conn.disconnect();
}
}
return null;
}
Answered By - Matic Tuma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.