错误:org.json.JSONException:java.lang.String类型的值<br无法转换为JSONObject

I know I have seen all similar questions on SO. I tried to solve this error but I failed. I tried almost everything but does not get solution.

My code is as follows:-

public class Tab2 extends Fragment {

private static String TAG = Tab2.class.getSimpleName();
private EditText editText1,editText2,editText3;
private Button button;
private String name,email,password;
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutPassword;
private ProgressDialog pDialog;
private SessionManager session;
private database db;
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.tab2,container,false);

    pDialog = new ProgressDialog(getActivity());
    pDialog.setCancelable(false);

    // Session manager
    session = new SessionManager(getActivity());

    // SQLite database handler
    db = new database(getActivity());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(getActivity(),MainActivity.class);
        startActivity(intent);
    }


    editText1 = (EditText)view.findViewById(R.id.name);
    editText2 = (EditText)view.findViewById(R.id.email);
    editText3 = (EditText)view.findViewById(R.id.password);
    inputLayoutEmail = (TextInputLayout)view. findViewById(R.id.view1);
    inputLayoutPassword = (TextInputLayout)view. findViewById(R.id.view2);
    inputLayoutName = (TextInputLayout)view. findViewById(R.id.view3);

    button = (Button)view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view1) {

            name = editText1.getText().toString().trim();
            email = editText2.getText().toString().trim();
            password = editText3.getText().toString().trim();

            if (!validateName() || !validateEmail() || !validatePassword() ) {
                Log.d(TAG, "Successfull");
                return;
            }
               try {
                   new Thread(new Runnable() {
                       @Override
                       public void run() {
                           registerUser(name, email, password);
                       }
                   }).start();
               }catch (NullPointerException e){
                   e.printStackTrace();
               }


            Toast.makeText(getActivity(), "Account Created Successfully!", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getActivity(), MainActivity.class);
            startActivity(i);
        }



    });



    return view;
}
public boolean validateName(){

    if(name.isEmpty() ) {
        inputLayoutName.setError(getString(R.string.error_name1));
        return false;
    }
    else if(name.length()<3){
        inputLayoutName.setError(getString(R.string.error_name2));
        return false;
    }
    else
        inputLayoutName.setErrorEnabled(false);
    return true;
}
public boolean validateEmail(){

    if(email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
        inputLayoutEmail.setError(getString(R.string.error_email));
        return false;
    }
    else
        inputLayoutEmail.setErrorEnabled(false);
    return true;
}
public boolean validatePassword(){

    if(password.isEmpty() ){
        inputLayoutPassword.setError(getString(R.string.error_password1));
        return false;
    }
    else if(password.length()<4){
        inputLayoutPassword.setError(getString(R.string.error_password2));
        return false;
    }
    else
        inputLayoutPassword.setErrorEnabled(false);
    return true;
}


