I'm developing my first sign in following this article. I've read a couple of others but this one seems simple/intuitive enough for me, specially when I'll want to do something bigger than a sign in.
I had to make some changes to the PHP script that was used.
UPDATE I have two php scripts, this is the correct one, the last one was for _GET method.
<?php
$con=mysql_connect("...");//deleted for privacy
mysql_select_db("..");//deleted for privacy
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$query=mysql_query("SELECT username FROM users");
echo $query;echo $query;echo $query;echo $query;
if($query){
$row = mysql_fetch_assoc($query);
$data = $row['username'];
echo $data;
}else{
echo "something went wrong:".mysql_error();
}
mysql_close($con);
?>
In any case I don't think the error is in the PHP, as I run the script on my browser using appropriate values in the URL for username/password and it prints out the response I'm looking for (which is just the username). Here is my modified SignInActivity.
package com.example.phpmysql;
public class LogInBackgroundActivity extends AsyncTask<String,Void,String>{
private Context context;
public AsyncResponse delegate=null;
public LogInBackgroundActivity(Context context) {
this.context=context;
}
@Override
protected String doInBackground(String... arg0) {
String address ="...";//hidden for privacy
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
address+="login_post.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null){
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result){
if(result.length()>0)
delegate.processFinished(result);
else
delegate.processFinished("Something Odd");
}
}
What I understood from the tutorial is that everything that is printed on the php script get sent back with onPostExecute(..). AsyncResponse is just an interface I created for transporting this data back to the main activity, according to this question.
This is the data that I want and it comes back empty.
I'm testing on a real device so I have no logcat reporting.