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:

Errorin 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:

classConnectToPHPextendsAsyncTask<String, String, String>
{
    @OverrideprotectedvoidonPreExecute()
    {
        // TODO Auto-generated method stub// show progress dialog heresuper.onPreExecute();
    }

    @OverrideprotectedStringdoInBackground(String... params)
    {
       // TODO Auto-generated method stubJSONObject jObject = Phpmysql.connections(params[0]);
       System.out.println(jObject.toString());
       // do your code herereturnnull;
    }

    @OverrideprotectedvoidonPostExecute(String result)
    {
        // TODO Auto-generated method stub// dismiss progress dialog heresuper.onPostExecute(result);
    }

}

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

Stringmy_url="192.168.1.20/Project/index.php";
newConnectToPHP.execute(my_url);

Solution 2:

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

classDownloadJsonextendsAsyncTask<String, Void, RSSFeed> {

    privateExceptionexception;

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

or add this in your onCreate():

StrictMode.ThreadPolicypolicy=newStrictMode.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"