1
resposta

String cannot be converted to JSONObject

Alguém pode me ajudar? Estou tentando buscar dados de um banco de dados em um servidor, mas estou tendo um erro.

org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

O app esta cadastrando normal no banco de dados do servidor. Estou tentando fazer a busca para mostrar na tela a lista de dados cadastrados.

MAIN ACTIVITY

public class MainActivity extends AppCompatActivity {
    private final String URL_LISTAR = "https://restaurantecome.000webhostapp.com/listar.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        result = findViewById(R.id.tvResult);

        etNome = findViewById(R.id.editTextNome);
        etIdade = findViewById(R.id.editTextIdade);

        btAdicionar = findViewById(R.id.button);
        btShow = findViewById(R.id.btMostrarLista);

        loading = findViewById(R.id.loading);

        requestQueue = Volley.newRequestQueue(this);

        //Botão Adicionar
        btAdicionar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Registrar();
            }
        });

        //Botão Listar
        btShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Listar();
            }
        });
    }

//FUNÇÃO PARA REALIZAR A BUSCA DAS INFORMAÇÕES
public void Listar(){
        //System.out.println("ww");
        Toast.makeText(MainActivity.this,
                "Carregando",
                Toast.LENGTH_SHORT).show();

        //Log.v("zzz", "01: " + parametrosLista.names());
        //Log.v("zzz", "01: " + parametrosLista.length());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL_LISTAR,
                null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.v("zzz", "1: " + response.toString());
                System.out.println(response.toString());
                try {
                    Log.v("zzz", "Entrei 1");
                    JSONArray students = response.getJSONArray("students");
                    for (int i = 0; i < students.length(); i++) {
                        JSONObject student = students.getJSONObject(i);

                        String nome = student.getString("nome");
                        String idade = student.getString("idade");

                        result.append(nome + " " + idade +  "\n");
                    }
                    result.append("===\n");
                    Log.v("zzz", "Entrei 2");
                    Toast.makeText(MainActivity.this,
                            "Click",
                            Toast.LENGTH_SHORT).show();

                } catch (JSONException e) {
                    Log.v("zzz", "Entrei 3");
                    Log.v("zzz", "erro: " + e.getMessage());
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this,
                            "Erro: " + e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.v("zzz", "Entrei 4");
                Log.v("zzz", "erro: " + error.getMessage());
                Toast.makeText(MainActivity.this,
                        "Erro: " + error.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

PHP - Listagem

<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
    include 'conexao.php';
    showStudent();
}

function showStudent()
{
    global $connect;

    $query = " SELECT * FROM tb_pessoas; ";

    $result = mysqli_query($connect, $query);
    $number_of_rows = mysqli_num_rows($result);

    $temp_array  = array();

    if($number_of_rows > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $temp_array[] = $row;
        }
    }
    header('Content-Type: application/json');
    echo json_encode(array("students"=>$temp_array));
    mysqli_close($connect);
}
?>
1 resposta

Fala Matheus, tudo bem ?

Seu problema é que seu servidor está enviando um objeto e você está tentando converter como string