Estou tentando executar o app no Android, onde quero listar os dados cadastrados em uma tabela Mysql. Estou tentando dessa forma:
Conexão
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();
}
}
}
}
Listar dados
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);
}
}
O PHP está dessa forma:
<?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);
Quando tento executar, diz que o app parou e em seguida fecha. Na depuração, o erro é:
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)
A linha 88:
dataParsed = dataParsed + singleParsed;
A linha 56:
String singleParsed = "";
O que pode estar de errado?