App only brings a record on Android

Asked

Viewed 67 times

0

I’m developing an app on Android where the data is in a web-based developed in PHP/Mysql. The code I’m using to get the data is:

public class ListarDados extends AppCompatActivity {

public static TextView data;

//String url = ""; //

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

        data = (TextView) findViewById(R.id.fetchedata);

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if(networkInfo != null && networkInfo.isConnected()){

           new SolicitaDados().execute();

        }else {
            Toast.makeText(getApplicationContext(), "Nenhuma conexão ativa", Toast.LENGTH_LONG).show();
        }
    }

    private class SolicitaDados extends AsyncTask<Void, Void, Void> {

        String data = "";
        String dataParsed = "";
        String singleParsed = "";

        @Override
        protected Void doInBackground(Void... voids){
            try {
                URL url = new URL("http://192.168.0.13/plataforma/android/listar.php");
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                String linhas = "";

                while(linhas != null){
                    linhas = bufferedReader.readLine();
                    data = data + linhas;
                }

                JSONArray JA = new JSONArray(data);

                  for(int i = 0; i < JA.length(); i++){
                      JSONObject JO = (JSONObject) JA.get(i);
                      singleParsed = "Email:" + JO.get("Email") + "Senha:" + JO.get("Senha") + "\n";
                      dataParsed = dataParsed + singleParsed + "\n";
                  }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ListarDados.data.setText(this.dataParsed);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Intent voltar = new Intent(ListarDados.this, ConteudoSistema.class);
        startActivity(voltar);
    }
}

Although in the database have 04 records:

inserir a descrição da imagem aqui

And PHP being that way:

<?php
$conexao = mysqli_connect('localhost','root','sucesso','projetos');

$sql = mysqli_query($conexao,"SELECT * FROM pe_mobile");

$mostrar = array();
//$mostrar["dados"] = array();

foreach($sql as $linha){

$listar["Email"] = $linha["Email"];
$listar["Senha"] = $linha["Senha"];

array_push($mostrar,$listar);
}
echo json_encode($mostrar);

I have as a result:

[{"Email":"[email protected]","Senha":"123"},{"Email":"[email protected]","Senha":"321"},{"Email":"[email protected]","Senha":"456"},{"Email":"[email protected]","Senha":"654"}]

But when I run the app, it only returns me the first record. How do I bring all the records?

In the Arrayjson tab, returns the following:

inserir a descrição da imagem aqui

  • This is Fox. So maybe you already have, but have tried debugging and inspecting Arrayjson JA?

  • Hi Marlon. I haven’t tried that yet. For me to debug, would it be inside Android Studio itself? I ask, because I’m starting now to work with this IDE and I don’t have much experience in it.

  • Yes, it’s only time to build you choose the bug icon button, then put a break point on the variable line and re-test the operation. When you go through the line the IDE will freeze the processing and you will be able to inspect what is inside the variable

  • Right. I debugged and put the print in the post. It looks like it’s returning the values correctly.

1 answer

-1

I’m not sure and I can’t confirm at the moment, but if I’m not mistaken you can use mysqli_fetch_all(), that will already return all desired records in an array, so that you can send directly as JSON for the request response.

That would be the idea:

<?php
$conexao = mysqli_connect('localhost','root','sucesso','projetos');
$sql = mysqli_query($conexao,"SELECT * FROM pe_mobile");
echo json_encode( mysqli_fetch_all( $sql, \MYSQLI_ASSOC ) );

It would be interesting if you set the response header to JSON as well:

header( 'Content-Type: application/json' );//antes do echo

And for development it would be interesting to enable error messages:

error_reporting( E_ALL );//primeira linha de código após abertura do <?php

See these examples from the manual as well: https://secure.php.net/manual/en/mysqli-result.fetch-row.php

  • Hello Erick. I tried this way, but it also only returns the first record. I believe the problem is in Java, because when I print directly on the screen, PHP brings all the results.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.