>

Fórum

Fórum da RL System, voltado para analistas, programadores etc. Tudo sobre linguagem de programação e desenvolvimento Full Stack: Banco de Dados, Android, C#, Java, .NET, PHP, Node, Javascript, TypeScript, Front, HTML e muito mais.



Curso Android Online - Aula 5 e 6 - Classe Service - Não consigo exportar os dados para o BD MySQL - Não passa do "InputStreamReader"


Segue codigo para analise. Debugando vi que chegar no "InputStreamReader", não consegue passar e volta para o While. Estou usando o WampServer (Apache 2.4.9 / PHP 5.5.12 / MySQL 5.6.17).
Obs.: executando o link: "http://localhost/vendas/inserir.php?produto=1&cliente=Trucks&latitude=-21.0&longitude=23.0" direto no navegador, os dados são incluídos no banco corretamente.


package com.example.vendas;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.util.Log;


public class ExportarVendasService extends Service implements Runnable {

public void onCreate() {
new Thread(ExportarVendasService.this).start();
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

public void run() {

SQLiteDatabase db = openOrCreateDatabase("vendas.db", Context.MODE_PRIVATE, null);

Cursor cursor = db.rawQuery("SELECT * FROM venda", null);

int totalDB = cursor.getCount();
int totalReplicado = 0;

while(cursor.moveToNext()){
StringBuilder strURL = new StringBuilder();
strURL.append("http://localhost/vendas/inserir.php?produto=");
strURL.append(cursor.getInt(cursor.getColumnIndex("produto")));
strURL.append("&cliente=");
strURL.append(cursor.getString(cursor.getColumnIndex("cliente")));
strURL.append("&latitude=");
strURL.append(cursor.getDouble(cursor.getColumnIndex("la")));
strURL.append("&longitude=");
strURL.append(cursor.getDouble(cursor.getColumnIndex("lo")));
Log.d("Exportar VendasService", strURL.toString());
try{
URL url = new URL(strURL.toString());
HttpURLConnection http = (HttpURLConnection) url.openConnection();
InputStreamReader ips = new InputStreamReader(http.getInputStream());
BufferedReader line = new BufferedReader(ips);

String linhaRetorno = line.readLine();

if(linhaRetorno.equals("Y")){
db.delete("venda", "_id=?", new String[]{String.valueOf(cursor.getInt(0))});
totalReplicado++;
Log.d("Exportar VendasService", "OK");
}

}catch(Exception ex){
Log.d("Exportar VendasService", ex.getMessage());

}
}

db.close();

if(totalDB == totalReplicado);

/*for (int i = 0; i < 1000; i++){
try{
Log.d("ExportarVendasService", String.valueOf(i));
Thread.sleep(100);
}catch(Exception ex){
Log.d("ExportarVendasService", ex.getMessage());
}
}*/
}


}



LogCat:

04-09 00:08:15.979: D/Exportar VendasService(1548): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:16.729: W/jdwp(1548): Debugger is telling the VM to exit with code=1
04-09 00:18:16.729: I/dalvikvm(1548): GC lifetime allocation: 9893 bytes
04-09 00:18:22.568: E/Trace(1564): error opening trace file: No such file or directory (2)
04-09 00:18:23.098: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=0&cliente=Trucks&latitude=-21.322131&longitude=23.54332
04-09 00:18:23.238: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.258: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=0&cliente=Trucks&latitude=-21.322131&longitude=23.54332
04-09 00:18:23.339: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.359: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=0&cliente=Trucks&latitude=-21.322131&longitude=23.54332
04-09 00:18:23.418: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.429: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=0&cliente=Trucks&latitude=-21.322131&longitude=23.54332
04-09 00:18:23.459: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.469: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=0&cliente=Trucks&latitude=-21.322131&longitude=23.54332
04-09 00:18:23.498: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.539: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=0&cliente=Trucks&latitude=-21.322131&longitude=23.54332
04-09 00:18:23.578: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.598: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=1&cliente=Trucks&latitude=-21.0&longitude=23.0
04-09 00:18:23.639: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.669: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=1&cliente=Trucks&latitude=-21.0&longitude=23.0
04-09 00:18:23.718: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.718: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=1&cliente=Trucks&latitude=-21.0&longitude=23.0
04-09 00:18:23.759: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.759: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=1&cliente=Trucks&latitude=-21.0&longitude=23.0
04-09 00:18:23.799: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
04-09 00:18:23.819: D/Exportar VendasService(1564): http://localhost/vendas/inserir.php?produto=1&cliente=Trucks&latitude=-21.0&longitude=23.0
04-09 00:18:23.849: D/Exportar VendasService(1564): failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)



