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

时间:2014-12-19 13:01:08

标签: php android json

我正在创建一个注册表单并通过android中的json将数据发送到MySql数据库,但每当我点击提交按钮时,我的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

这是我注册表单的安卓代码

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



        }




    }

}

这是我用json编码的php代码结果

{"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}

这是我的Php文件

<?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;

        }
    }

&GT;

1 个答案:

答案 0 :(得分:1)

重要

下面的答案涉及如何确保发送正确的标头,但这只有在您的代码本身不包含任何错误时才有效。但是,您的代码确实存在一些需要尽快解决的问题:

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

此语句 生成通知(未定义的偏移量),因为$userDetail初始化为空数组(1D),然后用作2D关联数组。如果php.ini设置为E_STRICT | E_ALL,这将(正确地)生成通知。解决它:

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

如果您不确定代码产生此通知的原因I've explained this here


您正在调用的PHP脚本未生成纯JSON字符串。异常消息告诉您字符串的值以<!DOCTYPE开头。您需要在PHP中添加相应的标头,将其添加到脚本中(在最顶层,在此之前不能发送任何输出):

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

当然,如果PHP脚本包含错误(通知,未捕获的异常等...),那么输出将因此而混乱。彻底调试脚本,也许通过打印(或写入)json.toString()到日志或tmp文件来检查Java中的响应是什么

更新

看起来你正在使用PHP框架(很可能是Laravel)。检查该框架的文档,看看它是否没有为您处理JSON响应的响应组件。如果您正在使用Laravel,则操作应该返回如下:

return Response::json($userDetail);

cf Laravel documentation