Denis  Yakovenko
Denis Yakovenko

Reputation: 127

Android HttpPost gets NULL from PHP script instead of JSONArray

I have a datebase with two columns (id, name) that is located at localhost:88. I'm trying to get into it from my android application, but while parsing Json the application gives JSONException. I've tryed getting the data from php without Json parsing, just a String. But it gets only NULL. Here is my php script:

<?php

$con = mysqli_connect('127.0.0.1:3306', 'root', '', 'test');

if(mysqli_connect_errno())
    echo 'Failed to connect to MySQL: ' . mysqli_connect_error();

$query = mysqli_query($con, "SELECT * FROM example");
$rows = array();

while($r = mysqli_fetch_assoc($query))
    $rows[] = $r;

print(json_encode($rows));
    mysqli_close($con);     
?>

And here's my method:

public class MainActivity extends Activity
{
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        txt = (TextView) findViewById(R.id.textView);

        txt.setText(getDataFromDB());
    }

    public String getDataFromDB()
    {
        try
        {
            HttpPost httpPost = new HttpPost("http://127.0.0.1:88/basicphp/GetData.php");

            HttpClient httpClient = new DefaultHttpClient();
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpClient.execute(httpPost, responseHandler);

            return response.trim();
        }
        catch(Exception e){
            return "error\n" + e.getMessage();
        }
    }
}

When i type in my browser "http://localhost:88/basicphp/GetData.php", i get this: "[{"id":"1","name":"John"}]". So i want to at least get this string on my TextView, but the TextView gets only null:( So, what am I doing wrong?

Upvotes: 1

Views: 230

Answers (1)

Nooh
Nooh

Reputation: 1546

change

 HttpPost httpPost = new HttpPost("http://127.0.0.1:88/basicphp/GetData.php");

it to

 HttpPost httpPost = new HttpPost("http://10.0.2.2/basicphp/GetData.php");

Visit [question]: java.net.ConnectException: /127.0.0.1:8080 an android emulator

Upvotes: 1

Related Questions