1

I am trying to insert data to mysql database from my android app. I have php file code like this:

<?php

// Connection data
    $host = 'xxxx';;
    $uname = 'xxx';
    $pwd = 'xxx';
    $db = 'xxxx';


    $con = mysql_connect($host,$uname,$pwd) or die("connection failed");
    mysql_select_db($db,$con) or die("db selection failed");

    $nombre=$_REQUEST['nombre'];
    $asunto=$_REQUEST['asunto'];
    $comentario=$_REQUEST['comentario'];

    $flag['code']=0;

    if($r=mysql_query("insert into comentarios (nombre, asunto, comentario) values('$nombre','$asunto','$comentario') ",$con))
    {
        $flag['code']=1;
        echo"hi";
    }

    print(json_encode($flag));
    mysql_close($con);
?>

And in my android app I am using this code:

   class CreateNewComment extends AsyncTask<String, String, String> {

                /**
                 * Before starting background thread Show Progress Dialog
                 * */
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(MyActivity.this);
                    pDialog.setMessage("Enviando comentario..");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }

                /**
                 * Creating product
                 * */
                protected String doInBackground(String... args) {
                    String nombre = inputnombre.getText().toString();
                    String asunto = inputasunto.getText().toString();
                    String comentario = inputcomentario.getText().toString();

                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("nombre", nombre));
                    params.add(new BasicNameValuePair("asunto", asunto));
                    params.add(new BasicNameValuePair("comentario", comentario));

                    // getting JSON Object
                    // Note that create product url accepts POST method
                    JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                            "POST", params);

                    // check log cat fro response
                    Log.d("Create Response", json.toString());

                    // check for success tag
                    try {
                        int success = json.getInt(TAG_SUCCESS);

                        if (success == 1) {
                            // successfully created product
                            Intent i = new Intent(getApplicationContext(), Comunidad.class);
                            startActivity(i);

                            // closing this screen
                            finish();
                        } else {
                            // failed to create product
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    return null;
                }

                /**
                 * After completing background task Dismiss the progress dialog
                 * **/
                protected void onPostExecute(String file_url) {
                    // dismiss the dialog once done
                    pDialog.dismiss();
                }

            }
        }

I always get the error "Invalid IP Address" and in the console I get the error that android.os.NetworkOnMainThreadException. Thanks.

Elena
  • 181
  • 2
  • 12
  • see that answer http://stackoverflow.com/questions/3505930/make-an-http-request-with-android?answertab=active#tab-top – NazarK Jan 28 '15 at 10:37
  • Don't use deprecated `mysql_*` functions; use PDO / MySQLi instead. Invalid IP address... is your URL valid? – Raptor Jan 28 '15 at 10:37

2 Answers2

0

Try putting your code in doInBackground(...) method of an async task in Android. Your network related tasks are not supposed to run on the main thread and doInBackgroung() will run your task on a background thread and publish the result on main thread in onPostExecute(...) method where you can update your UI.

For more information try this link: Make an HTTP request with android

Community
  • 1
  • 1
Nitesh
  • 3,868
  • 1
  • 20
  • 26
0

First of all dont use mysql_* api, its dead old deprecated, use mysqli or PDO. and for PHP script you are not sending a valid json response to client.

header('Content-type: application/json'); //put header
print(json_encode($flag));
mysql_close($con);

and for Android use AsyncTask keep the main UI thread free.

You can use library like Volley to make your life easier. It will make network calls very easy

Update

PHP with PDO

// Connection data
$host = 'xxxx';;
$uname = 'xxx';
$pwd = 'xxx';
$db = 'xxxx';

//Connect to DB using PDO
$db = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $uname, $pwd);

$nombre     = $_REQUEST['nombre'];
$asunto     = $_REQUEST['asunto'];
$comentario = $_REQUEST['comentario'];

$flag['code']=0;

//Insert into DB
$stmt = $db->prepare("INSERT INTO comentarios 
                            (nombre, asunto, comentario) 
                     VALUES (:nombre, :asunto, :comentario)");
$stmt->execute(array(
    ':nombre' => $nombre, 
    ':asunto' => $asunto, 
    ':comentario' => $comentario
));

//Check for affected rows
if($stmt->rowCount() > 0) {
    $flag['code']=1;
}

header('Content-type: application/json'); //put header for json
print(json_encode($flag));
Saqueib
  • 3,484
  • 3
  • 33
  • 56