用mysql连接android应用程序

时间:2013-02-16 15:16:30

标签: android mysql

我上传了一个用于开发与mysql和php连接的Android应用程序的代码来学习。从这里开始:http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ 我试图采取相同的步骤来进一步理解。 我在同一个数据库中创建了第二个表(测试)..我编写了用于在(测试表)中创建新原始的php代码。 这是php代码:

 <?php



// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['age'])){

    $name = $_POST['name'];
    $age = $_POST['age'];
    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO test (name, age) VALUES('$name', '$age')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "row successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

之后我在eclipse项目中添加了一个java类,代码如下:

package com.example.androidhive;



import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewRowActivity extends Activity{

    // Progress Dialog
        private ProgressDialog pDialog;

        JSONParser jsonParser = new JSONParser();

        EditText inputName;
        EditText inputAge;

        // url to create new row
        private static String url_create_raw = "http://10.0.2.2/test/create_row.php";

        // JSON Node names
        private static final String TAG_SUCCESS = "success";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.add_raw);

            // Edit Text
            inputName = (EditText) findViewById(R.id.editTextName);
            inputAge = (EditText) findViewById(R.id.editTextAge);


            // Create button
            Button btnAddRow = (Button) findViewById(R.id.buttonAdd);

            // button click event
            btnAddRow.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    // creating new product in background thread
                    new CreateNewRow().execute();
                }
            });
        }


        /**
         * Background Async Task to Create new product
         * */
        class CreateNewRow extends AsyncTask<String, String, String> {

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

            /**
             * Adding raw
             * */
            protected String doInBackground(String... args) {
                String name = inputName.getText().toString();
                String age = inputAge.getText().toString();


                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", name));
                params.add(new BasicNameValuePair("age", age));


                // getting JSON Object
                // Note that create product url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_create_raw,
                        "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(), MainScreenActivity.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();
            }

        }
    }

当应用程序在模拟器中运行时,它不起作用!然后模拟器停了下来。

任何解决方案?

2 个答案:

答案 0 :(得分:0)

您是否为此示例应用配置了Android Manifest,以便它有权访问互联网?如果您还没有这样做,则需要将INTERNET权限添加到清单文件中:

<uses-permission android:name="android.permission.INTERNET" /> 

.... AndroidManifest.xml中应用程序标记之外的某个地方

答案 1 :(得分:0)

你的方法有点超出常规。你为什么不形成一个类/方法来连接php脚本,然后你可以调用它?这是一种更好的方法。