Skip to content Skip to sidebar Skip to footer

Cannot Connect To PHP Using Android Application

Now I was developing an application which requires connection to a database, I tried to connect the android application directly to MYSQL but I failed and alot of people said that

Solution 1:

Error in http connection android.os.NetworkOnMainThreadException

Above exception state that you are doing network calling on main thread, you have to do it in asynctask or handler. Have a look at below class:

class ConnectToPHP extends AsyncTask<String, String, String>
{
    @Override
    protected void onPreExecute()
    {
        // TODO Auto-generated method stub
        // show progress dialog here
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params)
    {
       // TODO Auto-generated method stub
       JSONObject jObject = Phpmysql.connections(params[0]);
       System.out.println(jObject.toString());
       // do your code here
       return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        // TODO Auto-generated method stub
        // dismiss progress dialog here
        super.onPostExecute(result);
    }

}

Call this asynctask class in onCreate() of activity like below:

String my_url = "192.168.1.20/Project/index.php";
new ConnectToPHP.execute(my_url);

Solution 2:

You have to run on a different thread and not the main.

class DownloadJson extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected DownloadJson doInBackground(String... urls) {
       // Get Json here
    }
}

or add this in your onCreate():

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Use the above as a temporary solution. Otherwise use thread or asynctask.


Post a Comment for "Cannot Connect To PHP Using Android Application"