So I've been following a tutorial that shows how to connect android to MySQL db. I've done everything, but it didn't work. The PHP file works when i enter it's location in chrome -> it shows me the array in JSON format. However, in android it's not working maybe because I am hosting the file on a local server. Any help?
Thanks.
Android:
package com.example.mohammadel_ghali.icare;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class login extends AppCompatActivity {
String JSON_STRING ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void getJSON(View view){
new BackgroundTask().execute();
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
String JSON_URL;
@Override
protected void onPreExecute() {
JSON_URL ="10.0.2.2/ApplicationDemoNewNew/admin/android/json_get_login.php";
}
@Override
protected String doInBackground(Void... voids) {
try {
StringBuilder JSON_DATA = new StringBuilder();
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((JSON_STRING = reader.readLine())!=null) {
JSON_DATA.append(JSON_STRING).append("\n");
}
return JSON_DATA.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
TextView json = (TextView) findViewById(R.id.tv_result);
json.setText(result);
}
}
}
PHP:
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='root123';
$con = @mysqli_connect($mysql_host,$mysql_user,$mysql_password);
if(!$con){
die('Failed to connect to the database');//if not successful
}else{
//echo "Successfully connected to MySQL!";//if successful
if(@mysqli_select_db($con, 'application_database')){//selecting the database
//echo '<br>'."Connected to the specified database!";
}else{
die('<br>'."Could not connect to the specified database!");
}
}
$sql = "select * from users;";
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("id"=>$row[0],"username"=>$row[1],"password"=>$row[2],"first_name"=>$row[3],"last_name"=>$row[4]));
}
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>