我有一个通过 JSON 将数据(用户名、电子邮件)发送到数据库的应用程序。在此之后,用户从 PHP 脚本收到一封包含他的登录数据的电子邮件,这每次都有效。但在此之后,应用程序崩溃了。我不明白为什么。一切正常,只是崩溃了。
reglogin.java (对不起,它不是很干净......)
public class loginreg extends Activity {
public static final int MENU_REGLOGIN = Menu.FIRST;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputUsername, inputEMail;
TextView reguser, regemail;
String inserted, inserted_email, failedinput, txt_inputUsername, message;
static String txt_inputEMail;
int inserted_length, fail;
boolean b;
int userok = 0;
static int emailok = 0;
static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnmABCDEFGHIJKLMNOPQRSTUVWXYZ";
// url to create new product
private static String url_create_product = "http://192.168.99.108/cheateapp/new_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.login_reg);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.header_loginreg);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.cmd_reg);
// Edit Text
inputUsername = (EditText) findViewById(R.id.edit_reguser);
inputEMail = (EditText) findViewById(R.id.edit_regemail);
regemail = (TextView) findViewById(R.id.txt_regemail);
reguser = (TextView) findViewById(R.id.txt_reguser);
inputUsername.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
inserted = inputUsername.getText().toString().trim().replace(" ", "");
inserted_length = inserted.length();
failedinput = "";
fail = 0;
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(inserted);
b = m.find();
reguser.setOnClickListener(null);
check_username(inserted, inserted_length);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
inputEMail.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
inserted_length = inputEMail.getText().toString().length();
inserted_email = inputEMail.getText().toString();
regemail.setOnClickListener(null);
if(isEmailValid(inserted_email)){
regemail.setText(" OK");
regemail.setTextColor(Color.GREEN);
} else {
regemail.setText(" X");
regemail.setTextColor(Color.RED);
regemail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Keine gültige E-Mail Adresse!", Toast.LENGTH_SHORT).show();
}
});
}
//Check if field is empty
if(inserted_length == 0){
regemail.setText(" -");
regemail.setTextColor(Color.WHITE);
emailok = 0;
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
if(userok == 1 && emailok == 1){
new CreateNewUser().execute();
} else {
Toast.makeText(getApplicationContext(), "Benutzerdaten überprüfen!", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* Background Async Task to Create new product
* */
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.v("TEST", "1");
pDialog = new ProgressDialog(loginreg.this);
Log.v("TEST", "1");
pDialog.setMessage("Registrieren..");
Log.v("TEST", "1");
pDialog.setIndeterminate(false);
Log.v("TEST", "1");
pDialog.setCancelable(true);
Log.v("TEST", "1");
pDialog.show();
Log.v("TEST", "1");
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
Log.v("TEST", "1");
String BENUTZER_NAME = txt_inputUsername;
String BENUTZER_PW = getRandomString(5);
String BENUTZER_EMAIL = txt_inputEMail;
Log.v("TEST", "1");
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("BENUTZER_NAME", BENUTZER_NAME));
params.add(new BasicNameValuePair("BENUTZER_EMAIL", BENUTZER_EMAIL));
params.add(new BasicNameValuePair("BENUTZER_PW", BENUTZER_PW));
Log.v("TEST", "1");
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.v("TEST", "12");
// check log cat fro response
//Log.d("Create Response", json.toString());
Log.v("TEST", "1");
// check for success tag
try {
Log.v("TEST", "1");
int success = json.getInt(TAG_SUCCESS);
Log.v("TEST", "1");
message = json.getString(TAG_MESSAGE);
Log.v("TEST", "1");
if (success == 1) {
// successfully created product
Log.v("TEST", "1");
} else {
// failed to create product
Log.v("TEST", "1");
}
} 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
Log.v("TEST", "1");
pDialog.dismiss();
Log.v("TEST", "1");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
Log.v("TEST", "1");
finish();
}
}
public void check_username(String username, int username_length){
//Check if too less signs
if(username_length < 4){
failedinput = "Benutzername muss mehr als 4 Zeichen enthalten.\n";
fail = fail + 1;
}
//Check if too much signs
if(username_length > 20){
failedinput = failedinput + "Benutzername muss weniger als 20 Zeichen enthalten.\n";
fail = fail + 1;
}
if(b){
failedinput = failedinput + "Benutzername darf keine Sonderzeichen enthalten.\n";
fail = fail + 1;
}
if(fail > 0){
reguser.setText(" X");
reguser.setTextColor(Color.RED);
userok = 0;
reguser.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), failedinput, Toast.LENGTH_SHORT).show();
}
});
} else {
reguser.setText(" OK");
reguser.setTextColor(Color.GREEN);
txt_inputUsername = username.trim().replace(" ", "");
userok = 1;
}
//Check if field is empty
if(inserted_length == 0){
reguser.setText(" -");
reguser.setTextColor(Color.WHITE);
userok = 0;
}
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
txt_inputEMail = email;
emailok = 1;
} else {
emailok = 0;
}
return isValid;
}
private static String getRandomString(final int sizeOfRandomString)
{
final Random random=new Random();
final StringBuilder sb=new StringBuilder();
for(int i=0;i<sizeOfRandomString;++i)
sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
return sb.toString();
}
}
日志猫:
09-20 16:36:53.600: D/SensorManager(978): unregisterListener:: Listener= android.view.OrientationEventListener$SensorEventListenerImpl@42245de0
09-20 16:36:53.600: D/Sensors(978): Remain listener = Sending .. normal delay 200ms
09-20 16:36:53.600: I/Sensors(978): sendDelay --- 200000000
09-20 16:36:53.600: D/SensorManager(978): JNI - sendDelay
09-20 16:36:53.600: I/SensorManager(978): Set normal delay = true
09-20 16:36:56.850: E/JSON Parser(978): Error parsing data org.json.JSONException: Value 2013-09-20 of type java.lang.String cannot be converted to JSONObject
09-20 16:36:56.850: V/TEST(978): 12
09-20 16:36:56.850: V/TEST(978): 1
09-20 16:36:56.850: V/TEST(978): 1
09-20 16:36:56.855: W/dalvikvm(978): threadid=13: thread exiting with uncaught exception (group=0x412a32a0)
09-20 16:36:56.855: E/AndroidRuntime(978): FATAL EXCEPTION: AsyncTask #1
09-20 16:36:56.855: E/AndroidRuntime(978): java.lang.RuntimeException: An error occured while executing doInBackground()
09-20 16:36:56.855: E/AndroidRuntime(978): at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-20 16:36:56.855: E/AndroidRuntime(978): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.lang.Thread.run(Thread.java:856)
09-20 16:36:56.855: E/AndroidRuntime(978): Caused by: java.lang.NullPointerException
09-20 16:36:56.855: E/AndroidRuntime(978): at spicysoftware.cheatapp.loginreg$CreateNewUser.doInBackground(loginreg.java:196)
09-20 16:36:56.855: E/AndroidRuntime(978): at spicysoftware.cheatapp.loginreg$CreateNewUser.doInBackground(loginreg.java:1)
09-20 16:36:56.855: E/AndroidRuntime(978): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-20 16:36:56.855: E/AndroidRuntime(978): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-20 16:36:56.855: E/AndroidRuntime(978): ... 5 more
09-20 16:37:07.290: E/WindowManager(978): Activity spicysoftware.cheatapp.loginreg has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@429be460 that was originally added here
09-20 16:37:07.290: E/WindowManager(978): android.view.WindowLeaked: Activity spicysoftware.cheatapp.loginreg has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@429be460 that was originally added here
09-20 16:37:07.290: E/WindowManager(978): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:412)
09-20 16:37:07.290: E/WindowManager(978): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:312)
09-20 16:37:07.290: E/WindowManager(978): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
09-20 16:37:07.290: E/WindowManager(978): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
09-20 16:37:07.290: E/WindowManager(978): at android.view.Window$LocalWindowManager.addView(Window.java:554)
09-20 16:37:07.290: E/WindowManager(978): at android.app.Dialog.show(Dialog.java:277)
09-20 16:37:07.290: E/WindowManager(978): at spicysoftware.cheatapp.loginreg$CreateNewUser.onPreExecute(loginreg.java:166)
09-20 16:37:07.290: E/WindowManager(978): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
09-20 16:37:07.290: E/WindowManager(978): at android.os.AsyncTask.execute(AsyncTask.java:534)
09-20 16:37:07.290: E/WindowManager(978): at spicysoftware.cheatapp.loginreg$3.onClick(loginreg.java:130)
09-20 16:37:07.290: E/WindowManager(978): at android.view.View.performClick(View.java:4223)
09-20 16:37:07.290: E/WindowManager(978): at android.view.View$PerformClick.run(View.java:17275)
09-20 16:37:07.290: E/WindowManager(978): at android.os.Handler.handleCallback(Handler.java:615)
09-20 16:37:07.290: E/WindowManager(978): at android.os.Handler.dispatchMessage(Handler.java:92)
09-20 16:37:07.290: E/WindowManager(978): at android.os.Looper.loop(Looper.java:137)
09-20 16:37:07.290: E/WindowManager(978): at android.app.ActivityThread.main(ActivityThread.java:4898)
09-20 16:37:07.290: E/WindowManager(978): at java.lang.reflect.Method.invokeNative(Native Method)
09-20 16:37:07.290: E/WindowManager(978): at java.lang.reflect.Method.invoke(Method.java:511)
09-20 16:37:07.290: E/WindowManager(978): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
09-20 16:37:07.290: E/WindowManager(978): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
09-20 16:37:07.290: E/WindowManager(978): at dalvik.system.NativeStart.main(Native Method)
新用户.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
include("send_mail.php");
// check for required fields
if (isset($_POST['BENUTZER_NAME']) && isset($_POST['BENUTZER_EMAIL'])) {
$username = $_POST['BENUTZER_NAME'];
$useremail = $_POST['BENUTZER_EMAIL'];
$userpw = $_POST['BENUTZER_PW'];
// include db connect class
require_once 'db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check if user exists
$checkifuserexists = "SELECT COUNT(*) num FROM benutzer WHERE BENUTZER_NAME = '" . mysql_real_escape_string($username) . "'";
$result = mysql_query($checkifuserexists) or die('error');
$row = mysql_fetch_assoc($result);
$checkifemailexists = "SELECT COUNT(*) nummail FROM benutzer WHERE BENUTZER_EMAIL = '" . mysql_real_escape_string($useremail) . "'";
$resultmail = mysql_query($checkifemailexists) or die('error');
$rowmail = mysql_fetch_assoc($resultmail);
if($row['num'] && $rowmail['nummail']) {
$response["success"] = 0;
$response["message"] = "Der Benutzer und die E-Mail Adresse existieren bereits!";
echo json_encode($response);
} else {
if($row['num']){
$response["success"] = 0;
$response["message"] = "Der Benutzer $username existiert bereits!";
echo json_encode($response);
} else {
if($rowmail['nummail']){
$response["success"] = 0;
$response["message"] = "Die E-Mail Adresse $useremail existiert bereits!";
echo json_encode($response);
}else{
// mysql inserting a new row
$result = mysql_query("INSERT INTO benutzer(BENUTZER_NAME, BENUTZER_EMAIL, BENUTZER_PASSWORT) VALUES('$username', '$useremail', '$userpw')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Dein Benutzerkonto wurde erstellt!";
// echoing JSON response
echo json_encode($response);
send_email($username, $useremail, $userpw);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Ein Fehler trat auf!.";
// 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);
}
?>