从Android应用程序插入mysql数据

时间:2015-01-28 10:35:33

标签: php android mysql

我正在尝试从我的Android应用程序向mysql数据库插入数据。我有这样的php文件代码:

<?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);
?>

在我的Android应用程序中,我正在使用此代码:

   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();
                }

            }
        }

我总是收到错误“无效的IP地址”,在控制台中我收到android.os.NetworkOnMainThreadException错误。感谢。

2 个答案:

答案 0 :(得分:0)

尝试将代码放入Android中异步任务的doInBackground(...)方法中。您的网络相关任务不应该在主线程上运行,doInBackgroung()将在后台线程上运行您的任务,并以onPostExecute(...)方法在主线程上发布结果,您可以在其中更新UI。

有关更多信息,请尝试以下链接: Make an HTTP request with android

答案 1 :(得分:0)

首先,不要使用mysql_* api,其旧版已弃用,请使用 mysqli PDO 。对于PHP脚本,您没有向客户端发送有效的json响应。

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

并且对于Android使用AsyncTask保持主UI线程免费。

您可以使用 Volley 这样的库来让您的生活更轻松。这将使网络呼叫变得非常容易

<强>更新

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));