15 Respostas


O LogCat passado na abertura do topico o app foi executando no dispositivo Virtual.
O LogCat no link abaixo foi executando no celular SmartPhone Motorola Razr D3 (XT920) - Android 4.4.2, que também não consegue exporta os dados para o BD.

http://rlsystem.com.br/forum/disco/uploads/4fad27de25e19e9ad01b8d9912221e67-logcelular completo.txt

Segue o inserir.php:


error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
mysql_connect("localhost", "root", "");
mysql_select_db("vendas");
$SQL = "INSERT INTO venda (produto, cliente, latitude, longitude)
VALUES ('".$_GET["produto"]."', '".$_GET["cliente"]."', '".$_GET["latitude"]."', '".$_GET["longitude"]."')";
mysql_query($SQL);

if(mysql_affected_rows() > 0){
echo "Y";
}else{
echo "N";
}
?>



Segue Manifest:

[XML]

package="com.example.vendas"
android:versionCode="1"
android:versionName="1.0" >

android:minSdkVersion="8"
android:targetSdkVersion="8"/>













android:required="true"/>

android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name=".MainActivity"
android:label="@string/app_name" >



















android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyB_QH92u-I_MTc8Lwk3AI3M6sNSnbYfD88"/>








[/XML]













android:required="true"/>

android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name=".MainActivity"
android:label="@string/app_name" >



















android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyB_QH92u-I_MTc8Lwk3AI3M6sNSnbYfD88"/>








[/XML]">!-->




package="com.example.vendas"
android:versionCode="1"
android:versionName="1.0" >

android:minSdkVersion="8"
android:targetSdkVersion="8"/>













android:required="true"/>

android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name=".MainActivity"
android:label="@string/app_name" >



















android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyB_QH92u-I_MTc8Lwk3AI3M6sNSnbYfD88"/>




















android:required="true"/>

android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name=".MainActivity"
android:label="@string/app_name" >



















android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyB_QH92u-I_MTc8Lwk3AI3M6sNSnbYfD88"/>








">!-->



Ola Jose

vc esta usando skype??




Ola André

Estou usando o WampServer (Apache 2.4.9 / PHP 5.5.12 / MySQL 5.6.17).




mas vc tem skype instalado???




Ah ta.. Rsrs.. Tenho o skype instalado sim!




carlossmalta@hotmail.com




opa Carlos..

ta ai pq naum esta funcionando

mude a porta do wamp server

veja este link

http://virgiliocpontes.blogspot.com.br/2014/04/mudar-porta-do-apache-no-wampserver.html




Consegui resolver Andre, sem alterar a porta do WampServer.

Instalei o WampServer e criei o BD e as tabelas no meu computador da empresa onde trabalho, pois la tem IP fixo de internet. Criei um servidor virtual no roteador direcionando o IP do computador que instalei o WanpServer e a porta 80 usada pelo mesmo. No meu notebook pessoal de casa onde estudo o projeto no eclipse, alterei o localhost do "http://localhost/vendas/inserir.php?produto=");" pelo IP fixo de internet da empresa "http://IP_FIXO_INTERNET_EMPRESA/vendas/inserir.php?produto=");" e funcionou corretamente no SmartPhone e no Dispositivo Virtual.
Obs.: Tenho skype instalado nos dois computadores e não deu nenhum conflito, não precisei alterar a porta do WampServer.
Como não entendo muito de servidores Web, gostaria de saber se tem possibilidade de fazer estes testes usando o WampServer no meu notebook pessoal de casa, porem não tenho IP Fixo de Internet.




