Php Android:无法在MYSQL中插入数据

Php Android:无法在MYSQL中插入数据,php,android,mysql,crash,Php,Android,Mysql,Crash,我正在网站上尝试这个例子。我在MYSQL中插入数据。我面临的问题是,当我输入数据并按下ok按钮时,我的应用程序在几秒钟后崩溃,数据库中没有插入任何数据。我正在使用模拟器。这是我的密码 public class Register extends Activity implements OnClickListener { private EditText user, pass; private Button mRegister; private ProgressDialog pDialog; JSO

我正在网站上尝试这个例子。我在MYSQL中插入数据。我面临的问题是,当我输入数据并按下ok按钮时,我的应用程序在几秒钟后崩溃,数据库中没有插入任何数据。我正在使用模拟器。这是我的密码

public class Register extends Activity implements OnClickListener {
private EditText user, pass;
private Button mRegister;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();

private static final String LOGIN_URL = "http://10.0.2.2:8080/allevents/username.php";


private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);

    mRegister = (Button) findViewById(R.id.register);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    new CreateUser().execute();

}

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


    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setMessage("Creating User...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");


            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);


            Log.d("Login attempt", json.toString());


            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("User Created!", json.toString());
                finish();
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

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

        return null;

    }
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG)
                    .show();
        }

    }

}
}
公共类寄存器扩展活动实现OnClickListener{
私人编辑文本用户,通过;
私人按钮注册器;
私人对话;
JSONParser JSONParser=新的JSONParser();
私有静态最终字符串登录\u URL=”http://10.0.2.2:8080/allevents/username.php";
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_MESSAGE=“MESSAGE”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
mRegister=(按钮)findviewbyd(R.id.register);
mRegister.setOnClickListener(此);
}
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
新建CreateUser().execute();
}
类CreateUser扩展异步任务{
布尔失败=假;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(Register.this);
setMessage(“正在创建用户…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…args){
成功;
字符串username=user.getText().toString();
字符串密码=pass.getText().toString();
试一试{
//建筑参数
List params=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
添加(新的BasicNameValuePair(“密码”,password));
Log.d(“请求!”,“启动”);
JSONObject json=jsonParser.makeHttpRequest(登录地址,“POST”,
参数);
Log.d(“登录尝试”,json.toString());
success=json.getInt(TAG_success);
如果(成功==1){
Log.d(“用户创建的!”,json.toString());
完成();
返回json.getString(TAG_消息);
}否则{
Log.d(“登录失败!”,json.getString(TAG_MESSAGE));
返回json.getString(TAG_消息);
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
受保护的void onPostExecute(字符串文件\u url){
//删除产品后关闭对话框
pDialog.disclose();
如果(文件url!=null){
Toast.makeText(Register.this,file\u url,Toast.LENGTH\u LONG)
.show();
}
}
}
}
JSONParser.java

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";


public JSONParser() {

}

public JSONObject getJSONFromUrl(final String url) {


    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);


        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);

        StringBuilder sb = new StringBuilder();

        String line = null;


        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }


        is.close();

        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }


    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }


    return jObj;

}


public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {


    try {


        if (method == "POST") {


            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }


    return jObj;

}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
公共JSONParser(){
}
公共JSONObject getJSONFromUrl(最终字符串url){
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
返回jObj;
}
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
试一试{
如果(方法==“POST”){
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”
<?php
$response = array();


if (isset($_POST['username']) && isset($_POST['password'])) {


$username = $_POST['username'];
$password = $_POST['password'];




// include db connect class
require_once __DIR__ . '/db_connect.php';


$db = new DB_CONNECT();


$result = mysql_query("INSERT INTO users(Username,Password) VALUES('$username', '$password')");
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Operation successfull";
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    echo json_encode($response);
}
} else {

$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
</body>
</html>
    Log.d("Login attempt", json.toString());


                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created!", json.toString());
                    finish();
                    return json.getString(TAG_MESSAGE);
                } else {
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
String[]  myparams = 
{
    ((EditText)findViewById(R.id.username)).getText().toString(),
    ((EditText)findViewById(R.id.password)).getText().toString()
};
new CreateUser().execute(myparams);
protected String doInBackground(String... pParams)
{
    String username = pParams[0];
    String password= pParams[1];

    //Do what you like.
}