public void registerUser(final String name, final String email, final String password){

    String req = "req_request";
    pDialog.setMessage("Registering ...");
    showDialog();

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    StringRequest strReq = new StringRequest(Request.Method.POST, appConfig.url_sign, new Response.Listener<String>(){

        @Override
        public void onResponse(String response) {
          try {


               JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                Log.d(TAG,name + " " + email + " " + password );
                if (!error) {
                    String uid = jObj.getString("uid");
                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email= user.getString("email");
                    String created_at = user.getString("created_at");
                    db.addUser(name, email, uid, created_at);

                  Toast.makeText(getActivity(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
                    // Launch login activity
                    Intent i = new Intent(
                            getActivity(),
                            Login.class);
                    startActivity(i);


                }
                else {
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getActivity(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }




            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            NetworkResponse networkResponse = error.networkResponse;
            if (networkResponse != null) {
                Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode);
            }
            if (error instanceof TimeoutError) {
                Log.e("Volley", "TimeoutError");
            }else if(error instanceof NoConnectionError){
                Log.e("Volley", "NoConnectionError");
            } else if (error instanceof AuthFailureError) {

                Log.e("Volley", "AuthFailureError");
            } else if (error instanceof ServerError) {
                Log.e("Volley", "ServerError");
            } else if (error instanceof NetworkError) {
                Log.e("Volley", "NetworkError");
            } else if (error instanceof ParseError) {
                Log.e("Volley", "ParseError");
            }
            //Log.e(TAG, "Registration Error: " + error.getMessage());
         //   Toast.makeText(getActivity(),
           //         error.getMessage(), Toast.LENGTH_LONG).show();
          //  hideDialog();

        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    int socketTimeout = 10000;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    strReq.setRetryPolicy(policy);

    requestQueue.add(strReq);
}
private void showDialog() {

    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}
}

This is my php file

<?php
$response = array();
if (isset($_POST['name']) && isset($_POST['email']) && isset   ($_POST['password'] ))   
{  
  $name = $_POST['name'];
  $email = $_POST['email'];
  $password = $_POST['password'];


require_once __DIR__ . '/db_connection.php';
$db = new DB_CONNECT();
$result = mysql_query("Insert into words(name,email,password) values('$name','$email','$password')");

if ($result)
{
    $response["success"] = 1;
    $response["message"] = "Registration successfully.";
    echo json_encode($response);
}
else
{
  $response["success"] = 0;
  $response["message"] = "Oops! An error occurred.";
  echo json_encode($response);  
}
}

 else 
 {
   $response["success"] = 0;
   $response["message"] = "Required field(s) is missing";
   echo json_encode($response);
  } 
 ?>

My JSON response is:-

{"success":0,"message":"Required field(s) is missing"}

Can you identify the error please tell me.

2个回答



@Kartikeya Garg,您可能会从API获得HTML响应或错误,并且您正在尝试将这些响应转换为JSON对象, 响应没有有效的json。</ p>

你可以在postman上试试,你可以在chrome上安装它。 这样您就可以直接从API获得响应。 你实际上得到了什么</ p>
</ div>

展开原文

原文

@Kartikeya Garg, you may be getting html response or error from API, and you are trying to convert these response into JSON object,your response doesn't have a valid json.

you can try it on postman,you can install it on chrome. so that you can get directly response from API. what you are getting in actually




您可以通过编程打印您的回复,我相信您的回复与您发布的回复不一样</ p>
</ blockquote>
</ div>

展开原文

原文

You can print your response through programming, i am sure your response is not same as what ever you post

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
错误解析数据:org.json.JSONException:值<!DOCTYPE类型java.lang.String无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>The URL that I use to get JSON from redirects the URL to recaptcha and gives the following error: "data org.json.JSONException: Value <code>&lt;!DOCTYPE of type java.lang.String cannot be converted to JSONObject</code>" </p> <p>Following is the activity and the code has the url i am trying to get JSON from but instead i get redirected to recaptcha:</p> <pre><code>protected Void doInBackground(Void... params) { // Create an array arraylist = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); // Retrieve JSON Objects from the given URL address //URL jsonobject = JSONfunctions .getJSONfromURL("http://laboneinside.com/android/diag_conn.php"); try { // Locate the array name in JSON jsonarray = jsonobject.getJSONArray("result"); Log.i("JSON TAG", jsonobject.toString()); for (int i = 0; i &lt; jsonarray.length(); i++) { HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); jsonobject = jsonarray.getJSONObject(i); // Retrive JSON Objects map.put("nameDiag", jsonobject.getString("name")); map.put("srcDiag", jsonobject.getString("src")); map.put("linkDiag", jsonobject.getString("link")); // Set the JSON Objects into the array arraylist.add(map); } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return null; } </code></pre> <p>JSONFUNCTION:</p> <pre><code>public class JSONfunctions { public static JSONObject getJSONfromURL(String url) { InputStream is = null; String result = ""; JSONObject jArray = null; // Download JSON data from URL 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 + " "); } is.close(); result = sb.toString(); Log.i("JSON Parser", result); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { jArray = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return jArray; } } </code></pre> <p>Following is the logcat:</p> <pre><code>I/JSON Parser: &lt;!DOCTYPE html&gt; &lt;!--[if lt IE 7]&gt; &lt;html class="no-js ie6 oldie" lang="en-US"&gt; &lt;![endif]--&gt; &lt;!--[if IE 7]&gt; &lt;html class="no-js ie7 oldie" lang="en-US"&gt; &lt;![endif]--&gt; &lt;!--[if IE 8]&gt; &lt;html class="no-js ie8 oldie" lang="en-US"&gt; &lt;![endif]--&gt; &lt;!--[if gt IE 8]&gt;&lt;!--&gt; &lt;html class="no-js" lang="en-US"&gt; &lt;!--&lt;![endif]--&gt; &lt;head&gt; &lt;title&gt;Attention Required! | CloudFlare&lt;/title&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" /&gt; &lt;meta name="robots" content="noindex, nofollow" /&gt; &lt;meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1" /&gt; &lt;link rel="stylesheet" id="cf_styles-css" href="/cdn-cgi/styles/cf.errors.css" type="text/css" media="screen,projection" /&gt; &lt;!--[if lt IE 9]&gt;&lt;link rel="stylesheet" id='cf_styles-ie-css' href="/cdn-cgi/styles/cf.errors.ie.css" type="text/css" media="screen,projection" /&gt;&lt;![endif]--&gt; &lt;style type="text/css"&gt;body{margin:0;padding:0}&lt;/style&gt; &lt;!--[if lte IE 9]&gt;&lt;script type="text/javascript" src="/cdn-cgi/scripts/jquery.min.js"&gt;&lt;/script&gt;&lt;![endif]--&gt; &lt;!--[if gte IE 10]&gt;&lt;!--&gt;&lt;script type="text/javascript" src="/cdn-cgi/scripts/zepto.min.js"&gt;&lt;/script&gt;&lt;!--&lt;![endif]--&gt; &lt;script type="text/javascript" src="/cdn-cgi/scripts/cf.common.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="cf-wrapper"&gt; &lt;div class="cf-alert cf-alert-error cf-cookie-error" id="cookie-alert" data-translate="enable_cookies"&gt;Please enable cookies.&lt;/div&gt; &lt;div id="cf-error-details" class="cf-error-details-wrapper"&gt; &lt;div class="cf-wrapper cf-header cf-error-overview"&gt; &lt;h1 data-translate="challenge_headline"&gt;One more step&lt;/h1&gt; &lt;h2 class="cf-subheadline"&gt;&lt;span data-translate="complete_sec_check"&gt;Please complete the security check to access&lt;/span&gt; laboneinside.com&lt;/h2&gt; &lt;/div&gt;&lt;!-- /.header --&gt; &lt;div class="cf-section cf-highlight cf-captcha-container"&gt; &lt;div class="cf-wrapper"&gt; &lt;div class="cf-columns two"&gt; &lt;div class="cf-column"&gt; &lt;div class="cf-highlight-inverse cf-form-stacked"&gt; &lt;form class="challenge-form" id="challenge-form" action="/cdn-cgi/l/chk_captcha" method="get"&gt; &lt;script type="text/javascript" src="/cdn-cgi/scripts/cf.challenge.js" data-type="normal" data-ray="308cf17ac17329be" async data-sitekey="6LfOYgoTAAAAAInWDVTLSc8Yibqp-c9DaLimzNGM" data-stoken="kvvwvLSUth2MQ7fsfXFwr9TjwkJ6pEiMAfiAhb7x9fVk7yqCvGMh-myXoKQuhQt_4MjgZHunito0fikCnHS-DFoymBKWm5gb3lnlB4dceb0"&gt;&lt;/script&gt; &lt;div class="g-recaptcha"&gt;&lt;/div&gt; &lt;noscript id="cf-captcha-bookmark" class="cf-captcha-info"&gt; &lt;div&gt;&lt;div style="width: 302px"&gt; &lt;div&gt; &lt;iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfOYgoTAAAAAInWDVTLSc8Yibqp-c9DaLimzNGM&amp;stoken=kvvwvLSUth2MQ7fsfXFwr9TjwkJ6pEiMAfiAhb7x9fVk7yqCvGMh-myXoKQuhQt_4MjgZHunito0fikCnHS-DFoymBKWm5gb3lnlB4dceb0" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;div style="width: 300px; border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px;"&gt; &lt;textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid #c1c1c1; margin: 10px 25px; padding: 0px; resize: none;"&gt;&lt;/textarea&gt; &lt;input type="submit" value="Submit"&gt;&lt;/input&gt; &lt;/div&gt; &lt;/div&gt;&lt;/div&gt; &lt;/noscript&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cf-column"&gt; &lt;div class="cf-screenshot-container"&gt; &lt;span class="cf-no-screenshot"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- /.columns --&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- /.captcha-container --&gt; &lt;div class="cf-section cf-wrapper"&gt; &lt;div class="cf-columns two"&gt; &lt;div class="cf-column"&gt; &lt;h2 data-translate="why_captcha_headline"&gt;Why do I have to complete a CAP 11-28 04:55:15.976 30265-30325/com.example.predator.labone E/log_tag: Error parsing data org.json.JSONException: Value &lt;!DOCTYPE of type java.lang.String cannot be converted to JSONObject </code></pre> <p>How do i stop it from redirecting so that i can get to the page that has the JSON data?</p> </div>

org.json.JSONException:类型java.lang.String的值记录无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>I am making an activity to update user profile in android studio using volley,php and mysql.But whenever i am clicking the save button to save all the info nothing is happening</p> <p>android activity</p> <pre><code>public class ProfileInfoSignup extends AppCompatActivity { ImageView dp; ProgressBar pb; EditText save_name,save_bio; Button b1; RequestQueue requestQueue; boolean IMAGE_STATUS = false; Bitmap profilePicture; String name,bio,profile; String user_email; private static String SIGNUP_URL = "http://10.0.2.2/app2/profile_ru.php?apicall=updateuser"; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.profile_info_signup); dp=findViewById(R.id.circleView); save_name=findViewById(R.id.edit_name); save_bio=findViewById(R.id.edit_bio); b1=findViewById(R.id.btn_start); pb=findViewById(R.id.progress_bar3); sp=getApplicationContext().getSharedPreferences("myPref", Context.MODE_PRIVATE); if(sp.contains("user_email")) { user_email = sp.getString("user_email", "Data not found"); }else{ Toast.makeText(getApplicationContext(), "no email found", Toast.LENGTH_SHORT).show(); } //creating request queue requestQueue = Volley.newRequestQueue(this); //Adding onClickListener to the ImageView to select the profile Picture dp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, 1000); //result will be available in onActivityResult which is overridden } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name = save_name.getText().toString(); bio = save_bio.getText().toString(); if ( //perform validation by calling all the validate functions inside the IF condition validateName(name) &amp;&amp; validateBio(bio)&amp;&amp; validateProfile() ) { //Validation Success convertBitmapToString(profilePicture); saveProfileInfo(SIGNUP_URL,name,bio,user_email); } } }); } private void saveProfileInfo(String signupUrl, final String getuserName, final String getuserBio, final String getuserEmail) { RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); StringRequest stringRequest = new StringRequest(Request.Method.POST, signupUrl, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { try { Toast.makeText(getApplicationContext(), "making new json object and going to another activity", Toast.LENGTH_LONG).show(); JSONObject jsonObject = new JSONObject(response); if (jsonObject.getBoolean("success")) { Toast.makeText(getApplicationContext(), "Connected to json", Toast.LENGTH_LONG).show(); Intent intent = new Intent(ProfileInfoSignup.this, Activity2.class); startActivity(intent); } else Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show(); }catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { @Override protected Map&lt;String, String&gt; getParams() { Map&lt;String, String&gt; param = new HashMap&lt;String, String&gt;(); param.put("name", getuserName); param.put("bio", getuserBio); param.put("email", getuserEmail); return param; } }; int socketTimeout = 30000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); stringRequest.setRetryPolicy(policy); requestQueue.add(stringRequest); } private void convertBitmapToString(Bitmap profilePicture) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); profilePicture.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] array = byteArrayOutputStream.toByteArray(); profile = Base64.encodeToString(array, Base64.DEFAULT); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1000 &amp;&amp; resultCode == Activity.RESULT_OK &amp;&amp; data != null) { //Image Successfully Selected Toast.makeText(getApplicationContext(), "Image successfully selected", Toast.LENGTH_SHORT).show(); try { //parsing the Intent data and displaying it in the imageview Uri imageUri = data.getData();//Geting uri of the data InputStream imageStream = getContentResolver().openInputStream(imageUri);//creating an imputstrea profilePicture = BitmapFactory.decodeStream(imageStream);//decoding the input stream to bitmap dp.setImageBitmap(profilePicture); IMAGE_STATUS = true;//setting the flag } catch (FileNotFoundException e) { e.printStackTrace(); } } } private boolean validateName(String string) { if (string.equals("")) { save_name.setError("Enter Your Name"); return false; } else if (string.length() &gt; 50) { save_name.setError("Maximum 50 Characters"); return false; } return true; } private boolean validateBio(String string) { if (string.equals("")) { save_bio.setError("Enter Your Email Address"); return false; } else if (string.length() &gt; 300) { save_name.setError("Maximum 300 Characters"); return false; } return true; } private boolean validateProfile() { if (!IMAGE_STATUS) Toast.makeText(this, "Select A Profile Picture", Toast.LENGTH_SHORT).show(); return IMAGE_STATUS; } } </code></pre> <p>Every time i run the app and click the save button this comes up in log</p> <pre><code> 08-04 15:05:23.058 4409-4431/com.example.user.myapplication D/EGL_emulation: eglMakeCurrent: 0xb2eb8860: ver 2 0 (tinfo 0xb2e8b280) 08-04 15:05:23.180 1384-4481/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 1865147 , only wrote 1864800 08-04 15:05:23.848 4409-4409/com.example.user.myapplication W/System.err: org.json.JSONException: Value Record of type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:111) at org.json.JSONObject.&lt;init&gt;(JSONObject.java:163) at org.json.JSONObject.&lt;init&gt;(JSONObject.java:176) 08-04 15:05:23.849 4409-4409/com.example.user.myapplication W/System.err: at com.example.user.myapplication.Login.ProfileInfoSignup$3.onResponse(ProfileInfoSignup.java:114) at com.example.user.myapplication.Login.ProfileInfoSignup$3.onResponse(ProfileInfoSignup.java:109) at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:67) at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) 08-04 15:05:23.850 4409-4409/com.example.user.myapplication W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) 08-04 15:05:23.851 4409-4409/com.example.user.myapplication W/System.err: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) </code></pre> <p>php</p> <pre><code> @$name= $_POST['name']; @$bio=$_POST['bio']; @$email=$_POST['email']; @$id=$_POST['id']; if(!empty($_POST['name']) &amp;&amp; !empty($_POST['bio']) &amp;&amp; !empty($_POST['email']) ) { $result="SELECT id FROM accounts where email='$email'"; $row = mysqli_fetch_assoc(mysqli_query($con,$result)); $id=$row['id']; $Sql_Query =mysqli_prepare($con,"UPDATE profile SET name= ?, bio = ? WHERE id = ?"); /* bind parameters for markers */ mysqli_stmt_bind_param($Sql_Query, "ssi", $name,$bio,$id); /* execute query */ $sql= mysqli_stmt_execute($Sql_Query); if($sql){ echo 'Record Updated Successfully'; } else{ echo 'Something went wrong, whether id is not present or something else'.mysqli_error($con); } }else { echo 'missing parameters'; } </code></pre> <p>I am not to figure out whether the problem is in php or android code. Any help will be deeply appreciated</p> </div>

Android登录活动 - 解析数据时出错org.json.JSONException:类型java.lang.String的值无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>Im making a log in activity to connect to a MySQL database. For some reason I keep getting this</p> <pre><code>08-13 08:45:59.739 1144-1159/com.amity.paul.amity E/JSON Parser﹕ Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject 08-13 08:45:59.739 1144-1159/com.amity.paul.amity W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xb3ad0ba8) 08-13 08:46:02.409 1144-1159/com.amity.paul.amity E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1 Process: com.amity.paul.amity, PID: 1144 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at com.amity.paul.amity.login$AttemptLogin.doInBackground(login.java:129) at com.amity.paul.amity.login$AttemptLogin.doInBackground(login.java:93) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)             at java.lang.Thread.run(Thread.java:841) </code></pre> <p>I have no idea what is wrong. Below are the related files: login.java</p> <pre><code>package com.amity.paul.amity; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import library.JSONParser; public class login extends Activity implements OnClickListener{ private EditText user, pass; private Button mSubmit, mRegister; // Progress Dialog private ProgressDialog pDialog; // JSON parser class JSONParser jsonParser = new JSONParser(); //php login script location: //localhost : //testing on your device //put your local ip instead, on windows, run CMD &gt; ipconfig //or in mac's terminal type ifconfig and look for the ip under en0 or en1 // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php"; //testing on Emulator: private static final String LOGIN_URL = "http://192.168.2.157/amity/login.php"; //testing from a real server: //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php"; //JSON element ids from repsonse of php script: private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.login); //setup input fields user = (EditText)findViewById(R.id.username); pass = (EditText)findViewById(R.id.password); //setup buttons mSubmit = (Button)findViewById(R.id.login); mRegister = (Button)findViewById(R.id.register); //register listeners mSubmit.setOnClickListener(this); mRegister.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.login: new AttemptLogin().execute(); break; case R.id.register: Intent i = new Intent(this, register.class); startActivity(i); break; default: break; } } class AttemptLogin extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ boolean failure = false; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(login.this); pDialog.setMessage("Attempting login..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub // Check for success tag int success; String username = user.getText().toString(); String password = pass.getText().toString(); try { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); Log.d("request!", "starting"); // getting product details by making HTTP request JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params); // check your log for json response Log.d("Login attempt", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("Login Successful!", json.toString()); //save user data SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(login.this); SharedPreferences.Editor edit = sp.edit(); edit.putString("username",username); edit.commit(); Intent i = new Intent(login.this, home.class); finish(); startActivity(i); 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(login.this, file_url, Toast.LENGTH_LONG).show(); } } } } </code></pre> <p>JSONParser:</p> <pre><code>package library; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(final String url) { // Making HTTP request try { // Construct the client and the HTTP request. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // Execute the POST request and store the response locally. HttpResponse httpResponse = httpClient.execute(httpPost); // Extract data from the response. HttpEntity httpEntity = httpResponse.getEntity(); // Open an inputStream with the data content. is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { // Create a BufferedReader to parse through the inputStream. BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); // Declare a string builder to help with the parsing. StringBuilder sb = new StringBuilder(); // Declare a string to store the JSON object data in string form. String line = null; // Build the string until null. while ((line = reader.readLine()) != null) { sb.append(line + " "); } // Close the input stream. is.close(); // Convert the string builder data to an actual string. json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // Try to 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 the JSON Object. return jObj; } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request 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 + " "); } 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; } } </code></pre> <p>login.php</p> <pre><code>&lt;?php //load and connect to MySQL database stuff require("config.inc.php"); if (!empty($_POST)) { //gets user's info based off of a username. $query = " SELECT id, username, password FROM users WHERE username = :username "; $query_params = array( ':username' =&gt; $_POST['username'] ); try { $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch (PDOException $ex) { // For testing, you could use a die and message. //die("Failed to run query: " . $ex-&gt;getMessage()); //or just use this use this one to product JSON data: $response["success"] = 0; $response["message"] = "Database Error1. Please Try Again!"; die(json_encode($response)); } //This will be the variable to determine whether or not the user's information is correct. //we initialize it as false. $validated_info = false; //fetching all the rows from the query $row = $stmt-&gt;fetch(); if ($row) { //if we encrypted the password, we would unencrypt it here, but in our case we just //compare the two passwords if ($_POST['password'] === $row['password']) { $login_ok = true; } } // If the user logged in successfully, then we send them to the private members-only page // Otherwise, we display a login failed message and show the login form again if ($login_ok) { $response["success"] = 1; $response["message"] = "Login successful!"; die(json_encode($response)); } else { $response["success"] = 0; $response["message"] = "Invalid Credentials!"; die(json_encode($response)); } } else { ?&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;form action="login.php" method="post"&gt; Username:&lt;br /&gt; &lt;input type="text" name="username" placeholder="username" /&gt; &lt;br /&gt;&lt;br /&gt; Password:&lt;br /&gt; &lt;input type="password" name="password" placeholder="password" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;input type="submit" value="Login" /&gt; &lt;/form&gt; &lt;a href="register.php"&gt;Register&lt;/a&gt; &lt;?php } ?&gt; </code></pre> <p>I am extremely new to mobile development so please make it easy to understand. Cheers!</p> </div>

org.json.JSONException:java.lang.String类型的值<br无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>Good morning I've searched a lotin android and json forums But I didn't find any solution Can you help me please!"ndroidhive.loginandregistration W/System.err﹕ org.json.JSONException: Value </p><p>RegisterActivity.java</p> <pre><code> import info.androidhive.loginandregistration.app.AppConfig; import info.androidhive.loginandregistration.app.AppController; import info.androidhive.loginandregistration.helper.SQLiteHandler; import info.androidhive.loginandregistration.helper.SessionManager; public class RegisterActivity extends Activity { private static final String TAG = RegisterActivity.class.getSimpleName(); private Button btnRegister; private Button btnLinkToLogin; private EditText inputFullName; private EditText inputEmail; private EditText inputPassword; private ProgressDialog pDialog; private SessionManager session; private SQLiteHandler db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); inputFullName = (EditText) findViewById(R.id.name); inputEmail = (EditText) findViewById(R.id.email); inputPassword = (EditText) findViewById(R.id.password); btnRegister = (Button) findViewById(R.id.btnRegister); btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); // Progress dialog pDialog = new ProgressDialog(this); pDialog.setCancelable(false); // Session manager session = new SessionManager(getApplicationContext()); // SQLite database handler db = new SQLiteHandler(getApplicationContext()); // Check if user is already logged in or not if (session.isLoggedIn()) { // User is already logged in. Take him to main activity Intent intent = new Intent(RegisterActivity.this, MainActivity.class); startActivity(intent); finish(); } // Register Button Click event btnRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputFullName.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); if (!name.isEmpty() &amp;&amp; !email.isEmpty() &amp;&amp; !password.isEmpty()) { registerUser(name, email, password); } else { Toast.makeText(getApplicationContext(), "Please enter your details!", Toast.LENGTH_LONG) .show(); } } }); // Link to Login Screen btnLinkToLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); finish(); } }); } private void registerUser(final String name, final String email, final String password) { // Tag used to cancel the request String tag_string_req = "req_register"; pDialog.setMessage("Registering ..."); showDialog(); StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { Log.d(TAG, "Register Response: " + response.toString()); hideDialog(); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { // User successfully stored in MySQL // Now store the user in sqlite String uid = jObj.getString("uid"); JSONObject user = jObj.getJSONObject("user"); String name = user.getString("name"); String email = user.getString("email"); String created_at = user .getString("created_at"); // Inserting row in users table db.addUser(name, email, uid, created_at); // Launch login activity Intent intent = new Intent( RegisterActivity.this, LoginActivity.class); startActivity(intent); finish(); } else { // Error occurred in registration. Get the error // message String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Registration Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map&lt;String, String&gt; getParams() { // Posting params to register url Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); params.put("tag", "register"); params.put("name", name); params.put("email", email); params.put("password", password); return params; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } } </code></pre> <p>AppConfig.java</p> <pre><code> package info.androidhive.loginandregistration.app; public class AppConfig { // Server user login url public static String URL_LOGIN = "http://192.168.1.5/android_login_api/"; // Server user register url public static String URL_REGISTER = "http://192.168.1.5/android_login_api/"; } </code></pre> <p>myphpfile: index.php</p> <pre><code> &lt;?php if (isset($_POST['tag']) &amp;&amp; $_POST['tag'] != '') { // get tag $tag = $_POST['tag']; // include db handler require_once 'include/DB_Functions.php'; $db = new DB_Functions(); // response Array $response = array("tag" =&gt; $tag, "error" =&gt; FALSE); // check for tag type if ($tag == 'login') { // Request type is check Login $email = $_POST['email']; $password = $_POST['password']; // check for user $user = $db-&gt;getUserByEmailAndPassword($email, $password); if ($user != false) { // user found $response["error"] = FALSE; $response["uid"] = $user["unique_id"]; $response["user"]["name"] = $user["name"]; $response["user"]["email"] = $user["email"]; $response["user"]["created_at"] = $user["created_at"]; $response["user"]["updated_at"] = $user["updated_at"]; echo json_encode($response); } else { // user not found // echo json with error = 1 $response["error"] = TRUE; $response["error_msg"] = "Incorrect email or password!"; echo json_encode($response); } } else if ($tag == 'register') { // Request type is Register new user $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; // check if user is already existed if ($db-&gt;isUserExisted($email)) { // user is already existed - error response $response["error"] = TRUE; $response["error_msg"] = "User already existed"; echo json_encode($response); } else { // store user $user = $db-&gt;storeUser($name, $email, $password); if ($user) { // user stored successfully $response["error"] = FALSE; $response["uid"] = $user["unique_id"]; $response["user"]["name"] = $user["name"]; $response["user"]["email"] = $user["email"]; $response["user"]["created_at"] = $user["created_at"]; $response["user"]["updated_at"] = $user["updated_at"]; echo json_encode($response); } else { // user failed to store $response["error"] = TRUE; $response["error_msg"] = "Error occured in Registartion"; echo json_encode($response); } } } else { // user failed to store $response["error"] = TRUE; $response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'"; echo json_encode($response); } } else { $response["error"] = TRUE; $response["error_msg"] = "Required parameter 'tag' is missing!"; echo json_encode($response); } ?&gt; </code></pre> <p>activity_register.xml</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/bg_register" android:gravity="center" android:orientation="vertical" android:padding="10dp" &gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical" android:paddingLeft="20dp" android:paddingRight="20dp" &gt; &lt;EditText android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:background="@color/input_register_bg" android:hint="@string/hint_name" android:padding="10dp" android:singleLine="true" android:inputType="textCapWords" android:textColor="@color/input_register" android:textColorHint="@color/input_register_hint" /&gt; &lt;EditText android:id="@+id/email" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:background="@color/input_register_bg" android:hint="@string/hint_email" android:inputType="textEmailAddress" android:padding="10dp" android:singleLine="true" android:textColor="@color/input_register" android:textColorHint="@color/input_register_hint" /&gt; &lt;EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:background="@color/input_register_bg" android:hint="@string/hint_password" android:inputType="textPassword" android:padding="10dp" android:singleLine="true" android:textColor="@color/input_register" android:textColorHint="@color/input_register_hint" /&gt; &lt;!-- Login Button --&gt; &lt;Button android:id="@+id/btnRegister" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dip" android:background="#ea4c88" android:text="@string/btn_register" android:textColor="@color/white" /&gt; &lt;!-- Link to Login Screen --&gt; &lt;Button android:id="@+id/btnLinkToLoginScreen" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="40dip" android:background="@null" android:text="@string/btn_link_to_login" android:textAllCaps="false" android:textColor="@color/white" android:textSize="15dp" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> </div>

Error parsing data org.json.JSONException:

Android环境是wampserver+eclipse,在网上找了个demo,想实现初步的注册和登录功能.但是测试的时候报了Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject,卡住了。求解... logcat打印的信息: ``` 11-17 15:40:04.666: D/Log_Debug(14690): this json<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> 11-17 15:40:04.666: D/Log_Debug(14690): <HTML><HEAD><TITLE>Bad Request</TITLE> 11-17 15:40:04.666: D/Log_Debug(14690): <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD> 11-17 15:40:04.666: D/Log_Debug(14690): <BODY><h2>Bad Request - Invalid Header</h2> 11-17 15:40:04.666: D/Log_Debug(14690): <hr><p>HTTP Error 400. The request has an invalid header name.</p> 11-17 15:40:04.666: D/Log_Debug(14690): </BODY></HTML> 11-17 15:40:04.669: E/JSON Parser(14690): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject 11-17 15:40:04.671: W/System.err(14690): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference

报错:net.sf.json.JSONException

显示报错: ![图片说明](https://img-ask.csdn.net/upload/201705/02/1493697329_940817.png) 源代码: <% /*获取所有业务 */ String url="#url"; String param="#URL"; //地区编号 String html=""; //String temp=""; try{ String result=sendGet(url,param); result=URLDecoder.decode(result); //解析json数据 JSONObject jsonObject=JSONObject.fromObject(result); String info=jsonObject.getString("info"); JSONArray infoArray=JSONArray.fromObject(info); //拼接下面html数据 for(int i=0;i<infoArray.size();i++){ JSONObject oneObject=infoArray.getJSONObject(i); //temp=oneObject.getString("ACCEPT_USER_NAME"); //没有完成的业务就没有完成时间,需要先判断,否则报错: String finish_time=""; if(oneObject.containsKey("FINISH_TIME")){ finish_time="<script type='text/javascript'>showTime('"+oneObject.getString("FINISH_TIME")+"');</script>"; }else{ finish_time="处理中"; } String time_limit=""; if(oneObject.containsKey("TIME_LIMIT")){ time_limit="<script type='text/javascript'>showTime('"+oneObject.getString("TIME_LIMIT")+"');</script>"; }else{ time_limit="-"; } html+="<li><span class='span1'>"+oneObject.getString("RECEIVE_NUMBER")+"</span><span class='span2'><a title='"+oneObject.getString("APPLY_SUBJECT")+"'>"+oneObject.getString("APPLY_SUBJECT")+"</a></span><span class='span4'><a title='"+oneObject.getString("ORG_NAME")+"'>"+oneObject.getString("ORG_NAME")+"</a></span><span class='span4'>"+time_limit+"</span><span class='span4'>"+finish_time+"</span><span class='span3 yellow'>"+oneObject.getString("CURRENT_NODE_NAME")+"</span></li>"; } //out.print(html); }catch(Exception e){ out.print(e.toString()); } %> 麻烦高手看看是啥情况!

org.json.JSONException值类型java.lang.String无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>I'm trying to make a login/register app and when i run the code i get this error and my code doesn't work. What am i doing wrong? how can i solve this? If additional code is needed i can provide. Also if this question has a response already can you guide me to that response? I'm trying to find a solution to this problem since 2 days ago and can't seem to find what the problem is. I'm quite new to coding so any help is welcomed.</p> <p><strong>db_connect.php</strong></p> <pre><code>&lt;?php define('DB_USER', "root"); // db user define('DB_PASSWORD', ""); // db password (mention your db password here) define('DB_DATABASE', "member"); // database name define('DB_SERVER', "localhost"); // db server $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE); // Check connection if(mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?&gt; </code></pre> <p><strong>Function.php</strong></p> <pre><code>&lt;?php $random_salt_length = 32; /** * Queries the database and checks whether the user already exists * * @param $username * * @return */ function userExists($username){ $query = "SELECT username FROM member WHERE username = ?"; global $con; if($stmt = $con-&gt;prepare($query)){ $stmt-&gt;bind_param("s",$username); $stmt-&gt;execute(); $stmt-&gt;store_result(); $stmt-&gt;fetch(); if($stmt-&gt;num_rows == 1){ $stmt-&gt;close(); return true; } $stmt-&gt;close(); } return false; } function concatPasswordWithSalt($password,$salt){ global $random_salt_length; if($random_salt_length % 2 == 0){ $mid = $random_salt_length / 2; } else{ $mid = ($random_salt_length - 1) / 2; } return substr($salt,0,$mid - 1).$password.substr($salt,$mid,$random_salt_length - 1); } ?&gt; </code></pre> <p><strong>Login.php</strong></p> <pre><code>&lt;?php $response = array(); include 'db/db_connect.php'; include 'functions.php'; //Get the input request parameters $inputJSON = file_get_contents('php://input'); $input = json_decode($inputJSON); //convert JSON into array //Check for Mandatory parameters if(isset($input-&gt;username) &amp;&amp; isset($input-&gt;password)){ $username = $input-&gt;username; $password = $input-&gt;password; $query = "SELECT full_name,password_hash, salt FROM member WHERE username = ?"; if($stmt = $con-&gt;prepare($query)){ $stmt-&gt;bind_param("s",$username); $stmt-&gt;execute(); $stmt-&gt;bind_result($fullName,$passwordHashDB,$salt); if($stmt-&gt;fetch()){ //Validate the password if(password_verify(concatPasswordWithSalt($password,$salt),$passwordHashDB)){ $response["status"] = 0; $response["message"] = "Login successful"; $response["full_name"] = $fullName; } else{ $response["status"] = 1; $response["message"] = "Invalid username and password combination"; } } else{ $response["status"] = 1; $response["message"] = "Invalid username and password combination"; } $stmt-&gt;close(); } } else{ $response["status"] = 2; $response["message"] = "Missing mandatory parameters"; } //Display the JSON response echo json_encode($response); ?&gt; </code></pre> <p><strong>Register.php</strong></p> <pre class="lang-php prettyprint-override"><code>&lt;?php $response = array(); include 'db/db_connect.php'; include 'Functions.php'; //Get the input request parameters $inputJSON = file_get_contents('php://input'); $input = json_decode($inputJSON, TRUE); //convert JSON into array //Check for Mandatory parameters if(isset($input['username']) &amp;&amp; isset($input['password']) &amp;&amp; isset($input['full_name'])){ $username = $input['username']; $password = $input['password']; $fullName = $input['full_name']; //Check if user already exist if(!userExists($username)){ //Get a unique Salt $salt = getSalt(); //Generate a unique password Hash $passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT); //Query to register new user $insertQuery = "INSERT INTO member(username, full_name, password_hash, salt) VALUES (?,?,?,?)"; if($stmt = $con-&gt;prepare($insertQuery)){ $stmt-&gt;bind_param("ssss",$username,$fullName,$passwordHash,$salt); $stmt-&gt;execute(); $response["status"] = 0; $response["message"] = "User created"; $stmt-&gt;close(); } } else{ $response["status"] = 1; $response["message"] = "User exists"; } } else{ $response["status"] = 2; $response["message"] = "Missing mandatory parameters"; } echo json_encode($response); ?&gt; </code></pre> <p>RegisterActivity.java</p> <pre class="lang-java prettyprint-override"><code>package com.example.activitymanagement; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONException; import org.json.JSONObject; public class RegisterActivity extends AppCompatActivity { private static final String KEY_STATUS = "status"; private static final String KEY_MESSAGE = "message"; private static final String KEY_FULL_NAME = "full_name"; private static final String KEY_USERNAME = "username"; private static final String KEY_PASSWORD = "password"; private static final String KEY_EMPTY = ""; private EditText etUsername; private EditText etPassword; private EditText etConfirmPassword; private EditText etFullName; private String username; private String password; private String confirmPassword; private String fullName; private ProgressDialog pDialog; private String register_url = "http://10.0.2.2/member/register.php"; private SessionHandler session; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); session = new SessionHandler(getApplicationContext()); setContentView(R.layout.activity_register); etUsername = findViewById(R.id.etUsername); etPassword = findViewById(R.id.etPassword); etConfirmPassword = findViewById(R.id.etConfirmPassword); etFullName = findViewById(R.id.etFullName); Button login = findViewById(R.id.btnRegisterLogin); Button register = findViewById(R.id.btnRegister); //Launch Login screen when Login Button is clicked login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(i); finish(); } }); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Retrieve the data entered in the edit texts username = etUsername.getText().toString().toLowerCase().trim(); password = etPassword.getText().toString().trim(); confirmPassword = etConfirmPassword.getText().toString().trim(); fullName = etFullName.getText().toString().trim(); if (validateInputs()) { registerUser(); } } }); } /** * Display Progress bar while registering */ private void displayLoader() { pDialog = new ProgressDialog(RegisterActivity.this); pDialog.setMessage("Signing Up.. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * Launch Dashboard Activity on Successful Sign Up */ private void loadDashboard() { Intent i = new Intent(getApplicationContext(), DashboardActivity.class); startActivity(i); finish(); } private void registerUser() { displayLoader(); JSONObject request = new JSONObject(); try { //Populate the request parameters request.put(KEY_USERNAME, username); request.put(KEY_PASSWORD, password); request.put(KEY_FULL_NAME, fullName); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest jsArrayRequest = new JsonObjectRequest (Request.Method.POST, register_url, request, new Response.Listener&lt;JSONObject&gt;() { @Override public void onResponse(JSONObject response) { pDialog.dismiss(); try { //Check if user got registered successfully if (response.getInt(KEY_STATUS) == 0) { //Set the user session session.loginUser(username,fullName); loadDashboard(); }else if(response.getInt(KEY_STATUS) == 1){ //Display error message if username is already existsing etUsername.setError("Username already taken!"); etUsername.requestFocus(); }else{ Toast.makeText(getApplicationContext(), response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pDialog.dismiss(); //Display error message whenever an error occurs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest); } /** * Validates inputs and shows error if any * @return */ private boolean validateInputs() { if (KEY_EMPTY.equals(fullName)) { etFullName.setError("Full Name cannot be empty"); etFullName.requestFocus(); return false; } if (KEY_EMPTY.equals(username)) { etUsername.setError("Username cannot be empty"); etUsername.requestFocus(); return false; } if (KEY_EMPTY.equals(password)) { etPassword.setError("Password cannot be empty"); etPassword.requestFocus(); return false; } if (KEY_EMPTY.equals(confirmPassword)) { etConfirmPassword.setError("Confirm Password cannot be empty"); etConfirmPassword.requestFocus(); return false; } if (!password.equals(confirmPassword)) { etConfirmPassword.setError("Password and Confirm Password does not match"); etConfirmPassword.requestFocus(); return false; } return true; } } </code></pre> </div>

解析dataorg.json.JSONException时出错:java.lang.String类型的值<br无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>i'm trying to make android food order for my thesis and because this error i'm running out of time :( </p> <p>error on logcat :</p> <blockquote> <p>Error parsing dataorg.json.JSONException: Value cannot be converted to JSONObject org.json.JSONException: Value to JSONObject</p> </blockquote> <p>here's my JSONParser :</p> <pre><code>package com.makanan.restotradisional; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; public JSONParser() { } // fungsi abil json url lewat method HTTP POST atau GET public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { try { if (method == "POST") { // jika request method adalah 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") { // jika request method adalah 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 + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error Converting result" + e.toString()); } try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data" + e.toString()); e.printStackTrace(); } return jObj; } } </code></pre> <p>this my PHP &amp; Java : <em><a href="http://www.4shared.com/rar/1lGplX19ba/Java_and_PHP.html" rel="nofollow">http://www.4shared.com/rar/1lGplX19ba/Java_and_PHP.html</a></em></p> <p>and this is my database on phpmyadmin :<em><a href="http://www.4shared.com/rar/y_UMtL7_ce/rumah_makan.html" rel="nofollow">http://www.4shared.com/rar/y_UMtL7_ce/rumah_makan.html</a></em></p> <p>please help me</p> </div>

解析数据org.json.JSONException时出错,已经尝试过其他帖子

<div class="post-text" itemprop="text"> <p>I know there are several posts with the same error, but I've proven solutions and still have the same error</p> <p>Log.txt:</p> <pre><code>03-18 18:32:33.082: D/gralloc_goldfish(974): Emulator without GPU emulation detected. 03-18 18:33:21.706: E/JSON Parser(974): Error parsing data org.json.JSONException: End of input at character 0 of 03-18 18:33:21.706: W/dalvikvm(974): threadid=11: thread exiting with uncaught exception (group=0x40a71930) 03-18 18:33:21.726: E/AndroidRuntime(974): FATAL EXCEPTION: AsyncTask #1 03-18 18:33:21.726: E/AndroidRuntime(974): java.lang.RuntimeException: An error occured while executing doInBackground() 03-18 18:33:21.726: E/AndroidRuntime(974): at android.os.AsyncTask$3.done(AsyncTask.java:299) 03-18 18:33:21.726: E/AndroidRuntime(974): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 03-18 18:33:21.726: E/AndroidRuntime(974): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 03-18 18:33:21.726: E/AndroidRuntime(974): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 03-18 18:33:21.726: E/AndroidRuntime(974): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 03-18 18:33:21.726: E/AndroidRuntime(974): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 03-18 18:33:21.726: E/AndroidRuntime(974): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 03-18 18:33:21.726: E/AndroidRuntime(974): at java.lang.Thread.run(Thread.java:856) 03-18 18:33:21.726: E/AndroidRuntime(974): Caused by: java.lang.NullPointerException 03-18 18:33:21.726: E/AndroidRuntime(974): at com.example.cambio_moneda.LoadAllProducts.doInBackground(LoadAllProducts.java:25) 03-18 18:33:21.726: E/AndroidRuntime(974): at com.example.cambio_moneda.LoadAllProducts.doInBackground(LoadAllProducts.java:1) 03-18 18:33:21.726: E/AndroidRuntime(974): at android.os.AsyncTask$2.call(AsyncTask.java:287) 03-18 18:33:21.726: E/AndroidRuntime(974): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 03-18 18:33:21.726: E/AndroidRuntime(974): ... 4 more 03-18 18:33:21.786: D/dalvikvm(974): GC_CONCURRENT freed 149K, 10% free 2622K/2896K, paused 4ms+5ms, total 43ms </code></pre> <p>MainActivity.java</p> <pre><code>package com.example.cambio_moneda; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { JSONParser jParser = new JSONParser(); private TextView tvCambio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvCambio = (TextView) findViewById(R.id.tvCambio); } @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; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void consultarCambio(View v){ new LoadAllProducts().execute(); } } </code></pre> <p>LoadAllProducts.java</p> <pre><code>package com.example.cambio_moneda; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONObject; import android.os.AsyncTask; import android.util.Log; class LoadAllProducts extends AsyncTask&lt;String, String, String&gt;{ JSONParser jsonParser = new JSONParser(); private static String url_all_products = "http://10.10.1.40/cordova/Servidor/cambio_moneda_app/index.php"; @Override protected void onPreExecute(){ } @Override protected String doInBackground(String... params) { List&lt;NameValuePair&gt; params1 = new ArrayList&lt;NameValuePair&gt;(); JSONObject json = jsonParser.makeHttpRequest(url_all_products,"POST",params1); Log.d("All Products: ", json.toString()); return null; } } </code></pre> <p>JSONParser.java</p> <pre><code>package com.example.cambio_moneda; import java.io.InputStream; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject JObj = null; static String json = ""; // Constructor public JSONParser() { } public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { try { if (method == "POST") { 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 (Exception e) { e.printStackTrace(); } try{ JObj = new JSONObject(json); } catch (JSONException e){ Log.e("JSON Parser", "Error parsing data " + e.toString()); } return JObj; } } </code></pre> <p>index.php</p> <pre><code>&lt;?php require_once 'include/app_android/DB_Functions.php'; $db = new DB_Functions(); $response = array(); $result = $db-&gt;get_cambio(); if (mysql_num_rows($result) != 0) { while($reg = mysql_fetch_array($result)){ $fecha = date_create($reg['fecha']); $response['fecha'] = date_format($fecha, 'd-m-Y')." ".date_format($fecha, 'H:i:s'); $response['cambio'] = $reg['cambio']; } echo json_encode($response); } ?&gt; </code></pre> <p>I am new to all this, but I really do not watch what may be the mistake, as I said above, I followed the other post, and I don't find the error</p> <p>Thank you all.</p> <p>PD: In some post gave me negative points, please if I give them, leave a comment to know that I am wrong</p> </div>

如何解决这个问题org.json.JSONException:java.lang.String类型的值数据库无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>i am using Volley library php mysql to build login system and i am facing this problem </p> <p><b> Registration Error= 156 org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONObject</b> </p> <p>and when i check my <b> database user details inserted successfully </b> </p> <p><b> i already tried these ways </b></p> <pre><code>&lt;?php $result = array(); $allValues = array(); $values = array(); if (mysqli_query($connection, $sql)) { $values['status'] = 'true'; $values['message'] = 'successful'; } else { $values['status'] = 'false'; $values['message'] = 'failed'; } $allValues[] = $values; $result['result'] = $allValues; echo json_encode($result); ?&gt; </code></pre> <p><b> change my java codes </b></p> <pre><code>JSONArray jsonArray =response.getJSONArray("result"); for(int i = 0 ; i&lt;jsonArray.length(); i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); Log.i("jsonsingleImage",jsonObject.toString()); String status = jsonObject.getString("status"); String message = jsonObject.getString("message"); JSONObject jo = new JSONObject(success.substring(1, success.length()-1)); new JSONObject(success.substring(success.indexOf("{"), success.lastIndexOf("}") + 1)); </code></pre> <p></p><hr> <b> My Registration.php Codes </b> <pre><code>&lt;?php if ($_SERVER['REQUEST_METHOD'] == "POST") { require_once("connection.php"); $first_name = $_POST['firstName']; $first_name = strip_tags($first_name); $first_name = ucfirst(strtolower($first_name)); // uppercase first letter $first_name = str_replace(' ', '', $first_name); // remove spaces $last_name = $_POST['lastName']; $last_name = strip_tags($last_name); $last_name = ucfirst(strtolower($last_name)); // uppercase first letter $last_name = str_replace(' ', '', $last_name); // remove spaces $email = $_POST['email']; $email = strip_tags($email); $email = str_replace(' ', '', $email); // remove spaces $password = $_POST['password']; $password = mysqli_real_escape_string($password); $password = strip_tags($password); $password = str_replace(' ', '', $password); // remove spaces $password = password_hash($_POST['password'], PASSWORD_BCRYPT); $sql = "INSERT INTO users (firstName, lastName, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')"; if (mysqli_query($connection, $sql)) { $result['success'] = "True"; $result['message'] = "Successfully"; echo json_encode($result); mysqli_close($connection); } else { $result['success'] = "False"; $result['message'] = "Failed"; echo json_encode($result); mysqli_close($connection); } } ?&gt; </code></pre> <hr> <p><b>SignActivity.java Codes </b></p> <pre><code> StringRequest stringRequest = new StringRequest(Request.Method.POST, URLS.SIGNUP_API, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); String success = jsonObject.getString("success"); if (success.equals("True")) { Toast.makeText(SignupActivity.this, "Registration successfully", Toast.LENGTH_LONG).show(); Log.i("Registration ======= ", "Registration successfully"); } } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(SignupActivity.this, "Registration Error= 156 " + e.toString(), Toast.LENGTH_LONG).show(); Log.i("Catch error 156 ======", e.toString()); } } }, ''' </code></pre> </div>

org.json.JSONException:值为10的java.lang.String类型的电子邮件无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>i have a signup form which takes the username,email,password and mobile using json php and store them in php..but at runtime it is iving followin error.</p> <blockquote> <p>org.json.JSONException: Value Email Already Exist at 0 of type java.lang.String cannot be converted to JSONObject W/System.err:<br> at org.json.JSON.typeMismatch(JSON.java:100)</p> </blockquote> <p>my sinup.java is:</p> <pre><code> package com.breera.automechanic_storeapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Signup extends AppCompatActivity { private RequestQueue mQueue; EditText cusname,cusemail,cuspass,cusmobile,confrmpass; String cus_name,cus_email,cus_pass,cus_cnfrmPass,cus_mobile; Button btnlogin,btnSignup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); cusname=findViewById(R.id.fn); cusemail=findViewById(R.id.cusemail); cuspass=findViewById(R.id.cuspass); cusmobile=findViewById(R.id.cusmobile); confrmpass=findViewById(R.id.confrmpass); btnlogin=(Button)findViewById(R.id.logbtn); btnSignup=findViewById(R.id.signup); mQueue = Volley.newRequestQueue(this); btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intnt=new Intent(Signup.this,CusLogin.class); startActivity(intnt); } }); btnSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(Signup.this, "hhh", Toast.LENGTH_SHORT).show(); onsignup(); } }); }public void onsignup(){ cus_name = cusname.getText().toString(); cus_email = cusemail.getText().toString(); cus_pass = cuspass.getText().toString(); cus_cnfrmPass=confrmpass.getText().toString(); cus_mobile = cusmobile.getText().toString(); try { UrlPassClasa urlPassClasa=new UrlPassClasa("customer/signup.php?name=" + cus_name +"&amp;email=" + cus_email+ "&amp;userpass=" + cus_pass+ "&amp;cus_mobile=" + cus_mobile); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, urlPassClasa.getUrl(), null, new Response.Listener&lt;JSONObject&gt;() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("Signup"); JSONObject signup = jsonArray.getJSONObject(0); int signupStatus = signup.getInt("status"); // String signupmsg = signup.getString("msg"); if (signupStatus == 1) { Toast.makeText(Signup.this, "han", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Signup.this, "Failed", Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { Toast.makeText(Signup.this, "Error", Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); mQueue.add(request); }//1st try catch (Exception e) { Toast.makeText(Signup.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }//end mthd } </code></pre> <p>activity_signup.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@drawable/bck" tools:context=".Signup"&gt; &lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Rider's Signup" android:textSize="36sp" android:layout_marginTop="5dp" android:textColor="#fff" android:gravity="center" android:textStyle="bold" android:fontFamily="cursive"/&gt; &lt;ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@drawable/bck" android:layout_marginTop="0dp" android:layout_marginLeft="10dp" android:layout_marginBottom="15dp" android:scrollbarAlwaysDrawVerticalTrack="true" android:layout_marginRight="10dp"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:background="#fff" android:elevation="4dp" android:padding="10dp"&gt; &lt;android.support.design.widget.TextInputLayout android:id="@+id/input_layout_fn" android:layout_width="match_parent" android:layout_marginTop="0dp" android:layout_height="wrap_content" &gt; &lt;EditText android:id="@+id/fn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_people_black_24dp" android:hint="Name" android:inputType="text" android:singleLine="true" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;android.support.design.widget.TextInputLayout android:id="@+id/input_layout_email" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;EditText android:id="@+id/cusemail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_email_black_24dp" android:singleLine="true" android:hint="Mail Address" android:inputType="textEmailAddress" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;android.support.design.widget.TextInputLayout android:id="@+id/input_layout_password" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;EditText android:id="@+id/cuspass" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_lock_black_24dp" android:drawableTint="@color/colorPrimaryDark" android:singleLine="true" android:hint="Password" android:inputType="numberPassword" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;EditText android:id="@+id/confrmpass" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:singleLine="true" android:drawableLeft="@drawable/ic_lock_open_black_24dp" android:hint=" Confirm Password" android:inputType="numberPassword" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;EditText android:id="@+id/cusmobile" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:singleLine="true" android:drawableLeft="@drawable/ic_phone_android_black_24dp" android:hint=" Mobile No" android:inputType="numberPassword" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;Button android:id="@+id/logbtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:textAllCaps="false" android:layout_gravity="right" android:textColor="@color/colorPrimaryDark" android:text="Already an account.Login" /&gt; &lt;Button android:id="@+id/signup" android:layout_width="fill_parent" android:layout_height="40dp" android:layout_margin="5dp" android:background="@drawable/bck" android:text="Sign up" android:textAllCaps="false" android:textColor="#fff" android:textSize="18sp" /&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; &lt;/LinearLayout&gt; </code></pre> <p>signup.php:</p> <pre><code>&lt;?php require_once("../includes/db.php"); require_once("../includes/functions.php"); $response["Signup"] = array(); $name = $_REQUEST["name"]; $email = $_REQUEST["email"]; $userpass = $_REQUEST["userpass"]; $phone = $_REQUEST["cus_mobile"]; //$name = "zain"; //$email = "zain@gmail.com"; //$userpass = "123"; //$phone = "123456"; $msg = array(); if (check_customer_email($con, $email)) { $msg["status"] = 0; $msg["msg"] = "Email Already Exist"; array_push($response["Signup"], $msg["msg"]); } else { $sql = "insert into customer(cus_name, cust_email, cust_userpass,cus_mobile) values ('$name', '$email', '$userpass','$phone')"; if(mysqli_query($con, $sql)) { $msg["status"] = 1; $msg["msg"] = "Values successfully Added"; array_push($response["Signup"], $msg["msg"]); } else { $msg["status"] = 0; array_push($response["Signup"], $msg["status"]); } } echo json_encode($response); ?&gt; </code></pre> <p>UrlPassClasa.java:</p> <pre><code>package com.breera.automechanic_storeapp; public class UrlPassClasa { String Url="http://192.168.0.107/auto_mechanic/"; public UrlPassClasa(String file) { Url=Url+file; } public String getUrl(){ return Url; } } </code></pre> <p>database:<a href="https://i.stack.imgur.com/jPhYQ.png" rel="nofollow noreferrer">enter image description here</a></p> </div>

JSONException:Value。<!类型java.lang.String的DOCTYPE无法转换为JSONObject错误

<div class="post-text" itemprop="text"> <p>I have looked for solutions online on what I might be doing wrong but I am unable to find my mistake. The php works fine so am not sure what I am doing wrong. Please help! Here is my php.</p> <pre><code> &lt;?php if($_SERVER['REQUEST_METHOD']=='GET'){ $Speciality = $_GET['Speciality']; require_once('db_config.php'); $sql = "SELECT * FROM doctor WHERE Speciality='".$Speciality."'"; $r = mysqli_query($con,$sql); $res = mysqli_fetch_array($r); $result = array(); array_push($result,array( "Name"=&gt;$res['Name'], "Speciality"=&gt;$res['Speciality'], "Hospital"=&gt;$res['Hospital'] ) ); echo json_encode(array("result"=&gt;$result)); mysqli_close($con); } </code></pre> <p>The php works fine when I type the address on my web browser so am convinced the problem is on the activity but I dont know where. Here is my main Activity.</p> <pre><code> public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { //For the appointments public static final String DATA_URL = "http://XXXXX.com/doctor.php?Speciality="; public static final String KEY_NAME = "Name"; public static final String KEY_SPECIALITY = "Speciality"; public static final String KEY_HOSPITAL = "Hospital"; public static final String JSON_ARRAY = "result"; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewResult = (TextView) findViewById(R.id.textViewResult); } private void getData() { Spinner spinner=(Spinner)findViewById(R.id.spinnerdoctor); String doctor = spinner.getSelectedItem().toString(); textViewResult = (TextView) findViewById(R.id.textViewResult); if (doctor.equals("")) { Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show(); return; } loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false); String url = DATA_URL+doctor; StringRequest stringRequest = new StringRequest(url, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { loading.dismiss(); showJSON(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this,"Could not connect. Please try again",Toast.LENGTH_LONG).show(); loading.cancel(); } }); RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } private void showJSON(String response){ String Name=""; String Speciality=""; String Hospital = ""; textViewResult = (TextView) findViewById(R.id.textViewResult); try { JSONObject jsonObject = new JSONObject(response); JSONArray result = jsonObject.getJSONArray(JSON_ARRAY); JSONObject collegeData = result.getJSONObject(0); Name = collegeData.getString(KEY_NAME); Speciality = collegeData.getString(KEY_SPECIALITY); Hospital = collegeData.getString(KEY_HOSPITAL); } catch (JSONException e) { e.printStackTrace(); } textViewResult.setText("Name:\t"+Name+" Speciality:\t" +Speciality+ " Hospital:\t"+ Hospital); } public void loaddocs(View v) { getData(); } </code></pre> <p>And my logcat</p> <pre><code> 07-21 10:54:30.629 4221-4221/com.kirathe.mos.afriemergency W/System.err: org.json.JSONException: Value .&lt;!DOCTYPE of type java.lang.String cannot be converted to JSONObject 07-21 10:54:30.631 4221-4221/com.kirathe.mos.afriemergency W/System.err: at org.json.JSON.typeMismatch(JSON.java:111) 07-21 10:54:30.631 4221-4221/com.kirathe.mos.afriemergency W/System.err: at org.json.JSONObject.&lt;init&gt;(JSONObject.java:160) 07-21 10:54:30.631 4221-4221/com.kirathe.mos.afriemergency W/System.err: at org.json.JSONObject.&lt;init&gt;(JSONObject.java:173) 07-21 10:54:30.631 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.kirathe.mos.afriemergency.MainActivity.showJSON(MainActivity.java:389) 07-21 10:54:30.631 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.kirathe.mos.afriemergency.MainActivity.access$100(MainActivity.java:45) 07-21 10:54:30.631 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.kirathe.mos.afriemergency.MainActivity$2.onResponse(MainActivity.java:368) 07-21 10:54:30.631 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.kirathe.mos.afriemergency.MainActivity$2.onResponse(MainActivity.java:364) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at android.os.Handler.handleCallback(Handler.java:739) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at android.os.Looper.loop(Looper.java:211) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5389) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at java.lang.reflect.Method.invoke(Native Method) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at java.lang.reflect.Method.invoke(Method.java:372) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020) 07-21 10:54:30.632 4221-4221/com.kirathe.mos.afriemergency W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815) </code></pre> </div>

解析数据时出错org.json.JSONException:Value String无法转换为JSONArray

<div class="post-text" itemprop="text"> <p>Here is list activity.</p> <p><strong>List Activity:</strong></p> <pre><code>public class ListDataActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_listview); url = "http://xxx.xx.x.xxx/index.php"; Bundle c = getIntent().getExtras(); blo = c.getString("blood"); new ProgressTask(ListDataActivity.this).execute(); } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); } class ProgressTask extends AsyncTask&lt;String, Void, Boolean&gt; { ArrayList&lt;HashMap&lt;String, String&gt;&gt; jsonlist = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); { if (conMgr.getActiveNetworkInfo() != null &amp;&amp; conMgr.getActiveNetworkInfo().isAvailable() &amp;&amp; conMgr.getActiveNetworkInfo().isConnected()) { } else { Toast.makeText(getApplicationContext(), "INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT) .show(); startActivity(new Intent(ListDataActivity.this, MainActivity.class)); } } public ProgressTask(ListActivity activity) { context = activity; } private Context context; protected void onPreExecute() { } @Override protected void onPostExecute(final Boolean success) { ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.row_listitem, new String[] { name, Category }, new int[] { R.id.vehicleType, R.id.vehicleColor }) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { // This a new view we inflate the new layout LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.row_listitem, null); } // TODO Auto-generated method stub if (position % 2 == 1) { convertView.setBackgroundColor(Color.rgb(120, 151, 66)); } else { convertView.setBackgroundColor(Color.rgb(86, 107, 129)); } return super.getView(position, convertView, parent); } }; setListAdapter(adapter); lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { } }); } protected Boolean doInBackground(final String... args) { url = url + "?blo_name=" + blo; Log.d("", url); baseAdapter jParser = new baseAdapter(); JSONArray json = jParser.getJSONFromUrl(url); if (json != null) { for (int i = 0; i &lt; json.length(); i++) { try { JSONObject c = json.getJSONObject(i); String vtype = c.getString(name); String vfuel = c.getString(Category); HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // Add child node to HashMap key &amp; value map.put(name, vtype); map.put(Category, vfuel); jsonlist.add(map); } catch (JSONException e) { e.printStackTrace(); } } } return null; } </code></pre> <p><strong>Base Adapter class:</strong></p> <pre><code>public class baseAdapter { static InputStream iStream = null; static JSONArray jarray = null; static String json = ""; public baseAdapter() { } public JSONArray getJSONFromUrl(String url) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e("==&gt;", "Failed "); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Parse String to JSON object try { jarray = new JSONArray(builder.toString()); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON Object return jarray; } </code></pre> <p><strong>php:</strong></p> <pre><code>if(isset($_POST['blo_name'])){ $str = $_POST['blo_name']; $sql = "SELECT * FROM blood_group where Category IN ($str)"; $result = mysql_query($sql); while($row=mysql_fetch_array($result)) $output[]=$row; print(json_encode($output)); mysql_close(); } </code></pre> <p>My Question is, I an trying to parse <code>bol</code> string, it have value like <code>bol="'B-','O-'";</code> while I parse this type of value it didn't show results and gives the logcat.</p> <p><strong>logcat:</strong></p> <pre><code>Error parsing data org.json.JSONException: Value &lt;br of type java.lang.String cannot be converted to JSONArray </code></pre> <p>While I parse simple value like <code>"B,O"</code>and change in DB it give me result fine. But, I need to parse that value. Pplease, help me out. Thank You</p> </div>

继续解析数据的错误org.json.JsonException:Value <!DOCTYPE

<div class="post-text" itemprop="text"> <p>I have looked at several answered posted here and on Google and am still confused why I am getting this error. The json variable I created reads out I do not have permission. I changed the permissions to allow all and this did not solve the error. I also played around with my URL using my computers IP address of 196.... and the online examples of 127.0.0.1. When I use my IP I get the above error. When I used the 127.0 I get failed to connect error, which I assume is because the IP address does not go anywhere. I tested my PHP code and it input data into MySQL db. So I know that my problem is in my java code. I am posting my code below and trying to post minimal code so I do code dump. If you want me to post more code let me know. </p> <pre><code> try { // check for request method if(method.equals("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.equals("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 + " "); } 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; </code></pre> <p>So what do I need to do to get permission?<br> The Error message I am getting for </p> <pre><code>catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } </code></pre> <p>is:</p> <pre><code>Error parsing data org.json.JSONException: Value DOCTYPE of type java.lang.String cannot be converted to JSONObject </code></pre> </div>

JSON错误:java.lang.String无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>I'm developing an android app and I'm trying to use <strong><em>Volley Library</em></strong>. The problem that I can't solve is about the JSON. I checked my php file, the result and the Java code but I'm still getting the same error. </p> <p>The interesting part is that <strong><em>VolleyLog</em></strong> doesn't show an error message but, <strong><em>Log</em></strong>, does. </p> <pre><code>E/Volley﹕ [1] 2.onErrorResponse: VOLLEY_ERROR </code></pre> <p>and </p> <pre><code>E/LOG﹕ Error: org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject </code></pre> <p>That's my PHP code:</p> <pre><code>&lt;?php # Inform which carachters type will be used. header('Content-Type: text/html; charset=utf-8'); // array for JSON response $response = array(); // include db connect class require_once ('../conn.php'); require_once('pClass.php'); error_reporting( E_ALL ); // connecting to db $db = new DB_CONNECT(); //Setting to UTF8 mysql_query("SET NAMES 'utf8_general_ci'"); mysql_query('SET character_set_connection=utf8_general_ci'); mysql_query('SET character_set_client=utf8_general_ci'); mysql_query('SET character_set_results=utf8_general_ci'); mysql_query('SET CHARACTER SET utf8'); $ff_error = "ERROR"; $arrPOI["arrPOI"] = array(); $poi=new POI(); if (isset($_REQUEST["ff_01"])) { //Execute the query $ff_01 = $_REQUEST['ff_01']; $return = mysql_query($ff_01) or die(mysql_error()); // check for empty result if (mysql_num_rows($return) &gt; 0) { while ($row = mysql_fetch_array($return)) { $poi-&gt;setPOIId($row["intPointId"]); $poi-&gt;setPOIName($row["vchPointName"]); $poi-&gt;setPOIImage($row["vchAwesomeFont"]); $poi-&gt;setStatusId($row["intStatusId"]); $poi-&gt;setLanguageId($row["intLanguageId"]); // push single category into final response array array_push($arrPOI["arrPOI"], $poi-&gt;getPOIData()); } // echoing JSON response header('Content-Type: application/json'); echo json_encode($arrPOI, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_NUMERIC_CHECK); } else { //No data found array_push($arrPOI["arrPOI"], $poi-&gt;getPOIData()); // echo no users JSON header('Content-Type: application/json'); echo json_encode($arrPOI); } } else { //ERROR array_push($arrPOI["arrPOI"], $poi-&gt;getPOIData()); //Echo header('Content-Type: application/json'); echo json_encode($arrPOI); } ?&gt; </code></pre> <p>The PHP result:</p> <pre><code>{"arrPOI":[{"intPOIId":1,"strPOIName":"Cinema","strPOIImage":"fa-film","intStatusId":1,"intLanguageId":1},{"intPOIId":2,"strPOIName":"Teatro","strPOIImage":"fa-smile-o|fa-frown-o","intStatusId":1,"intLanguageId":1},{"intPOIId":3,"strPOIName":"Restaurante","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":4,"strPOIName":"Bar","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":5,"strPOIName":"Pontos Turísticos","strPOIImage":"fa-map-marker","intStatusId":1,"intLanguageId":1},{"intPOIId":6,"strPOIName":"Cafeteria","strPOIImage":"fa-coffee","intStatusId":1,"intLanguageId":1},{"intPOIId":7,"strPOIName":"Shopping","strPOIImage":"fa-diamond","intStatusId":1,"intLanguageId":1},{"intPOIId":8,"strPOIName":"Livraria","strPOIImage":"fa-book","intStatusId":1,"intLanguageId":1},{"intPOIId":9,"strPOIName":"Show","strPOIImage":"fa-microphone","intStatusId":1,"intLanguageId":1},{"intPOIId":10,"strPOIName":"Boates","strPOIImage":"fa-glass","intStatusId":1,"intLanguageId":1},{"intPOIId":11,"strPOIName":"Lanchonete","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":12,"strPOIName":"Hotéis","strPOIImage":"fa-building","intStatusId":1,"intLanguageId":1},{"intPOIId":13,"strPOIName":"Pub","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":14,"strPOIName":"Pizzaria","strPOIImage":"fa-pie-chart","intStatusId":1,"intLanguageId":1},{"intPOIId":15,"strPOIName":"Univesidade","strPOIImage":"fa-university","intStatusId":1,"intLanguageId":1},{"intPOIId":16,"strPOIName":"Hospital","strPOIImage":"fa-plus-square","intStatusId":1,"intLanguageId":1}]} </code></pre> <p>And my Java Code:</p> <pre><code>import com.android.volley.NoConnectionError; import com.android.volley.ServerError; import com.game.code.guide44.adapter.POIAdapter; import com.game.code.guide44.app.AppController; import com.game.code.guide44.data.PointOfInterest; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.Toast; public class POIChoose extends Activity { private ListView lVwPOI; private POIAdapter adapterPOI; private ProgressDialog pDialog; private List&lt;PointOfInterest&gt; POIList; private String url; private StringBuilder stbCheckedPOI; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_poi_choose); //Initialize with ListView object from activity_poi_choose by id lVwPOI = (ListView)findViewById(R.id.lvwPOI); //Initialize the list of POI POIList = new ArrayList&lt;PointOfInterest&gt;(); //initialize with POI List adapterPOI = new POIAdapter(this, POIList); //Fill the LiistView with POIAdapter content lVwPOI.setAdapter(adapterPOI); stbCheckedPOI = new StringBuilder(); //Base url //Change "1" to dynamic user language url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1"); //Initialize the ProgressDialog pDialog = new ProgressDialog(POIChoose.this); //Show the progress bar befores making HTTP request pDialog.setMessage(getString(R.string.txtMsgPleaseWait)); pDialog.show(); // making fresh volley request and getting json JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener&lt;JSONObject&gt;() { @Override public void onResponse(JSONObject response) { VolleyLog.v("VOLLEY", "Response: " + response.toString()); if (response != null) { parseJsonFeed(response); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if(error instanceof NoConnectionError) Toast.makeText(POIChoose.this, "No internet available", Toast.LENGTH_SHORT).show(); else if(error instanceof ServerError) Toast.makeText(POIChoose.this, "Server Error", Toast.LENGTH_SHORT).show(); VolleyLog.e("VOLLEY_ERROR", "Error: " + error.getMessage()); Log.e("LOG", "Error: " + error.getMessage()); pDialog.dismiss(); } }); // Adding request to volley request queue AppController.getInstance().addToRequestQueue(jsonReq); } @Override public void onDestroy() { super.onDestroy(); hidePDialog(); } private void hidePDialog() { if (pDialog != null) { pDialog.dismiss(); pDialog = null; } } private void parseJsonFeed(JSONObject response){ try{ JSONArray jsonArray = response.getJSONArray("arrPOI"); for (int i = 0; i &lt; response.length(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); PointOfInterest Poi = new PointOfInterest(); Poi.setPOIId(jsonObject.getInt("intPointId")); Poi.setPOIName(jsonObject.getString("vchPointName")); Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont")); Poi.setStatusId(jsonObject.getInt("intStatusId")); Poi.setLanguageId(jsonObject.getInt("intLanguageId")); // adding movie to movies array POIList.add(Poi); } } catch(JSONException e){ e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_first_choose, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void performSelectPOI(View view){ for(int i = 0; i &lt; POIList.size(); i++) { if(adapterPOI.mCheckStates.get(i)==true) { stbCheckedPOI.append(POIList.get(i).toString()); stbCheckedPOI.append(" "); } else { } } Toast.makeText(AppController.getContext(), stbCheckedPOI, Toast.LENGTH_LONG).show(); } } </code></pre> <p>I also heard about <strong><em>GSON</em></strong>. Is it the solution? Can anyone help me? Thanks in advance!!</p> </div>

安卓中解析json出现问题,大家帮忙看看

05-07 01:24:03.837: W/System.err(1349): org.json.JSONException: Unterminated string at character 30 of {"Result":"1","LoginPwd":"456} 05-07 01:24:03.837: W/System.err(1349): at org.json.JSONTokener.syntaxError(JSONTokener.java:450) 05-07 01:24:03.837: W/System.err(1349): at org.json.JSONTokener.nextString(JSONTokener.java:230) 05-07 01:24:03.847: W/System.err(1349): at org.json.JSONTokener.nextValue(JSONTokener.java:107) 05-07 01:24:03.847: W/System.err(1349): at org.json.JSONTokener.readObject(JSONTokener.java:385) 05-07 01:24:03.847: W/System.err(1349): at org.json.JSONTokener.nextValue(JSONTokener.java:100) 05-07 01:24:03.857: W/System.err(1349): at org.json.JSONObject.<init>(JSONObject.java:154) 05-07 01:24:03.857: W/System.err(1349): at org.json.JSONObject.<init>(JSONObject.java:171)

解析数据时出错org.json.JSONException:在Android的字符0处输入结束

<div class="post-text" itemprop="text"> <p>I'm developing a test Android application that must display some data from a mysql db. Here my logs:</p> <pre><code>05-22 17:10:56.865: E/JSON Parser(31648): Error parsing data org.json.JSONException: End of input at character 0 of 05-22 17:10:56.865: W/dalvikvm(31648): threadid=11: thread exiting with uncaught exception (group=0x418e3da0) 05-22 17:10:56.875: E/AndroidRuntime(31648): FATAL EXCEPTION: AsyncTask #1 05-22 17:10:56.875: E/AndroidRuntime(31648): Process: com.example.androidhive, PID: 31648 05-22 17:10:56.875: E/AndroidRuntime(31648): java.lang.RuntimeException: An error occured while executing doInBackground() 05-22 17:10:56.875: E/AndroidRuntime(31648): at android.os.AsyncTask$3.done(AsyncTask.java:300) 05-22 17:10:56.875: E/AndroidRuntime(31648): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 05-22 17:10:56.875: E/AndroidRuntime(31648): at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 05-22 17:10:56.875: E/AndroidRuntime(31648): at java.util.concurrent.FutureTask.run(FutureTask.java:242) 05-22 17:10:56.875: E/AndroidRuntime(31648): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 05-22 17:10:56.875: E/AndroidRuntime(31648): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 05-22 17:10:56.875: E/AndroidRuntime(31648): at java.lang.Thread.run(Thread.java:841) 05-22 17:10:56.875: E/AndroidRuntime(31648): Caused by: java.lang.NullPointerException 05-22 17:10:56.875: E/AndroidRuntime(31648): at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130) 05-22 17:10:56.875: E/AndroidRuntime(31648): at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1) 05-22 17:10:56.875: E/AndroidRuntime(31648): at android.os.AsyncTask$2.call(AsyncTask.java:288) 05-22 17:10:56.875: E/AndroidRuntime(31648): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 05-22 17:10:56.875: E/AndroidRuntime(31648): ... 3 more 05-22 17:10:57.436: D/AbsListView(31648): onDetachedFromWindow 05-22 17:10:57.436: D/AbsListView(31648): unregisterIRListener() is called 05-22 17:10:57.446: E/WindowManager(31648): android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42c02238 V.E..... R.....ID 0,0-914,346} that was originally added here 05-22 17:10:57.446: E/WindowManager(31648): at android.view.ViewRootImpl.&lt;init&gt;(ViewRootImpl.java:456) 05-22 17:10:57.446: E/WindowManager(31648): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267) 05-22 17:10:57.446: E/WindowManager(31648): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.Dialog.show(Dialog.java:288) 05-22 17:10:57.446: E/WindowManager(31648): at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117) 05-22 17:10:57.446: E/WindowManager(31648): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587) 05-22 17:10:57.446: E/WindowManager(31648): at android.os.AsyncTask.execute(AsyncTask.java:535) 05-22 17:10:57.446: E/WindowManager(31648): at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.Activity.performCreate(Activity.java:5426) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.ActivityThread.access$900(ActivityThread.java:161) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265) 05-22 17:10:57.446: E/WindowManager(31648): at android.os.Handler.dispatchMessage(Handler.java:102) 05-22 17:10:57.446: E/WindowManager(31648): at android.os.Looper.loop(Looper.java:157) 05-22 17:10:57.446: E/WindowManager(31648): at android.app.ActivityThread.main(ActivityThread.java:5356) 05-22 17:10:57.446: E/WindowManager(31648): at java.lang.reflect.Method.invokeNative(Native Method) 05-22 17:10:57.446: E/WindowManager(31648): at java.lang.reflect.Method.invoke(Method.java:515) 05-22 17:10:57.446: E/WindowManager(31648): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) 05-22 17:10:57.446: E/WindowManager(31648): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 05-22 17:10:57.446: E/WindowManager(31648): at dalvik.system.NativeStart.main(Native Method) 05-22 17:11:01.279: I/Process(31648): Sending signal. PID: 31648 SIG: 9 </code></pre> <p>Here the class JSONParser.java</p> <pre><code>package com.example.androidhive; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request 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(); } </code></pre> <p>Here the class I use to display the selected data:</p> <pre><code>package com.example.androidhive; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class AllProductsActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList&lt;HashMap&lt;String, String&gt;&gt; productsList; // url to get all products list private static String url_all_products = "http://10.1.20.10/android/get_all_products.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCTS = "products"; private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name"; // products JSONArray JSONArray products = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.all_products); // Hashmap for ListView productsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); // Loading products in Background Thread new LoadAllProducts().execute(); // Get listview ListView lv = getListView(); // on seleting single product // launching Edit Product Screen lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // getting values from selected ListItem String pid = ((TextView) view.findViewById(R.id.pid)).getText() .toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), EditProductActivity.class); // sending pid to next activity in.putExtra(TAG_PID, pid); // starting new activity and expecting some response back startActivityForResult(in, 100); } }); } // Response from Edit Product Activity @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // if result code 100 if (resultCode == 100) { // if result code 100 is received // means user edited/deleted product // reload this screen again Intent intent = getIntent(); finish(); startActivity(intent); } } /** * Background Async Task to Load all product by making HTTP Request * */ class LoadAllProducts extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(AllProductsActivity.this); pDialog.setMessage("Loading products. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); // Check your log cat for JSON reponse Log.d("All Products: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // products found // Getting Array of Products products = json.getJSONArray(TAG_PRODUCTS); // looping through All Products for (int i = 0; i &lt; products.length(); i++) { JSONObject c = products.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_PID); String name = c.getString(TAG_NAME); // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value map.put(TAG_PID, id); map.put(TAG_NAME, name); // adding HashList to ArrayList productsList.add(map); } } else { // no products found // Launch Add New product Activity Intent i = new Intent(getApplicationContext(), NewProductActivity.class); // Closing all previous activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( AllProductsActivity.this, productsList, R.layout.list_item, new String[] { TAG_PID, TAG_NAME}, new int[] { R.id.pid, R.id.name }); // updating listview setListAdapter(adapter); } }); } } } </code></pre> <p>Here the php file:</p> <pre><code>get_all_products.php &lt;?php /* * Following code will list all the products */ // array for JSON response $response = array(); // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $db = new DB_CONNECT(); // get all products from products table $result = mysql_query("SELECT *FROM products") or die(mysql_error()); // check for empty result if (mysql_num_rows($result) &gt; 0) { // looping through all results // products node $response["products"] = array(); while ($row = mysql_fetch_array($result)) { // temp user array $product = array(); $product["pid"] = $row["pid"]; $product["name"] = $row["name"]; $product["price"] = $row["price"]; $product["created_at"] = $row["created_at"]; $product["updated_at"] = $row["updated_at"]; // push single product into final response array array_push($response["products"], $product); } // success $response["success"] = 1; // echoing JSON response echo json_encode($response); } else { // no products found $response["success"] = 0; $response["message"] = "No products found"; // echo no users JSON echo json_encode($response); } ?&gt; </code></pre> <p>In addition, here the main Activity:</p> <pre><code>package com.example.androidhive; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainScreenActivity extends Activity{ Button btnViewProducts; Button btnNewProduct; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_screen); // Buttons btnViewProducts = (Button) findViewById(R.id.btnViewProducts); btnNewProduct = (Button) findViewById(R.id.btnCreateProduct); // view products click event btnViewProducts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launching All products Activity Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); startActivity(i); } }); // view products click event btnNewProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launching create new product activity Intent i = new Intent(getApplicationContext(), NewProductActivity.class); startActivity(i); } }); } } </code></pre> <p>I read various thread around the internet about this error, but it is even caused by differents problems, and I did not found a case similar to mine or a solution that solved my problem.</p> </div>

json数据转换异常

json数据转换异常:net.sf.json.JSONException: java.lang.reflect.InvocationTargetException 解决方法如下(非常感谢这位童鞋): 摘自:http://www.2cto.com/kf/201312/266457.html 执行: JSONArray array = JSONArray.fromObject(this.users); 就会报以下错误: net.sf.json.JSONException: java.lang.reflect.InvocationTargetException users是一个list集合 方案一: JSONArray array = JSONArray.fromObject(this.users.toArray()); 方案二: 因为bean里有Date字段,且从数据库里读出来的是java.sql.Date赋值给了java.util.Date,转化成JSONArray时出错;可以在从数据库读出Date 时直接写成:new java.util.Date(rs.getDate("date").getTime),这样就不会出错了; 方案三: 日期格式hibernate延时加载 1.解决:日期格式 private java.util.Date createTime; 只在字段前声明Date的数据类型可能也会抛异常,在Set,get方法中,有出现Date类型的都把包名加上 2.解决:hibernate延时加载 设置 Java代码 收藏代码 JsonConfig cfg = new JsonConfig(); cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"}); 方法举例 Java代码 收藏代码(参考图片) ![图片说明](https://img-ask.csdn.net/upload/201612/22/1482382044_822286.png)

按照第一行代码上打酷欧天气提示我 Value Request of type java.lang.String cannot be converte

12-28 19:54:35.763 7686-8889/com.example.administrator.kuou W/System.err: org.json.JSONException: Value Request of type java.lang.String cannot be converted to JSONObject 12-28 19:54:35.763 7686-8889/com.example.administrator.kuou W/System.err: at org.json.JSON.typeMismatch(JSON.java:111) 12-28 19:54:35.763 7686-8889/com.example.administrator.kuou W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160) 12-28 19:54:35.763 7686-8889/com.example.administrator.kuou W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173) 12-28 19:54:35.763 7686-8889/com.example.administrator.kuou W/System.err: at com.example.administrator.kuou.util.Utility.handleWeatherResponse(Utility.java:125) 12-28 19:54:35.764 7686-8889/com.example.administrator.kuou W/System.err: at com.example.administrator.kuou.WeatherActivity$1.onResponse(WeatherActivity.java:91) 12-28 19:54:35.764 7686-8889/com.example.administrator.kuou W/System.err: at okhttp3.RealCall$AsyncCall.execute(RealCall.java:126) 12-28 19:54:35.764 7686-8889/com.example.administrator.kuou W/System.err: at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 12-28 19:54:35.764 7686-8889/com.example.administrator.kuou W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 12-28 19:54:35.764 7686-8889/com.example.administrator.kuou W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 12-28 19:54:35.764 7686-8889/com.example.administrator.kuou W/System.err: at java.lang.Thread.run(Thread.java:760) 12-28 19:54:35.764 7686-7686/com.example.administrator.kuou D/TAG: run: null 12-28 19:54:35.782 7686-7686/com.example.administrator.kuou I/Toast: Show toast from OpPackageName:com.example.administrator.kuou, PackageName:com.example.administrator.kuou ``` ```public static Weather handleWeatherResponse(String response) { try { // 将整个json实例化保存在jsonObject中 JSONObject jsonObject = new JSONObject(response); // 从jsonObject中取出键为"HeWeather"的数据,并保存在数组中 JSONArray jsonArray = jsonObject.getJSONArray("Weather"); // 取出数组中的第一项,并以字符串形式保存 String weatherContent = jsonArray.getJSONObject(0).toString(); // 返回通过Gson解析后的Weather对象 return new Gson().fromJson(weatherContent, Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; }

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

Python可以这样学(第四季:数据分析与科学计算可视化)

董付国老师系列教材《Python程序设计(第2版)》(ISBN:9787302436515)、《Python可以这样学》(ISBN:9787302456469)配套视频,在教材基础上又增加了大量内容,通过实例讲解numpy、scipy、pandas、statistics、matplotlib等标准库和扩展库用法。

组成原理课程设计(实现机器数的真值还原等功能)

实现机器数的真值还原(定点小数)、定点小数的单符号位补码加减运算、定点小数的补码乘法运算和浮点数的加减运算。

javaWeb图书馆管理系统源码mysql版本

系统介绍 图书馆管理系统主要的目的是实现图书馆的信息化管理。图书馆的主要业务就是新书的借阅和归还,因此系统最核心的功能便是实现图书的借阅和归还。此外,还需要提供图书的信息查询、读者图书借阅情况的查询等

土豆浏览器

土豆浏览器可以用来看各种搞笑、电影、电视剧视频

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

Java8零基础入门视频教程

这门课程基于主流的java8平台,由浅入深的详细讲解了java SE的开发技术,可以使java方向的入门学员,快速扎实的掌握java开发技术!

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

TTP229触摸代码以及触摸返回值处理

自己总结的ttp229触摸代码,触摸代码以及触摸按键处理

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

本课程适合CCNA或HCNA网络小白同志,高手请绕道,可以直接学习进价课程。通过本预科课程的学习,为学习网络工程师、思科CCNA、华为HCNA这些认证打下坚实的基础! 重要!思科认证2020年2月24日起,已启用新版认证和考试,包括题库都会更新,由于疫情原因,请关注官网和本地考点信息。题库网络上很容易下载到。

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

java jdk 8 帮助文档 中文 文档 chm 谷歌翻译

JDK1.8 API 中文谷歌翻译版 java帮助文档 JDK API java 帮助文档 谷歌翻译 JDK1.8 API 中文 谷歌翻译版 java帮助文档 Java最新帮助文档 本帮助文档是使用谷

Ubuntu18.04安装教程

Ubuntu18.04.1安装一、准备工作1.下载Ubuntu18.04.1 LTS2.制作U盘启动盘3.准备 Ubuntu18.04.1 的硬盘空间二、安装Ubuntu18.04.1三、安装后的一些工作1.安装输入法2.更换软件源四、双系统如何卸载Ubuntu18.04.1新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列...

快速排序---(面试碰到过好几次)

原理:    快速排序,说白了就是给基准数据找其正确索引位置的过程.    如下图所示,假设最开始的基准数据为数组第一个元素23,则首先用一个临时变量去存储基准数据,即tmp=23;然后分别从数组的两端扫描数组,设两个指示标志:low指向起始位置,high指向末尾.    首先从后半部分开始,如果扫描到的值大于基准数据就让high减1,如果发现有元素比该基准数据的值小(如上图中18&amp;lt...

手把手实现Java图书管理系统(附源码)

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录https://edu.csdn.net/course/detail/27513,点击右下方课程资料、代码、课件等打包下载

HTML期末大作业

这是我自己做的HTML期末大作业,花了很多时间,稍加修改就可以作为自己的作业了,而且也可以作为学习参考

Python数据挖掘简易入门

&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

想学好JAVA必须要报两万的培训班吗? Java大神勿入 如果你: 零基础想学JAVA却不知道从何入手 看了一堆书和视频却还是连JAVA的环境都搭建不起来 囊中羞涩面对两万起的JAVA培训班不忍直视 在职没有每天大块的时间专门学习JAVA 那么恭喜你找到组织了,在这里有: 1. 一群志同道合立志学好JAVA的同学一起学习讨论JAVA 2. 灵活机动的学习时间完成特定学习任务+每日编程实战练习 3. 热心助人的助教和讲师及时帮你解决问题,不按时完成作业小心助教老师的家访哦 上一张图看看前辈的感悟: &nbsp; &nbsp; 大家一定迫不及待想知道什么是极简JAVA学习营了吧,下面就来给大家说道说道: 什么是极简JAVA学习营? 1. 针对Java小白或者初级Java学习者; 2. 利用9天时间,每天1个小时时间; 3.通过 每日作业 / 组队PK / 助教答疑 / 实战编程 / 项目答辩 / 社群讨论 / 趣味知识抢答等方式让学员爱上学习编程 , 最终实现能独立开发一个基于控制台的‘库存管理系统’ 的学习模式 极简JAVA学习营是怎么学习的? &nbsp; 如何报名? 只要购买了极简JAVA一:JAVA入门就算报名成功! &nbsp;本期为第四期极简JAVA学习营,我们来看看往期学员的学习状态: 作业看这里~ &nbsp; 助教的作业报告是不是很专业 不交作业打屁屁 助教答疑是不是很用心 &nbsp; 有奖抢答大家玩的很嗨啊 &nbsp; &nbsp; 项目答辩终于开始啦 &nbsp; 优秀者的获奖感言 &nbsp; 这是答辩项目的效果 &nbsp; &nbsp; 这么细致的服务,这么好的氛围,这样的学习效果,需要多少钱呢? 不要1999,不要199,不要99,只要9.9 是的你没听错,只要9.9以上所有就都属于你了 如果你: 1、&nbsp;想学JAVA没有基础 2、&nbsp;想学JAVA没有整块的时间 3、&nbsp;想学JAVA没有足够的预算 还等什么?赶紧报名吧,抓紧抢位,本期只招300人,错过只有等时间待定的下一期了 &nbsp; 报名请加小助手微信:eduxy-1 &nbsp; &nbsp;

C++语言基础视频教程

C++语言基础视频培训课程:本课与主讲者在大学开出的程序设计课程直接对接,准确把握知识点,注重教学视频与实践体系的结合,帮助初学者有效学习。本教程详细介绍C++语言中的封装、数据隐藏、继承、多态的实现等入门知识;主要包括类的声明、对象定义、构造函数和析构函数、运算符重载、继承和派生、多态性实现等。 课程需要有C语言程序设计的基础(可以利用本人开出的《C语言与程序设计》系列课学习)。学习者能够通过实践的方式,学会利用C++语言解决问题,具备进一步学习利用C++开发应用程序的基础。

UnityLicence

UnityLicence

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

YOLOv3目标检测实战:训练自己的数据集

YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!

Python数据分析师-实战系列

系列课程主要包括Python数据分析必备工具包,数据分析案例实战,核心算法实战与企业级数据分析与建模解决方案实战,建议大家按照系列课程阶段顺序进行学习。所有数据集均为企业收集的真实数据集,整体风格以实战为导向,通俗讲解Python数据分析核心技巧与实战解决方案。

YOLOv3目标检测实战系列课程

《YOLOv3目标检测实战系列课程》旨在帮助大家掌握YOLOv3目标检测的训练、原理、源码与网络模型改进方法。 本课程的YOLOv3使用原作darknet(c语言编写),在Ubuntu系统上做项目演示。 本系列课程包括三门课: (1)《YOLOv3目标检测实战:训练自己的数据集》 包括:安装darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 (2)《YOLOv3目标检测:原理与源码解析》讲解YOLOv1、YOLOv2、YOLOv3的原理、程序流程并解析各层的源码。 (3)《YOLOv3目标检测:网络模型改进方法》讲解YOLOv3的改进方法,包括改进1:不显示指定类别目标的方法 (增加功能) ;改进2:合并BN层到卷积层 (加快推理速度) ; 改进3:使用GIoU指标和损失函数 (提高检测精度) ;改进4:tiny YOLOv3 (简化网络模型)并介绍 AlexeyAB/darknet项目。

超详细MySQL安装及基本使用教程

一、下载MySQL 首先,去数据库的官网http://www.mysql.com下载MySQL。 点击进入后的首页如下:  然后点击downloads,community,选择MySQL Community Server。如下图:  滑到下面,找到Recommended Download,然后点击go to download page。如下图:  点击download进入下载页面选择No...

一学即懂的计算机视觉(第一季)

图像处理和计算机视觉的课程大家已经看过很多,但总有“听不透”,“用不了”的感觉。课程致力于创建人人都能听的懂的计算机视觉,通过生动、细腻的讲解配合实战演练,让学生真正学懂、用会。 【超实用课程内容】 课程内容分为三篇,包括视觉系统构成,图像处理基础,特征提取与描述,运动跟踪,位姿估计,三维重构等内容。课程理论与实战结合,注重教学内容的可视化和工程实践,为人工智能视觉研发及算法工程师等相关高薪职位就业打下坚实基础。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/26281 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,但是大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录https://edu.csdn.net/course/detail/26281,点击右下方课程资料、代码、课件等打包下载

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

爬取妹子图片(简单入门)

安装第三方请求库 requests 被网站禁止了访问 原因是我们是Python过来的 重新给一段 可能还是存在用不了,使用网页的 编写代码 上面注意看匹配内容 User-Agent:请求对象 AppleWebKit:请求内核 Chrome浏览器 //请求网页 import requests import re //正则表达式 就是去不规则的网页里面提取有规律的信息 headers = { 'User-Agent':'存放浏览器里面的' } response = requests.get

web网页制作期末大作业

分享思维,改变世界. web网页制作,期末大作业. 所用技术:html css javascript 分享所学所得

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

相关热词 c# 局部 截图 页面 c#实现简单的文件管理器 c# where c# 取文件夹路径 c# 对比 当天 c# fir 滤波器 c# 和站 队列 c# txt 去空格 c#移除其他类事件 c# 自动截屏
立即提问