App is closing when debugging on Android

Asked

Viewed 38 times

0

I’m trying to run the app on Android, where I want to list the data registered in a Mysql table. I’m trying this way:

Connection

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Conexao {

    public static String postDados(String urlUsuario, String parametrosUsuarios){

        URL url;
        HttpURLConnection connection = null;

        try{

           url = new URL(urlUsuario);

           connection = (HttpURLConnection) url.openConnection();

           connection.setRequestMethod("POST");
           connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
           connection.setRequestProperty("Content-Lenght","" + Integer.toString(parametrosUsuarios.getBytes().length));
           connection.setRequestProperty("Content-Language","pt-BR");
           connection.setUseCaches(false);
           connection.setDoInput(true);
           connection.setDoOutput(true);

           /*
           DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
           dataOutputStream.writeBytes(parametrosUsuarios);
           dataOutputStream.flush();
           dataOutputStream.close();
           */

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            outputStreamWriter.write(parametrosUsuarios);
            outputStreamWriter.flush();

           InputStream inputStream = connection.getInputStream();

           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
           String linha;
           StringBuffer resposta = new StringBuffer();

           while ((linha = bufferedReader.readLine()) != null){
                resposta.append(linha);
                resposta.append('\r');
           }

           bufferedReader.close();

           return resposta.toString();

        }catch (Exception erro){

            return null;
        }finally {

            if(connection != null){
                connection.disconnect();
            }
        }
    }
}

List data

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ListarDados extends AppCompatActivity {

TextView txtListar;
public static TextView data;

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

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

        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/projeto/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;

                  }

            } 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);
    }
}

PHP is that way:

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

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

while($jm = mysqli_fetch_array($sql)){
       $mostrar[] = $jm["Email"];
       $mostrar[] =  $jm["Senha"];
}

echo json_encode($mostrar);

When I try to run, it says that the app has stopped and then closes. In debugging, the error is:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
                  Process: br.com.projeto.acessosistema, PID: 2192
                  java.lang.RuntimeException: An error occurred while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:318)
                      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                      at java.lang.Thread.run(Thread.java:761)
                   Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject
                      at br.com.projeto.acessosistema.ListarDados$SolicitaDados.doInBackground(ListarDados.java:88)
                      at br.com.projeto.acessosistema.ListarDados$SolicitaDados.doInBackground(ListarDados.java:56)
                      at android.os.AsyncTask$2.call(AsyncTask.java:304)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
                      at java.lang.Thread.run(Thread.java:761) 

The line 88:

dataParsed = dataParsed + singleParsed;

The line 56:

String singleParsed = "";

What could be wrong?

  • I noticed that it does not seem to work with PHP files, because when I tested through http://myjson.com/ and then with a js file it worked correctly. What can it be?

1 answer

0

I was able to solve the auto lock. The problem was in PHP and I adjusted the code to:

<?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);

Browser other questions tagged

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