Android: невозможно вставить данные в MYSQL

Я пытаюсь этот пример с сайта. в котором я вставляю данные в 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

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

Другие решения

Вы не можете получить пользователя editTexts & передать в свой AsyncTask doInBackground ().
Дайте им это в качестве параметров .execute () в вашей деятельности
(ПРИМЕЧАНИЕ: в вашем OnClickListener вы должны получить их с нуля!):

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 в вашем лог-скриншоте. 😉

Надеюсь это поможет…

0