I'm building a mobile application in Android Studio for the first time, and in order to connect to MySQL database I used PHP.
I created a login interface (with email and password) which will redirect the user to profile interface where I need to display user's data in text view.
The problem is that I don't know how to get other user's data (for example :name , age ...) in my code, I can only get entered values (email or password).
Could somebody show me how please ?
Login activity code:
public class MainActivity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
public static final String USER_NAME = "USERNAME";
EditText _txtemail;
EditText _txtpassword;
//CardView _button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_txtemail=(EditText)findViewById(R.id.email);
_txtpassword=(EditText)findViewById(R.id.matricule);
}
public void checkLogin(View arg0) {
// Get text from email and passord field
final String email = _txtemail.getText().toString();
final String matricule = _txtpassword.getText().toString();
// Initialize AsyncLogin() class with email and password
new AsyncLogin().execute(email,matricule);
}
private class AsyncLogin extends AsyncTask<String, String, String>
{
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.1.141/androidfiles/login.inc.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", params[0])
.appendQueryParameter("matricule", params[1]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return(result.toString());
}else{
return("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
if(result.equalsIgnoreCase("true"))
{
/* Here launching another activity when login successful. If you persist login state
use sharedPreferences of Android. and logout button to clear sharedPreferences.
*/
// Toast.makeText(MainActivity.this, "login successfull", Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
intent.putExtra(USER_NAME, _txtemail.getText().toString());
startActivity(intent);
MainActivity.this.finish();
}else if (result.equalsIgnoreCase("false")){
// If username and password does not match display a error message
Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();
} else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
- PHP file
<?php
include 'config.inc.php';
// Check whether username or password is set from android
if(isset($_POST['email']) && isset($_POST['matricule']))
{
// Initialize Variable
$result='';
$email = $_POST['email'];
$matricule = $_POST['matricule'];
// Query database for row exist or not
$sql = 'SELECT * FROM chauffeur WHERE email = :email AND matricule = :matricule';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':matricule', $matricule, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount())
{
$result="true";
}
elseif(!$stmt->rowCount())
{
$result="false";
}
// send result back to android
echo $result;
}
?>