dongqi8114 2018-08-04 11:28
浏览 243

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

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

android activity

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) &&
                                validateBio(bio)&&
                                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<String>() {
            @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<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();

                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 && resultCode == Activity.RESULT_OK && 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() > 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() > 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;
    }
}

Every time i run the app and click the save button this comes up in log

    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.<init>(JSONObject.java:163)
        at org.json.JSONObject.<init>(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)

php

  @$name= $_POST['name'];
    @$bio=$_POST['bio'];
        @$email=$_POST['email'];
        @$id=$_POST['id'];

    if(!empty($_POST['name']) && !empty($_POST['bio']) && !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';
    }

I am not to figure out whether the problem is in php or android code. Any help will be deeply appreciated

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 活动选择题。最多可以参加几个项目?
    • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
    • ¥15 vs2019中数据导出问题
    • ¥20 云服务Linux系统TCP-MSS值修改?
    • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
    • ¥20 怎么在stm32门禁成品上增加查询记录功能
    • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
    • ¥50 NT4.0系统 STOP:0X0000007B
    • ¥15 想问一下stata17中这段代码哪里有问题呀
    • ¥15 flink cdc无法实时同步mysql数据