英文:
Value connected of type java.lang.string cannot be converted to jsonobject [Android Volley Library]
问题
I understand that you're facing an issue with your code, and you'd like some assistance. The error message you provided, "value connected of type java.lang.string cannot be converted to jsonobject," suggests that there might be a problem with the response from your PHP script. It seems that the response is not in the expected JSON format.
To address this issue, you can make the following adjustments to your PHP code:
- Ensure that you are setting the content type correctly in your PHP script. You have a typographical error in the content type header. It should be "charset" instead of "chartset." Correct it to:
header('Content-type: application/json; charset=utf-8');
- In your PHP code, you have an error when echoing the response for failure. Change this line:
echo json_encode($response);
to:
echo json_encode($result);
- It's also a good practice to add error handling for your database connection and query. Here's an updated version of your PHP script with improved error handling:
<?php
header('Content-type: application/json; charset=utf-8');
include 'conn.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$noHp = $_POST['noHp'];
$email = $_POST['email'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$password = $_POST['password'];
$q = mysqli_query($conn, "INSERT INTO user (noHp, email, nama, alamat, password) VALUES ('$noHp','$email','$nama','$alamat','$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
echo json_encode($response);
} else {
$response["success"] = "0";
$response["message"] = "error";
echo json_encode($response);
}
mysqli_close($conn);
}
?>
Make these changes in your PHP script and see if it resolves the JSON conversion error you were encountering. Additionally, ensure that your Android app is correctly handling the JSON response from the PHP script.
英文:
I know, i know, it's an old question to ask but I'm totally stuck. I've been trying to solve it using all those answer on Stackoverflow but still helpless. So, this is my code:
[Java]:
package com.projectbengkelin;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
EditText Edtnama,Edtemail,Edtalamat,EdtnoHp,Edtpassword;
Button btnLanjut;
Button btnKembali;
ProgressBar loading;
String nama, email, alamat, noHp, password;
//private static String URL_REGISTER = "http://192.168.56.1/finals-mobile/register.php";
String URL_REGISTER = "https://bengkelinteam.000webhostapp.com/api/insert_user.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Edtnama = findViewById(R.id.nama);
Edtemail = findViewById(R.id.email);
Edtalamat = findViewById(R.id.alamat);
EdtnoHp = findViewById(R.id.noHp);
Edtpassword = findViewById(R.id.password);
loading = findViewById(R.id.loading);
btnLanjut = findViewById(R.id.btnLanjut);
btnKembali = findViewById(R.id.btnKembali);
btnKembali.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openMainActivity();
}
});
btnLanjut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Register();
}
});
}
private void Register() {
loading.setVisibility(View.VISIBLE);
btnLanjut.setVisibility(View.GONE);
nama = Edtnama.getText().toString();
email = Edtemail.getText().toString();
alamat = Edtalamat.getText().toString();
noHp = EdtnoHp.getText().toString();
password = Edtpassword.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(Register.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
int sukses = jsonObject.getInt("success");
// Toast.makeText(Register.this, "Setelah jsonObject", Toast.LENGTH_SHORT).show();
if (sukses == 1) {
Toast.makeText(Register.this, "Register Success!", Toast.LENGTH_SHORT).show();
finish();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(Register.this, "Register Failed!" + e.toString(), Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
btnLanjut.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this, "Register Failed!" + error.toString(), Toast.LENGTH_SHORT).show();
//error.printStackTrace();
Log.e("Error", error.getMessage());
loading.setVisibility(View.GONE);
btnLanjut.setVisibility(View.VISIBLE);
}
})
{
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("nama", nama);
params.put("email", email);
params.put("alamat", alamat);
params.put("noHp", noHp);
params.put("password", password);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.getCache().clear();
requestQueue.add(stringRequest);
}
public void openMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
And then, here is my PHP code which is I'd put on 000webhost:
[PHP]:
<?php
header('Content-type:application/json;chartset=utf-8');
include 'conn.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$noHp = $_POST['noHp'];
$email = $_POST['email'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$password = $_POST['password'];
// $password = password_hash($password, PASSWORD_DEFAULT);
// require_once 'connect.php';
$q = mysqli_query($conn, "INSERT INTO user (noHp, email ,nama, alamat, password) VALUES ('$nohp','$email','$nama','$alamat','$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
echo json_encode($response);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($response);
mysqli_close($conn);
}
}
Everytime I tried to insert the data using that API JSON, I always get this error messange:
value connected of type java.lang.string cannot be converted to jsonobject
Please help me.
答案1
得分: 0
你的 PHP 代码中存在一个简单的问题 - 做如下更改:
$response = array();
$q = mysqli_query($conn, "INSERT INTO user (noHp, email, nama, alamat, password) VALUES ('$nohp', '$email', '$nama', '$alamat', '$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
} else {
$response["success"] = "0";
$response["message"] = "error";
}
echo json_encode($response);
mysqli_close($conn);
使用 Postman 来检查你的响应。
英文:
there is simple issue in your php code - do like that :
$response=array();
$q = mysqli_query($conn, "INSERT INTO user (noHp, email ,nama, alamat, password) VALUES ('$nohp','$email','$nama','$alamat','$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
} else {
$response["success"] = "0";
$response["message"] = "error";
}
echo json_encode($response);
mysqli_close($conn);
use Postman to check your response
专注分享java语言的经验与见解,让所有开发者获益!
评论