Patrick De Vera
Patrick De Vera

Reputation: 53

How to read string from php to android studio (java)

I don't know why i get a null value when i call the GetPHPData() function. The "out" variable returns nothing (""). I make a Toast.makeTest and it returns empty string. Please help. This is my code:

public class PHPConnect extends  Activity
{
    String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
    HttpURLConnection urlConnection = null;
    String out = null;
    public String GetPHPData()
    {
        try {

            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(10000);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            out = readStream(in);
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
        }
        finally
        {
            urlConnection.disconnect();
            return out;
        }

    }
    private String readStream(BufferedReader is)
    {
        try
        {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            int i = is.read();
            while(i != -1)
            {
                bo.write(i);
                i = is.read();
            }
            return bo.toString();
        } catch (IOException e)
        {
            return e.getMessage();
        }
    }
}

By the way, im running a wamp server and I port forwarded my router, on local host, the url works, but on remote connection, it won't return a string. You can try out the url, the result is: "This is the output:emil"

Upvotes: 0

Views: 2259

Answers (1)

Ganesh AB
Ganesh AB

Reputation: 4698

Can you please try below piece of code which is working for me, also add INTERNET permission in android manifest file. Still if it is not working then may be issue with server end then try to debug it.

URL url;
    try {
        url = new URL("myurl");

        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 1

Related Questions