douyalin0847 2014-12-19 13:01
浏览 157
已采纳

在我的代码中获取JSON Parser的错误

I am creating a registration form and sending data to MySql database through json in android but whenever i do click on submit button I got the following error in my logcat.

    12-19 18:19:22.145: E/JSON Parser(2620): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
12-19 18:19:22.365: W/dalvikvm(2620): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
12-19 18:19:22.865: E/AndroidRuntime(2620): FATAL EXCEPTION: AsyncTask #1
12-19 18:19:22.865: E/AndroidRuntime(2620): java.lang.RuntimeException: An error occured while executing doInBackground()
12-19 18:19:22.865: E/AndroidRuntime(2620):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.lang.Thread.run(Thread.java:856)
12-19 18:19:22.865: E/AndroidRuntime(2620): Caused by: java.lang.NullPointerException
12-19 18:19:22.865: E/AndroidRuntime(2620):     at app.restaurant.Register_Activity$RegisterUser.doInBackground(Register_Activity.java:162)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at app.restaurant.Register_Activity$RegisterUser.doInBackground(Register_Activity.java:1)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-19 18:19:22.865: E/AndroidRuntime(2620):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-19 18:19:22.865: E/AndroidRuntime(2620):     ... 5 more

This is my android code of registering form

Register_Activity.java

public class Register_Activity extends Activity {



//RadioGroup rg;

private ProgressDialog pDialog;
  // RadioButton rb;
 //  int id;

TextView nm,ad,ps,ph,em;
 String password;
    Button bnt_Submit;
    EditText edt_email,edt_password,edt_name,edt_phone,edt_address,edt_lastName;
    JSONObject json;

    JSONParser jsonParser = new JSONParser();

    private static String url_create_product = "http://192.168.1.9/adminfoodOld/public/jsonregister";

    //http://www.truzzinfotech.co.nz/admin/public/jsonregister


    private static final String TAG_SUCCESS = "success";



    //JSONArray phn,eml,pas,add,nam;
    String gender ="Male";
   @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

/*
     nm  = (TextView)findViewById(R.id.TXt_Name);
     em  = (TextView)findViewById(R.id.TXt_Email);
     ph  = (TextView)findViewById(R.id.TXt_Ph);
     ps  = (TextView)findViewById(R.id.TXt_password);
     ad  = (TextView)findViewById(R.id.TXt_Ad);

    */
    // rg = (RadioGroup)findViewById(R.id.radioGroup1);
    bnt_Submit =(Button)findViewById(R.id.btnsubmit);
    edt_email = (EditText)findViewById(R.id.Edt_Email);
    edt_password = (EditText)findViewById(R.id.Edt_Password);
    edt_name  = (EditText)findViewById(R.id.Edt_Name);
    edt_phone = (EditText)findViewById(R.id.Edt_Phone);
    edt_address = (EditText)findViewById(R.id.Edt_Address);
    edt_lastName = (EditText)findViewById(R.id.Edt_LastName);

/*   id = rg.getCheckedRadioButtonId();
      rb = (RadioButton)findViewById(id);*/
    bnt_Submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            password = edt_password.getText().toString();
            if (!isValidPassword(password)) {
                edt_password.setError("The Passward must be at least 8 character ");
            }




              // Toast.makeText(getApplicationContext(), gender+"Selected", Toast.LENGTH_LONG).show();
            new RegisterUser().execute();



            }

    });

}


private boolean isValidPassword(String pass) {
    if (pass != null && pass.length() > 7) {
        return true;
    }
    return false;
}

class RegisterUser extends AsyncTask<String, String, String> {



    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        pDialog = new ProgressDialog(Register_Activity.this);
        pDialog.setMessage("Registering...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();


    }

    @Override
    protected String doInBackground(String... params) {

// TODO Auto-generated method stub
        //  gender= rb.getText().toString();

         String firstname =edt_name.getText().toString();
         String emails =edt_email.getText().toString();
         String phone =edt_phone.getText().toString();
         String address =edt_address.getText().toString();
         String lastname =edt_lastName.getText().toString();






     List<NameValuePair> params1 = new ArrayList<NameValuePair>();
     params1.add(new BasicNameValuePair("firstname", firstname));
     params1.add(new BasicNameValuePair("password", password));
     params1.add(new BasicNameValuePair("email", emails));
     params1.add(new BasicNameValuePair("phone", phone));
     params1.add(new BasicNameValuePair("address",address));
     params1.add(new BasicNameValuePair("gender", gender));
     params1.add(new BasicNameValuePair("lastname", lastname));
     Log.d("param",params1.toString());

 json = jsonParser.makeHttpRequest(url_create_product,"POST", params1);


     Log.d("Create Response", json.toString());

    /* Log.d("Gender", gender.toString());
     Log.d("name", firstname.toString());
     Log.d("pass", password.toString());
     Log.d("email", emails.toString());
     Log.d("lastname", lastname.toString());
     Log.d("address", address.toString());*/



     try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
            /*  Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);*/


            //  Toast.makeText(getApplicationContext(),"ravi kujaa", Toast.LENGTH_LONG).show();

                // closing this screen
                //finish();
            } else {
                // failed to create product



            }
     }catch (Exception e) {
                // TODO: handle exception
            }
    return null;





    }




    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();


                    /* try {


                            JSONObject json1 = json.getJSONObject("detail");




                    //   phn,eml,pas,add,nam;

                     phn = json1.optJSONArray("phone");
                     eml = json1.optJSONArray("email");
                     pas = json1.optJSONArray("password");
                     add = json1.optJSONArray("address");
                     nam = json1.optJSONArray("name");

                //  Log.d("Else_Part", json.toString());

                    Log.d("Name", nam.getString(0));
                    Log.d("Phone", phn.getString(0));
                    Log.d("Email", eml.getString(0));
                    Log.d("Password", pas.getString(0));
                    Log.d("Address", add.getString(0));


                    //edt_email,edt_password,edt_name,edt_phone,edt_address;
                    if(nam != null) {
                        nm.setText(nam.getString(0));
                        }

                        if(eml!= null ){
                        em.setText(eml.getString(0));
                        }
                        if(phn!= null ){
                        ph.setText(phn.getString(0));
                        }
                        if(pas!= null ){
                        ps.setText(pas.getString(0));
                        }
                        if(add!= null ){
                        ad.setText(add.getString(0));
                        }





                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                */



        }




    }

}

