1
I wanted to integrate my Android project with my Web Project in Jsp.. When I try to download data from Web to android from this error:
Fatal Exception: main java.lang.Stringindexoutofboundsexception: lenght=43; regionStart =0; regionLenght=-1
I did some tests and saw that the error is in the Receive class in the method of Ackground() triggering the excesses "Ioexception"
Receive class receiving data
package br.com.itb.teem.agenda;
import java.io.IOException;
import java.util.Scanner;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
/*class OperacaoAlgumaCoisaWebServiceAsyncTask
extends AsyncTask<Void, Void, Void> {
}
* Vendo a implementação desta classe percebemos que precisamos definir alguns tipos “Generic”.
* Para o exemplo acima, colocamos todos como Void. Vamos entender para que serve cada tipo:
* Primeiro Generic(Params) : o tipo que pode ser enviado para a thread background desse mecanismo, ou seja, o método doInBackground.
* Segundo Generic(Progress): o tipo que pode ser usado para usar com finalidade de enviar o progresso de alguma execução da thread background.
* Terceiro Generic(Result) : o tipo de retorno da thread background. */
public class RecebeJSP extends AsyncTask<Integer, Double, String> {
private Activity ctx;
private ProgressDialog progress;
public RecebeJSP(Activity ctx) {
this.ctx = ctx;
}
//onPreExecute() – É executado antes do doInBackground().
protected void onPreExecute() {
progress = ProgressDialog.show(ctx, "Aguarde...", "Baixando dados da web!!!", true);
}
// doInBackground(Params…)– A thread background. É chamado quando o onPreExecute finaliza.
protected String doInBackground(Integer... params) {
StringBuilder sb = new StringBuilder();
try {
HttpClient httpclient = new DefaultHttpClient();
String endereco = "http://localhost:8085/projetoWeb/listaContatosOra.jsp";
//String endereco = "http://localhost:8080/projetoWeb/listaContatosOra.jsp";
Log.i("URL", endereco);
HttpGet httpget = new HttpGet(endereco);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
Scanner s = new Scanner(entity.getContent());
while (s.hasNext()) {
sb.append(s.next());
}
}
Log.i("Finalizou... ","Fim");
} catch (ClientProtocolException e) {
sb.append(e.getMessage());
} catch (IllegalStateException e) {
sb.append(e.getMessage());
} catch (IOException e) {
sb.append(e.getMessage());
}
return sb.toString();
}
//onPostExecute(Result)– Invocado depois que a thread principal finaliza e esta retorna algum valor como parâmetro para este método.
protected void onPostExecute(String result) {
progress.dismiss();
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
String[] matrizTela= new String[5];
String LinhaDados = null;
//aqui ele pega a quantidade de carcteres que tem uma determinada variável
//e armazena numa INT para usá-la de contador
int contador = result.length();
String total =result.substring(result.indexOf("{")+1,result.indexOf("}"));
Log.i("Tot. Reg.: ", total);
Log.i("Tot. Car.: ", String.valueOf(contador));
int PosIni = 0;
int PosFin = 0;
String Pos1, Pos2, Pos3, Pos4, Pos5;
//cria um for( para fazer uma varredura letra por letra até encontrar
for(int i = 0;i<contador;i++)
{
//usamos substring pra pegar um caractere, passando como parâmetro,
//o primeiro caractere a ser pega, até a ultima.
//fiz um if para verificar se o caractere é igual a "?"
if (result.substring(i,i+1).equals("?")){
{
Log.i("i : ", String.valueOf(i));
Log.i("PosIni: ", String.valueOf(PosIni));
Log.i("PosFin: ", String.valueOf(PosFin=i));
LinhaDados = result.substring(PosIni,PosFin).trim();
LinhaDados = LinhaDados.replaceAll("[&]", " ");
Log.i("String: ", LinhaDados);
PosIni = PosFin+1;
/*Caso utilize a Classe Split.java que realiza a separação dos dados
* Split separados;
* separados = new Split();
* matrizTela = separados.separaDados(LinhaDados, "|"); */
//Utilizando a metodo Split nativo do Java
//Exemplo nomeString.split(limit);
matrizTela = LinhaDados.split("[|]");
//Retorna cada campo em uma posicao
Pos1 = matrizTela[0].toString();
Pos2 = matrizTela[1].toString();
Pos3 = matrizTela[2].toString();
Pos4 = matrizTela[3].toString();
Pos5 = matrizTela[4].toString();
//Exibindo no console (Logcat)
Log.i("Pos1 : ", Pos1);
Log.i("Pos2 : ", Pos2);
Log.i("Pos3 : ", Pos3);
Log.i("Pos4 : ", Pos4);
Log.i("Pos5 : ", Pos5);
//Declarando a classe de controle de conexao
DatabaseHandler db = new DatabaseHandler(ctx);
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact( Pos2, Pos3, Pos4, Pos5);
}
}
}
}
}
Class Android Databasehandler also to receive data
package br.com.itb.teem.agenda;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
@SuppressLint("DefaultLocale")
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "Agenda.db";
// Agenda table name
private static final String TABLE_AGENDA = "agenda";
// ContAgenda Table Columns names
private static final String KEY_ID = "_id";
private static final String KEY_NOME = "nome";
private static final String KEY_EMAIL = "email";
private static final String KEY_FONE = "fone";
private static final String KEY_SEXO = "sexo";
// Produto table name
private static final String TABLE_PROD = "produto";
// Produto Table Columns names
private static final String KEY_PRO_ID = "_id";
private static final String KEY_PRO_DESC = "descricao";
private static final String KEY_PRO_CAT = "categoria";
private static final String KEY_PRO_VL = "valor";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
public void onCreate(SQLiteDatabase db) {
//Criar Tabela agenda
String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_AGENDA + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NOME + " VARCHAR(40), "
+ KEY_EMAIL + " VARCHAR(30), "
+ KEY_FONE + " VARCHAR(10), "
+ KEY_SEXO + " VARCHAR(01));";
db.execSQL(CREATE_TABLE);
//Criar Tabela produto
CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_PROD + " ("
+ KEY_PRO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_PRO_DESC + " VARCHAR(40), "
+ KEY_PRO_CAT + " VARCHAR(20), "
+ KEY_PRO_VL + " NUMERIC(6,2));";
db.execSQL(CREATE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_AGENDA);
// Create tables again
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROD);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
@SuppressLint("DefaultLocale") // Adding new contact
void addContact(String nome, String email, String fone, String sexo) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOME, nome.toUpperCase());
values.put(KEY_EMAIL, email.toLowerCase());
values.put(KEY_FONE, fone);
values.put(KEY_SEXO, sexo);
// Inserting Row
db.insert(TABLE_AGENDA, null, values);
db.close(); // Closing database connecting
}
// Updating single contact
public int updateContact(int id, String nome, String email, String fone, String sexo) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOME, nome.toUpperCase());
values.put(KEY_EMAIL, email.toLowerCase());
values.put(KEY_FONE, fone);
values.put(KEY_SEXO, sexo.toUpperCase());
// updating row
return db.update(TABLE_AGENDA, values, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
}
// Deleting single contact
public void deleteContact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_AGENDA, KEY_ID + " = ?",
new String[] { String.valueOf(id)});
db.close();
}
// Deleting all contact
public void deleteAllContact() {
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("DELETE FROM " + TABLE_AGENDA);
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_AGENDA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = 0;
try {
if (cursor.moveToFirst()) {
count = cursor.getCount();
}
return count;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
// Getting All Contacts
public List<Agenda> getAllContacts() {
List<Agenda> contactList = new ArrayList<Agenda>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_AGENDA;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Agenda agenda = new Agenda();
agenda.setID(Integer.parseInt(cursor.getString(0)));
agenda.setNome(cursor.getString(1));
agenda.setEmail(cursor.getString(2));
agenda.setFone(cursor.getString(3));
agenda.setSexo(cursor.getString(4));
// Adding contact to list
contactList.add(agenda);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
Jsp class
<%--
Document : Seleciona Registros
Created on : 10/03/2015, 17:35:37
Author : Alberti
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="classeConexao.*"%>
<%@ page import="java.sql.*"%>
<%
//(" ESTOU NA PAGINA JSP - CONECTANDO NO BANCO E EXECUTANDO A SELECT...");
Conexao conexao = new Conexao();
String sql = "SELECT * FROM CADASTROWEB ORDER BY NOME";
int registros = 0;
try{
ResultSet dados = conexao.ponte.executeQuery(sql);
//(" EXECUTEI A SELECT, CARREGANDO INFORMACOES NA PAGINA...");
while(dados.next())
{
out.print(dados.getInt(1));
out.print("|"+dados.getString(2));
out.print("|"+dados.getString(3));
out.print("|"+dados.getString(4));
out.print("|"+dados.getString(5)+"?");
registros++;
}
dados.close();
}
catch(Exception e)
{
out.println(e.getMessage());
}
//(" INFORMANDO A QUANTIDADE DE REGISTROS INSERIDOS NA PAGINA... ")".
out.print("#{" + registros + "}" );
//(" TERMINEI DE CARREGAR AS INFORMACOES NA PAGINA...");
%>
Can you point to the specific line in the code? I didn’t see anything very obvious in the function you pointed out from the specified class... And could also add the
stacktrace?– Jefferson Quesado
httpresponse Response = httpclient.execute(httpget);
– Marcus Vinicius
Right, what about the
stacktrace? Can you add to the question?– Jefferson Quesado
Maybe if instead of capturing the exception and only show the exception message you print the
stacktracemake it easier to track. I think it would bee.printStackTrace(out);inside the blockcatch– Jefferson Quesado
I’m not sure what stacktrace is, sorry.
– Marcus Vinicius
Example of
stacktrace: https://answall.com/q/99755/64969– Jefferson Quesado
Displaying the
stacktracein the console log: https://answall.com/q/616/64969– Jefferson Quesado
is an orange in Logcat?
– Marcus Vinicius
org.apache.http.conn.Httphostconnectexception: Connection to http://localhost:8085 refused
– Marcus Vinicius
Thanks Jefferson, through your comment I could go after the solution..
– Marcus Vinicius