Android:无法在MYSQL中插入数据

时间:2014-10-29 13:53:17

标签: php android mysql crash

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

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

    }

}
}

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;

}

我的PHP文件是     

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

我的logcat的屏幕截图 http://i57.tinypic.com/4exk8.png

2 个答案:

答案 0 :(得分:0)

尝试从 doInBackground 方法中删除此剪切代码并将其放入onPostExecute()。

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

答案 1 :(得分:0)

你无法获得editTexts用户&amp;传递你的AsyncTask doInBackground()。 将它们作为Activity中的.execute()的参数提供给它 (注意:在你的OnClickListener中,你必须从Scratch获取它们!):

String[]  myparams = 
{
    ((EditText)findViewById(R.id.username)).getText().toString(),
    ((EditText)findViewById(R.id.password)).getText().toString()
};
new CreateUser().execute(myparams);

现在您可以在AsyncTask中提取它们了:

protected String doInBackground(String... pParams)
{
    String username = pParams[0];
    String password= pParams[1];

    //Do what you like.
}

我认为这是你的日志截图中NullPointerException的原因。 ;)

希望这会有所帮助......