Android 致命异常:AsyncTask #5 和 Error parseing data org.json.JSO


Android FATAL EXCEPTION: AsyncTask #5 and Error parsing data org.json.JSONException

我尝试进行注册过程,但发生了这些,我遇到了一些错误。
愿有人帮助我..由于我不知道该怎么办,我已经搜索了其他类似的情况,但仍然..不明白..

日志猫

11-21 15:30:30.762: D/dalvikvm(3859): GC_FOR_ALLOC freed 126K, 10% free 3294K/3636K, paused 7ms, total 7ms
11-21 15:30:53.194: E/ini(3859): bisa
11-21 15:30:53.234: D/dalvikvm(3859): GC_FOR_ALLOC freed 161K, 10% free 3503K/3884K, paused 11ms, total 11ms
11-21 15:30:53.234: I/dalvikvm-heap(3859): Grow heap (frag case) to 4.705MB for 1127532-byte allocation
11-21 15:30:53.250: D/dalvikvm(3859): GC_FOR_ALLOC freed 1K, 8% free 4602K/4988K, paused 9ms, total 14ms
11-21 15:30:53.270: E/ini(3859): bisa
11-21 15:30:53.310: D/request!(3859): starting
11-21 15:30:53.330: W/EGL_genymotion(3859): eglSurfaceAttrib not implemented
11-21 15:31:01.970: E/JSON Parser(3859): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
11-21 15:31:01.974: W/dalvikvm(3859): threadid=15: thread exiting with uncaught exception (group=0xa4b74648)
11-21 15:31:01.982: E/AndroidRuntime(3859): FATAL EXCEPTION: AsyncTask #5
11-21 15:31:01.982: E/AndroidRuntime(3859): java.lang.RuntimeException: An error occured while executing doInBackground()
11-21 15:31:01.982: E/AndroidRuntime(3859):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at java.lang.Thread.run(Thread.java:841)
11-21 15:31:01.982: E/AndroidRuntime(3859): Caused by: java.lang.NullPointerException
11-21 15:31:01.982: E/AndroidRuntime(3859):     at com.android.GoTrip.Register$CreateUser.doInBackground(Register.java:147)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at com.android.GoTrip.Register$CreateUser.doInBackground(Register.java:1)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-21 15:31:01.982: E/AndroidRuntime(3859):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-21 15:31:01.982: E/AndroidRuntime(3859):     ... 4 more
11-21 15:31:02.350: W/EGL_genymotion(3859): eglSurfaceAttrib not implemented
11-21 15:31:02.814: E/WindowManager(3859): Activity com.android.GoTrip.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{52784ba4 V.E..... R......D 0,0-684,192} that was originally added here
11-21 15:31:02.814: E/WindowManager(3859): android.view.WindowLeaked: Activity com.android.GoTrip.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{52784ba4 V.E..... R......D 0,0-684,192} that was originally added here
11-21 15:31:02.814: E/WindowManager(3859):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
11-21 15:31:02.814: E/WindowManager(3859):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
11-21 15:31:02.814: E/WindowManager(3859):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
11-21 15:31:02.814: E/WindowManager(3859):  at android.app.Dialog.show(Dialog.java:281)
11-21 15:31:02.814: E/WindowManager(3859):  at com.android.GoTrip.Register$CreateUser.onPreExecute(Register.java:103)
11-21 15:31:02.814: E/WindowManager(3859):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
11-21 15:31:02.814: E/WindowManager(3859):  at android.os.AsyncTask.execute(AsyncTask.java:534)
11-21 15:31:02.814: E/WindowManager(3859):  at com.android.GoTrip.Register.btnRegister(Register.java:83)
11-21 15:31:02.814: E/WindowManager(3859):  at java.lang.reflect.Method.invokeNative(Native Method)
11-21 15:31:02.814: E/WindowManager(3859):  at java.lang.reflect.Method.invoke(Method.java:525)
11-21 15:31:02.814: E/WindowManager(3859):  at android.view.View$1.onClick(View.java:3628)
11-21 15:31:02.814: E/WindowManager(3859):  at android.view.View.performClick(View.java:4240)
11-21 15:31:02.814: E/WindowManager(3859):  at android.view.View$PerformClick.run(View.java:17721)
11-21 15:31:02.814: E/WindowManager(3859):  at android.os.Handler.handleCallback(Handler.java:730)
11-21 15:31:02.814: E/WindowManager(3859):  at android.os.Handler.dispatchMessage(Handler.java:92)
11-21 15:31:02.814: E/WindowManager(3859):  at android.os.Looper.loop(Looper.java:137)
11-21 15:31:02.814: E/WindowManager(3859):  at android.app.ActivityThread.main(ActivityThread.java:5103)
11-21 15:31:02.814: E/WindowManager(3859):  at java.lang.reflect.Method.invokeNative(Native Method)
11-21 15:31:02.814: E/WindowManager(3859):  at java.lang.reflect.Method.invoke(Method.java:525)
11-21 15:31:02.814: E/WindowManager(3859):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-21 15:31:02.814: E/WindowManager(3859):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-21 15:31:02.814: E/WindowManager(3859):  at dalvik.system.NativeStart.main(Native Method)
11-21 15:31:04.154: I/Process(3859): Sending signal. PID: 3859 SIG: 9

