4

我正在用 eclipse 开发一个应用程序。我试图将用户键入的数据存储到 phpmyadmin 的数据库中。不幸的是,用户点击提交按钮后,没有响应,数据也没有存储在我的数据库中。

这是我的java文件:

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

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.content.res.Configuration;

public class UserRegister extends Activity {

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
RadioButton button1;
RadioButton button2;
Button button3;
int success = 0;

private static String url_register_user = "http://10.20.92.81/database/add_user.php";
private static final String TAG_SUCCESS = "success";

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

    inputName = (EditText) findViewById(R.id.nameTextBox);
    inputUsername = (EditText) findViewById(R.id.usernameTextBox);
    inputEmail = (EditText) findViewById(R.id.emailTextBox);
    inputPassword = (EditText) findViewById(R.id.pwTextBox);

    Button button3 = (Button) findViewById(R.id.regSubmitButton);

    button3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            String name = inputName.getText().toString();
            String username = inputUsername.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals(""))
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this);


                builder.setMessage(R.string.nullAlert)
                   .setTitle(R.string.alertTitle);

                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {

                   }
               });

            AlertDialog dialog = builder.show();
            }

            // creating new product in background thread
                RegisterNewUser();  
        }
    });
}


   public void RegisterNewUser()
   {
   try
   {
        String name = inputName.getText().toString();
        String username = inputUsername.getText().toString();
        String email = inputEmail.getText().toString();
        String password = inputPassword.getText().toString();

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

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

        // check log cat for response
        Log.d("Send Notification", json.toString());

        success = json.getInt(TAG_SUCCESS);

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

        else
        {
            // failed to register

        }
   }

    catch (Exception e)
    {
       e.printStackTrace();
    }
   }

   @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }
}

我的 php 文件:

<?php
$response = array();

require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();


if (isset($_GET['name']) && isset($_GET['username']) && isset($_GET['email']) && isset($_GET['password'])) {

$name = $_GET['name'];
$username = $_GET['username'];
$email = $_GET['email'];
$password = $_GET['password'];


// mysql inserting a new row
$result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password')");

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

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

日志猫如下:

11-25 10:37:46.772: I/Choreographer(638): Skipped 30 frames!  The application may be doing too much work on its main thread.
4

1 回答 1

1

首先,遵循 Java 命名约定并保持方法名称以小写字母开头。

其次,你必须得到一个NetworkOnMainThreadException,因为你正在你的 UI 线程上执行阻塞网络操作。你这样做,你会过得很糟糕。

将所有网络代码放在一个异步任务中,或者至少放在一个单独的线程中。

于 2012-11-25T10:48:22.167 回答