This is my php code result encoded in json

{"detail":{"email":["The email field is required."],"password":["The password field is required."],"firstname":["The firstname field is required."],"lastname":["The lastname field is required."],"phone":["The phone field is required."],"address":["The address field is required."]},"success":0}

This is my Php file

<?php

class FrontUserController extends \BaseController {

    /**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index()
{

    if(controllerAssignView('frontuser'))      
    {

    $frontuser = frontuser::all();

    return View::make('admin.registered')->with('data', $frontuser);
    }
    else
    {
            return Redirect::to('index');
    }
}


    public function jsonregister()
{

        $inputs = Input::all();
        $validator = Validator::make(
            array(
                'email' => $inputs['email'],
                'password' => $inputs['password'],
                'firstname' => $inputs['firstname'],
                'lastname' => $inputs['lastname'],
                'phone' => $inputs['phone'],
                'address' => $inputs['address']

            ),
            array(
                'email' => 'required|email|unique:frontuser',
                'password' => 'required|min:8',
                'firstname' => 'required',
                'lastname' => 'required',
                'phone' => 'required|numeric',
                'address' => 'required'

            )
        );
    if ($validator->fails())
        {
            $messages = $validator->messages();
            $userDetail = array();
            $userDetail['detail'] = $messages;
            $userDetail['success'] = 0;
            return $userDetail;
        }
        else
        {

                $Frontuser = new frontuser;
                $Frontuser->email = $inputs['email'];
                $Frontuser->password =  Hash::make($inputs['password']);
                $Frontuser->firstname = $inputs['firstname'];
                $Frontuser->lastname = $inputs['lastname'];
                $Frontuser->phone = $inputs['phone'];
                $Frontuser->address = $inputs['address'];
                $Frontuser->status = $inputs['active'];
                $Frontuser->gender = $inputs['gender'];
                if($inputs['type'] != 'null'){$Frontuser->$inputs['type'] =1;}

                $Frontuser->save();

                $user = frontuser::where('email', '=', $inputs['email'])->take(1)->get();


                    $userDetail = array();
                    $userDetail['detail']['firstname'] = $user[0]->firstname;
                    $userDetail['detail']['lastname'] = $user[0]->lastname;
                    $userDetail['detail']['gender'] = $user[0]->gender;
                    $userDetail['detail']['phone'] = $user[0]->phone;
                    $userDetail['detail']['address'] = $user[0]->address;
                    if($user[0]->facebook == 1){$userDetail['detail']['login'] = 'registered with facebook.';}
                    if($user[0]->twitter == 1){$userDetail['detail']['login'] = 'registered with twitter.';}
                    if($user[0]->googleplus == 1){$userDetail['detail']['login'] = 'registered with googleplus.';}
                    $userDetail['success'] = 1;
                    return $userDetail;

        }
    }

?>

  • 写回答

1条回答 默认 最新

  • douxunnian0423 2014-12-19 13:10
    关注

    Important:

    The answer below deals with how to ensure the correct headers are sent, but this can only work if your code itself doesn't contain any errors. Your code, however, does have some issues that need to be addressed ASAP:

    $userDetail = array();
    $userDetail['detail']['firstname'] = $user[0]->firstname;
    

    This statement will produce a notice (undefined offset), because $userDetail is initialized to an empty array (1D), and then used as a 2D associative array. If php.ini is set to E_STRICT | E_ALL this will (rightfully) generate a notice. Fix it:

    $userDetail = array('detail' => array());
    

    If you're unsure as to why your code produces this notice I've explained this here


    The PHP script you're calling isn't generating a pure JSON string. The exception message tells you the string's value starts with a <!DOCTYPE. You'll need to set the appropriate headers in PHP by adding this to your script (at the very top, no output can be sent prior to this point):

    <?php //before this opening tag, not even a space is allowed!
    header('Content-Type: application/json');
    $data = ['get' => 'data', 'here'];
    echo json_encode($data);
    

    Of course, if the PHP script contains errors (notices, uncaught exceptions etc...), then the output will be messed up because of that. Debug the script thoroughly, and perhaps check what the response looks like in Java by printing (or writing) json.toString() to a log or tmp file

    Update:

    It looks like you're using a PHP framework (Laravel most likely). Check that framework's docs to see if it doesn't have a response component that handles JSON responses for you. In case you're using Laravel, the action should return like so:

    return Response::json($userDetail);
    

    cf Laravel documentation

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

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