Ola José

pensava q vc estivesse utilizando o da sua casa

claro q tem... é so mudar o localhost para 127.0.0.1




Ola Andre,

Eu estava usando somente no notebook em casa mesmo, porem como estava com o problema que postei neste topico, acabei fazendo desta outra forma pra ver se funcionava, se tinha algum problema no meu codigo.

Intão como vc me instruiu sobre a porta do skype, para não precisar usar o pc da empresa, alem de desinstalar o skype, fiz a alteração da porta do WampServer para 8080 e não deu certo, alterei para porta 82 e continua não dando certo não conseguindo conectar ao server conforme log do logcat abaixo e copia do meu codigo.


package com.example.vendas;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.util.Log;

public class ExportarVendasService extends Service implements Runnable {

public void onCreate() {
new Thread(ExportarVendasService.this).start();
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

public void run() {

SQLiteDatabase db = openOrCreateDatabase("vendas.db", Context.MODE_PRIVATE, null);

Cursor cursor = db.rawQuery("SELECT * FROM venda", null);

int totalDB = cursor.getCount();
int totalReplicado = 0;

while(cursor.moveToNext()){
StringBuilder strURL = new StringBuilder();
strURL.append("http://127.0.0.1:82/vendas/inserir.php?produto="); //IP fixo do Servidor local
strURL.append(cursor.getInt(cursor.getColumnIndex("produto")));
strURL.append("&cliente=");
strURL.append(URLEncoder.encode(cursor.getString(cursor.getColumnIndex("cliente"))));
strURL.append("&latitude=");
strURL.append(cursor.getDouble(cursor.getColumnIndex("la")));
strURL.append("&longitude=");
strURL.append(cursor.getDouble(cursor.getColumnIndex("lo")));
Log.d("Exportar VendasService", strURL.toString());
try{
URL url = new URL(strURL.toString());
HttpURLConnection http = (HttpURLConnection) url.openConnection();
InputStreamReader ips = new InputStreamReader(http.getInputStream());
BufferedReader line = new BufferedReader(ips);

String linhaRetorno = line.readLine();

if(linhaRetorno.equals("Y")){
db.delete("venda", "_id=?", new String[]{String.valueOf(cursor.getInt(0))});
totalReplicado ;
Log.d("Exportar VendasService", "OK");
}

}catch(Exception ex){
Log.d("Exportar VendasService", ex.getMessage());
}
}

db.close();
stopSelf();
if(totalDB == totalReplicado);

/*for (int i = 0; i < 1000; i ){
try{
Log.d("ExportarVendasService", String.valueOf(i));
Thread.sleep(100);
}catch(Exception ex){
Log.d("ExportarVendasService", ex.getMessage());
}
}*/
}
}




LogCat:

http://rlsystem.com.br/forum/disco/uploads/fd4e2c2eef043ca7973a2651afe73ad6-Erro.txt




Ola Jose

se vc desinstalou o skype

naum é preciso mudar a porta ..

so é preciso mudar a porta se vc esta utilizando o skype




e use no seu emulador :)

vc pode instalar o genymotion

q é o emulador mais rapido

veja o meu blog

http://andreleonis.blogspot.com.br/2014/08/genymotion-com-eclipse.html

http://andreleonis.blogspot.com.br/2014/12/como-colocar-genymotion-no-android.html




Antes de alterar a porta eu somente desinstalei o skype e testei, porem o erro continuou e por isso mudei a porta também para testar.

Vou instalar este emulador pra fazer o teste.