doudun8705 2013-09-20 14:43
浏览 56
已采纳

通过JSON和PHP发送电子邮件后的Nullpointerexception

I have an application that sends data (username, email) to a database via JSON. After this the user receives an email with his login data from the PHP script, this works everytime. But after this the application is crashing. I don't get why. Everything is working it's just crashing.

reglogin.java (sorry it's not very clean...)

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.
";
            fail = fail + 1;
        }

        //Check if too much signs
        if(username_length > 20){
            failedinput = failedinput + "Benutzername muss weniger als 20 Zeichen enthalten.
";
            fail = fail + 1;
        }

        if(b){
            failedinput = failedinput + "Benutzername darf keine Sonderzeichen enthalten.
";
            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();
      }


}

Logcat:

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)

new_user.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);
}


?>
  • 写回答

1条回答 默认 最新

  • douxia6554 2013-09-20 14:52
    关注

    Based on the exception's line number, it looks like the NullPointerException is happening on this line:

    int success = json.getInt(TAG_SUCCESS);
    

    This implies the that json object is null. Since you got the following error message:

    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
    

    It looks like the problem is in the decoding of the JSon object. This error says that you tried to convert a string to a JSONObject. I'd look to make sure you're parsing this object correctly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!