JSON praser

   public class JSONParser {
static InputStream is = null;
static String json = "";
static JSONObject jObj = null;
public static JSONObject getJSONfromURL(String url) {
    String result = "";
    JSONObject jArray = null;
    Log.d("Json", "1");
    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    // convert response to string
    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();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }
    Log.d("Json", "2");
    Log.d("Json", result);
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
    return jArray;
}
public static JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {
    try {
        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            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") {
            // request method is 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 parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}
}

注册.java

    public class Register  extends Activity {

EditText inputUsername;
EditText inputNama;
EditText inputEmail;
EditText inputPassword;
EditText inputPassword2;
Button btnRegister;
Button btnLogin;

private ProgressDialog pDialog; 
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://10.0.3.2/1aaa/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.register);
    inputUsername = (EditText) findViewById(R.id.username);
    inputNama = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    inputPassword2 = (EditText) findViewById(R.id.password2);

    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLogin = (Button) findViewById(R.id.btnLinkToLogin);

}

    public void btnRegister(View v) {
        // TODO Auto-generated method stub
        Log.e("ini", "bisa");
        new CreateUser().execute();
        Log.e("ini", "bisa");
    }

    class CreateUser extends AsyncTask<String, String, String> {
         /**
         * Before starting background thread Show Progress Dialog
         * */
        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();
        }
        @SuppressWarnings("static-access")
        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
                String username = inputUsername.getText().toString();
                String name = inputNama.getText().toString();
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                String password2 = inputPassword2.getText().toString();
                Encrypt a = new Encrypt();
                a.encrrypte(password);
                String encpassword = a.GetHashtext();
                a.encrrypte(password2);
                String encretypepwd = a.GetHashtext();
                Date c = Calendar.getInstance().getTime();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String output = formatter.format(c);
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("username", username));
                        params.add(new BasicNameValuePair("name", name));
                        params.add(new BasicNameValuePair("email", email));
                        params.add(new BasicNameValuePair("password", encpassword));
                        params.add(new BasicNameValuePair("password2", encretypepwd));
                        params.add(new BasicNameValuePair("ctime",  output));
                        params.add(new BasicNameValuePair("date_edit_profile", "0000-00-00 00:00:00"));

                        Log.d("request!", "starting");
                        //Posting user data to script 
                        JSONObject json = jsonParser.makeHttpRequest(
                               LOGIN_URL, "POST", params);
                        // full json response
                        Log.d("Login attempt", json.toString());
                        // json success element
                        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;
                }
                /**
                 * After completing background task Dismiss the progress dialog
                 * **/

                    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();
                    }
                }
    }
    public void btnLogin(View v){
        Intent s = new Intent(this, Login.class);
        startActivity(s);
    }

            public class Encrypt{
                private String hashtext= "";
                public void encrrypte(String yourString){
                    try {
                        byte[] bytesOfMessage = yourString.getBytes("UTF-8");
                        MessageDigest md = MessageDigest.getInstance("MD5");
                        byte[] thedigest = md.digest(bytesOfMessage);
                        BigInteger bigInt = new BigInteger(1,thedigest);
                        hashtext = bigInt.toString(16);
                        // Now we need to zero pad it if you actually want the full 32 chars.
                        while(hashtext.length() < 32 ){
                          hashtext = "0"+hashtext;
                        }
                    } catch (UnsupportedEncodingException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                public String GetHashtext(){
                    return hashtext;
                }
            }
    }

注册.php

<?php
require("config.php");
$email="";
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (!empty($_POST)) {

if (empty($_POST['username'])) {
    // Create some data that will be the JSON response 
    $response["success"] = 0;
    $response["message"] = "Please input username";
    die(json_encode($response));
}  
if (empty($_POST['name'])) {
  $response["success"] = 0;
    $response["message"] = "Please input your name";
    die(json_encode($response));
} 
if (empty($_POST['email'])) {
    $response["success"] = 0;
    $response["message"] = "Please input your email address";
    die(json_encode($response));
}  
else{
    $email = test_input($_POST['email']);
    if(!preg_match("/(['w'-]+'@['w'-]+'.['w'-]+)/",$email)){
    $response["success"] = 0;
    $response["message"] = "Input the correct email address form";
    die(json_encode($response));
    }
}
if (empty($_POST['password'])) {
    $response["success"] = 0;
    $response["message"] = "Please input a Password.";
    die(json_encode($response));
} 
else{
    if(strlen($_POST['password'])<6){
            $response["success"] = 0;
            $response["message"] = "password length should be longer than 6 characters";
            die(json_encode($response));
    }
    else{
        if ($_POST['password']!=$_POST['password2']){
            $response["success"] = 0;
            $response["message"] = "Password doesn't match";
            die(json_encode($response));
        }
    }
}


$query        = " SELECT 1 FROM user WHERE username = :user";
$query_params = array(
    ':user' => $_POST['username']
);
try {
    // These two statements run the query against your database table. 
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));
}

