0

我上传了一个用于开发与 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();
            }

        }
    }

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

有什么解决办法吗?

4

2 回答 2

0

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

于 2013-02-16T15:28:05.277 回答
0

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

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

....在您的 AndroidManifest.xml 中的应用程序标记之外的某个位置

于 2013-02-16T15:22:09.723 回答