Data not being retrieved from online mysql server

I am trying to get data from an online database (MySql) via json and want to display it as a ListView. What I have done so far:

Downloader.java

public class Downloader extends AsyncTask<Void,Integer,String> {
Context c;
String address;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String address, ListView lv) {
    this.c = c;
    this.address = address;
    this.lv = lv;
}
//B4 JOB STARTS
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pd=new ProgressDialog(c);
    pd.setTitle("Fetch Data");
    pd.setMessage("Fetching Data...Please wait");
    pd.show();
}
@Override
protected String doInBackground(Void... params) {
    String data=downloadData();
    return data;
}
@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    pd.dismiss();;
    if(s != null)
    {
        Parser p=new Parser(c,s,lv);
        p.execute();
    }else
    {
        Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
    }
}
private String downloadData()
{
    //connect and get a stream
    InputStream is=null;
    String line =null;
    try {
        URL url=new URL(address);
        HttpURLConnection con= (HttpURLConnection) url.openConnection();
        is=new BufferedInputStream(con.getInputStream());
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        StringBuffer sb=new StringBuffer();
        if(br != null) {
            while ((line=br.readLine()) != null) {
                sb.append(line+"n");
            }
        }else {
            return null;
        }
        return sb.toString();
        } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(is != null)
        {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
return null;
}

      

}

MainActivity.java

public class MainActivity extends Activity {
 String url="http://bookvilla.esy.es/book.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ListView lv= (ListView) findViewById(R.id.lv);
        final Downloader d=new Downloader(this,url,lv);
        d.execute();

    }
}

      

when i run my app in app. I get a toast message saying "unable to download data" which is on line 35 of the Downloader.java class. So I am assuming that the data I am getting from the database is null ... but why is it ...

$ con = mysqli_connect ($ host, $ u_name, $ pwd, $ db) or die ('Unable to connect'); if (mysqli_connect_error ($ con)) {echo "Failed to connect to database" .mysqli_connect_error ();

}

$ query = mysqli_query ($ con, "SELECT * FROM playerstb"); if ($ query) {

while ($ row = mysqli_fetch_array ($ query)) {$ flag [] = $ row;

} print (json_encode ($ flag)); } mysqli_close ($ con);

above is my php file

enter image description here

enter image description here

+3


source to share


1 answer


Not sure how to fix your problem, but I used a different method:

db_config.php:

<?php
define('DB_USER',"root");
define('DB_PASSWORD',null);
define('DB_DATABASE',"phoneshop");
define('DB_SERVER',"localhost");
?>

      

db_connect.php:

<?php
class DB_CONNECT {
private $con = '';
function __construct() {
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$this->con = mysqli_connect(DB_SERVER , DB_USER , null , DB_DATABASE) or die(mysqli_error());
return $this->con;
}
function close() {
mysqli_close($this->con);
}
function query($query){
return mysqli_query($this->con, $query);
}
}
?>

      

And then I made this file to get the data:

<?php

$response = array();

require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();

$result = $db->query('SELECT * FROM products') or die('error');

if (mysqli_num_rows($result) > 0) {

$response["products"] = array();

while ($row = mysqli_fetch_array($result)) {

$product = array();

$product["pid"] = $row["pid"];

$product["name"] = $row["name"];

$product["price"] = $row["price"];

$product["description"] = $row["description"];

array_push($response["products"], $product);

}

$response["success"] = 1;

echo json_encode($response);

} else {

$response["success"] = 0;

$response["message"] = "No products found";

echo json_encode($response);

}

?>

      



And then from android studio:

Call:

private String url_all_products = "http://10.0.0.10:8012/onlineShop/get_all_products.php";
//ip of the server or 10.0.2.2 if in emulator

ContentValues params = new ContentValues();

JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

      

And the analyzer:

public class JSONParser {

static JSONObject jObj;
static String json;

// constructor
public JSONParser() {
}

// function get json from url
// by making HTTP POST or GET mehtod
public static JSONObject makeHttpRequest(String url, String method, ContentValues params) {
    // Making HTTP request
    try {
        final OkHttpClient client = new OkHttpClient();
        Request request;
        // check for request method
        if (method.equals("POST")) {
            // request method is POST

            MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
            String content = "";
            for (String key : params.keySet())
            {
                if ( !content.isEmpty())
                    content += "&";

                content += key + "=" + params.get(key);
            }

            RequestBody body = RequestBody.create(contentType, content);
            request = new Request.Builder().url(url).post(body).build();
        }
        else  {
            // request method is GET
            request = new Request.Builder().url(url).build();
        }
        final Response response = client.newCall(request).execute();
        json = response.body().string();

    } catch (IOException e) {
        e.printStackTrace();
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e ){
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}
}

      

Adding this to gradle:

compile 'com.squareup.okhttp3:okhttp:3.4.2'

      

+1


source







All Articles