$row = $stmt->fetch();
if ($row) {
    $response["success"] = 0;
    $response["message"] = "I'm sorry, this username is already in use";
    die(json_encode($response));
}

$query = ("INSERT INTO user ( username, name, password, email, role_id,ctime) VALUES ( :user, :name, :password, :email , :role_id, :ctime) ");
//Again, we need to update our tokens with the actual data:
$query_params = array(
    ':user' => $_POST['username'],
    ':name' => $_POST['name'],
    ':password' => $_POST['password'],
    ':email' => $_POST['email'],
    ':role_id'  => '2',
    ':ctime' => $_POST['ctime'],
    );

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error2. Please Try Again!";
    die(json_encode($response));
}

$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);


} else {
?>
<h1>Register</h1> 
<form action="register.php" method="post"> 
    Username:<br /> 
    <input type="text" name="username" value="" /> 
    <br /><br />
     Name:<br /> 
    <input type="text" name="name" value="" /> 
    <br /><br /> 
    Email:<br /> 
    <input type="text" name="email" value="" /> 
    <br /><br /> 
    Password:<br /> 
    <input type="password" name="password" value="" /> 
    <br /><br />
    Confirm Your Password:<br /> 
    <input type="password" name="password2" value="" /> 
    <br /><br />
    <input type="submit" value="Register New User" /> 
</form>
<?php
}
?>

注册.xml

 <!-- View Title Label -->
 <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginLeft="7dp"
     android:layout_marginRight="7dp"
     android:layout_marginTop="15dp"
     android:gravity="center_horizontal"
     android:orientation="vertical" >
<TextView
    android:id="@+id/TextView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="10dip"
    android:text="REGISTER"
    android:textSize="25dip"
    android:textStyle="bold" />
<!-- Name Label -->
<TextView
    android:id="@+id/TextView2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/TextView1"
    android:text="Username" />
<!-- Name TextField -->
<EditText
    android:id="@+id/username"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/TextView2" />
<TextView
    android:id="@+id/TextView3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/username"
    android:text="Name" />
<!-- NAME TextField -->
<EditText
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/TextView3" />
 <!-- Email Label -->
<TextView
    android:id="@+id/TextView4"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/name"
    android:text="Email" />
<!-- Email TextField -->
<EditText
    android:id="@+id/email"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/TextView4" />
<!-- Password Label -->
<TextView
    android:id="@+id/TextView5"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/registerEmail"
    android:text="Password" />
<!-- Password TextField -->
<EditText
    android:id="@+id/password"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/TextView5"
    android:password="true" />
<!-- Password Label -->
<TextView
    android:id="@+id/TextView6"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/registerEmail"
    android:text="Re-type Password" />
<!-- Password TextField -->
<EditText
    android:id="@+id/password2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/TextView5"
    android:password="true" />
<!-- Error message -->

<!-- Login Button -->
<Button
    android:id="@+id/btnRegister"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/register_error"
    android:layout_marginTop="2dip"
    android:text="Register"
    android:onClick="btnRegister" />
<!-- Link to Login Screen -->
<Button
    android:id="@+id/btnLinkToLogin"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/btnRegister"
    android:layout_marginTop="4dip"
    android:background="@null"
    android:text="Already registered. Login Me!"
    android:textColor="#c90505"
    android:textStyle="bold"
    android:onClick="btnLogin" />
   </LinearLayout>
<LinearLayout
    android:id="@+id/footer"
    android:layout_width="fill_parent"
    android:layout_height="65dip"
    android:layout_alignParentBottom="true"
    android:background="@layout/zfooter"
    android:orientation="vertical" >
</LinearLayout>

请帮我:(

以下错误是您问题的根源 -

11-21 15:31:01.970:E/JSON 解析器(3859):解析数据时出错 org.json.JSONException:无法将 java.lang.String 类型的值<br转换为 JSONObject

NullPointerException 是 JSON 解析器无法解析来自 URL 的响应的结果。

您必须验证从http://10.0.3.2/1aaa/register.php收到的 POST 响应是否为 JSON 格式。

从错误代码来看,响应中似乎有一个<br />,导致解析错误。

Caused by: java.lang.NullPointerException
    at com.android.GoTrip.Register$CreateUser.doInBackground(Register.java:147)

也许这是因为json.getInt(TAG_SUCCESS)success 中存储了一个 null 值,因为解析器没有从 register.php 获得正确的响应,或者您使用了错误的键(响应中不存在TAG_SUCCESS)。

对于调试,您可以尝试删除if块并直接打印出successjson.toString()的值。