Trazer o resultado de um banco firebird no android, usando DataSnap do Delphi? [RESOLVIDO]

4 respostas
A

Consegui trazer os dados usando este video aula
http://rafakwolf.blogspot.com.br/2012/04/aplicacoes-android-conectando-delphi.html

Peguei a lista dos dados do banco firebird e esta tudo num listview do android.

Até na parte de trazer a lista de todos os dados da tabela no android esta trazendo, mas preciso fazer o mesmo num edittext digitar um codigo no edittext e neste mesmo edittext retornar o nome.

Tenho uma tabela chamada clientes, e nela tenho os campos CODIGO e NOME

Se algem puder me ajudar a trazer o resultado dentro do edittext do android...

No delphi ja fiz o método de busca pelo ID
function TServerMethods1.GetDados_Clientes(Codigo: string; out Erro: string): TDataSet;
begin
  with CDS_Clientes do
  begin
    try
      Close;
      CommandText := ' SELECT CAST(CODIGO AS VARCHAR(30))AS CODIGO, NOME '+
                     '   FROM CLIENTES '+
                     '  WHERE CODIGO = :PCODIGO ';
      Params.ParamByName('PCODIGO ').AsString := Codigo;
      Open;
      Result := CDS_Clientes;
    except on E:Exception do
      Erro := E.Message;
    end;
  end;
end;
e no android ficou assim
public static class GetDados_ClientesReturns {
      public String Erro;
      public TDataSet returnValue;
    }
    public GetDados_ClientesReturns GetDados_Clientes(String Codigo) throws DBXException {
      DSRESTCommand cmd = getConnection().CreateCommand();
      cmd.setRequestType(DSHTTPRequestType.GET);
      cmd.setText("TServerMethods1.GetDados_Clientes");
      cmd.prepare(get_TServerMethods1_GetDados_Clientes_Metadata());
      cmd.getParameter(0).getValue().SetAsString(Codigo);
      getConnection().execute(cmd);
      GetDados_ClientesReturns ret = new GetDados_ClientesReturns();
      ret.Erro = cmd.getParameter(1).getValue().GetAsString();
      ret.returnValue = (TDataSet)cmd.getParameter(2).getValue().GetAsTable();
      return ret;
    }
    
    
    private DSRESTParameterMetaData[] TServerMethods1_InsertDados_Clientes_Metadata;
    private DSRESTParameterMetaData[] get_TServerMethods1_InsertDados_Clientes_Metadata() {
      if (TServerMethods1_InsertDados_Clientes_Metadata == null) {
        TServerMethods1_InsertDados_Clientes_Metadata = new DSRESTParameterMetaData[]{
          new DSRESTParameterMetaData("Nome", DSRESTParamDirection.Input, DBXDataTypes.WideStringType, "string"),
          new DSRESTParameterMetaData("Erro", DSRESTParamDirection.Output, DBXDataTypes.WideStringType, "string"),
          new DSRESTParameterMetaData("", DSRESTParamDirection.ReturnValue, DBXDataTypes.BooleanType, "Boolean"),
        };
      }
      return TServerMethods1_InsertDados_Clientes_Metadata;
    }

Mais não sei como chamar no android

Cheguei a montar o codigo, mais não esta correto
private void pesquisar() {
        dialog = progressDialog.show(VendaClienteActivity.this, "Aguarde...",
                "Pesquisando registros");

        new Thread() {
            @Override
            public void run() {
                DSRESTConnection conn = getConnection();
                TServerMethods1 serv = new TServerMethods1(conn);
                
                GetDados_ClientesReturns gc;
                
                TDataSet ds = null;
                
                try {
                    String Codigo;
                    Codigo = edtCliente.getText().toString();
                    gc = serv.GetDados_Clientes(Codigo);
                    
                    //carrega o edit com o resultado do select
                    edtCliente.setText(ds.getValue("nome").GetAsString());
                    
                    finalizaDialogo(false, "");
                    
                } catch (Exception e){
                    finalizaDialogo(true, e.toString());
                }
            }       
            
        }.start();

    }
    
    private DSRESTConnection getConnection() {
        DSRESTConnection conn = new DSRESTConnection();
        conn.setHost(ip);
        conn.setPort(1032); //porta     
        
        return conn;
    }
    
    private void finalizaDialogo(final boolean temErro, final String msg) {
        handler.post(new Runnable() {
            
            @Override
            public void run() {
                if (temErro)
                    Toast.makeText(VendaClienteActivity.this, msg, Toast.LENGTH_LONG).show();
                else
                    AtualizarTela();
                //finaliar o dialogo
                dialog.dismiss();
            }           
        });     
    }
    
    private void AtualizarTela() {
        //
        
    }

Minha dificuldade é passar o parametro do codigo para buscar o ID do cliente e retornar o nome do cliente no edittext.

Obrigado a quem me ajudar.

4 Respostas

A
Mudei o select la no delphi
function TServerMethods1.GetDados_Clientes(Codigo: string; out Nome: string): string;
begin
  with CDS_Clientes do
  begin
    Close;
    CommandText := ' SELECT CAST(CODIGO AS VARCHAR(30))AS CODIGO, NOME '+
                   '   FROM CLIENTES '+
                   '  WHERE CAST(CODIGO AS VARCHAR(30))AS CODIGO = '+ QuotedStr(Codigo);
    Open;
    Nome := FieldByName('NOME').AsString;
    Result := Nome;
  end;
end;
A classe do proxy
public GetDados_ClientesReturns GetDados_Clientes(String Codigo) throws DBXException {
      DSRESTCommand cmd = getConnection().CreateCommand();
      cmd.setRequestType(DSHTTPRequestType.GET);
      cmd.setText("TServerMethods1.GetDados_Clientes");
      cmd.prepare(get_TServerMethods1_GetDados_Clientes_Metadata());
      cmd.getParameter(0).getValue().SetAsString(Codigo);
      getConnection().execute(cmd);
      GetDados_ClientesReturns ret = new GetDados_ClientesReturns();
      ret.Nome = cmd.getParameter(1).getValue().GetAsString();
      ret.returnValue = cmd.getParameter(2).getValue().GetAsString();
      return ret;
    }
E agora sim consegui trazer o que estava querendo no edittext do android
private void pesquisar() {
		dialog = progressDialog.show(VendaClienteActivity.this, "Aguarde...",
				"Pesquisando registros");
		DSRESTConnection conn = getConnection();
		TServerMethods1 serv = new TServerMethods1(conn);

		try {
			String Codigo = edtCliente.getText().toString();

			GetDados_ClientesReturns ret;

			ret = serv.GetDados_Clientes(Codigo);

			// carrega o edit com o resultado do select
			edtCliente.setText(ret.Nome);

			finalizaDialogo(false, "");

		} catch (Exception e) {
			finalizaDialogo(true, e.toString());
		}

	}

Obrigado pessoal.

A

Só mais uma pequena duvida

Como tratar para que mostre uma mensagem quando o resultado não tiver retorno?

Tentei assim
private void pesquisar() {
		dialog = progressDialog.show(VendaClienteActivity.this, "Aguarde...",
				"Pesquisando registros");
		DSRESTConnection conn = getConnection();
		TServerMethods1 serv = new TServerMethods1(conn);

		try {
			String Codigo = edtCliente.getText().toString();

			GetDados_ClientesReturns ret;

			ret = serv.GetDados_Clientes(Codigo);

			if (ret.Nome == null) {
				Toast.makeText(VendaClienteActivity.this,
						"Cliente não localizado", Toast.LENGTH_LONG).show();
				edtCliente.setFocusableInTouchMode(true);
				edtCliente.requestFocus();
			} else {
				// carrega o edit com o resultado do select
				edtCliente.setText(ret.Nome);
			}

			finalizaDialogo(false, "");

		} catch (Exception e) {
			finalizaDialogo(true, e.toString());
		}

	}
E assim
if (ret.Nome == "") {

Mais nenhum dos dois deu certo, sempre quando não tem dados no resultado não mostra a mensagem.

Obrigado.

A

Outra coisa, alguém sabe como eu faço para digitar no edittext do android e trazer uma lista no listview?

Meu select no delphi eu mudei assim
function TServerMethods1.GetDados_Clientes(Codigo: string; out Nome: string): string;
var
  sSQL: string;
begin
  sSQL := ' SELECT CAST(CODIGO AS VARCHAR(30))AS CODIGO, NOME '+
          '   FROM CLIENTES '+
          '  WHERE ATIVO = ''Sim'' ';
  if IsCode(Codigo) then
    sSQL := sSQL + '  AND CAST(CODIGO AS VARCHAR(30)) = '+ QuotedStr(Codigo)
  else
    sSQL := sSQL + '  AND UPPER(NOME) LIKE ' + AnsiUpperCase(QuotedStr(Codigo + '%'));

  with CDS_Clientes do
  begin
    Close;
    CommandText := sSQL;
    Open;
    Nome := FieldByName('NOME').AsString;
    Result := Nome;
  end;
end;

Preciso ao digitar um nome do edittext do android trazer a lista de todos que contém no LIKE da busca

Me parece que tenho que usar um while para isso, porque fiz assim no android
private void buscaClientes() {
		// limpa a lista a cada pesquisa
		list.clear();

		dialog = progressDialog.show(ClientesListaActivity.this, "Aguarde...",
				"Pesquisando registros");

		DSRESTConnection conn = getConnection();
		TServerMethods1 serv = new TServerMethods1(conn);

		try {
			String Codigo = edBusca.getText().toString();

			GetDados_ClientesReturns ret;

			ret = serv.GetDados_Clientes(Codigo);

			if (ret.Nome == null) {
				Toast.makeText(ClientesListaActivity.this,
						"Profissional não localizado", Toast.LENGTH_LONG)
						.show();
				edBusca.setFocusableInTouchMode(true);
				edBusca.requestFocus();
			} else {

				//Cursor cursor = (Cursor) serv.GetDados_Clientes(Codigo);

				//while (cursor.moveToNext()) {

					HashMap<String, String> item = new HashMap<String, String>();
					item.put("nome", ret.Nome);
					list.add(item);
					AtualizarTela();
				//}
			}

			finalizaDialogo(false, "");

		} catch (Exception e) {
			finalizaDialogo(true, e.toString());
		}
	}
e o método atualizaTela
private void AtualizarTela() {
		String[] from = new String[] { "nome", "id" };
		int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
		int layoutNativo = android.R.layout.two_line_list_item;

		listItens.setAdapter(new SimpleAdapter(this, list, layoutNativo, from,
				to));

	}

Sem o while traz no listview apenas 01 (um) resultado da busca, as linhas comentadas tentei fazer, mais não da certo desta forma ai.

Minha classe que contém os dados que busca os clientes são estas aqui
private DSRESTParameterMetaData[] TServerMethods1_GetDados_Clientes_Metadata;

		private DSRESTParameterMetaData[] get_TServerMethods1_GetDados_Clientes_Metadata() {
			if (TServerMethods1_GetDados_Clientes_Metadata == null) {
				TServerMethods1_GetDados_Clientes_Metadata = new DSRESTParameterMetaData[] {
						new DSRESTParameterMetaData("Codigo",
								DSRESTParamDirection.Input,
								DBXDataTypes.WideStringType, "string"),
						new DSRESTParameterMetaData("Nome",
								DSRESTParamDirection.Output,
								DBXDataTypes.WideStringType, "string"),
						new DSRESTParameterMetaData("",
								DSRESTParamDirection.ReturnValue,
								DBXDataTypes.WideStringType, "string"), };
			}
			return TServerMethods1_GetDados_Clientes_Metadata;
		}

		/**
		 * @param Codigo
		 *            [in] - Type on server: string
		 * @param Nome
		 *            [out] - Type on server: string
		 * @return result - Type on server: string
		 */
		public static class GetDados_ClientesReturns {
			public String Nome;
			public String returnValue;
		}

		public GetDados_ClientesReturns GetDados_Clientes(String Codigo)
				throws DBXException {
			DSRESTCommand cmd = getConnection().CreateCommand();
			cmd.setRequestType(DSHTTPRequestType.GET);
			cmd.setText("TServerMethods1.GetDados_Clientes");
			cmd.prepare(get_TServerMethods1_GetDados_Clientes_Metadata());
			cmd.getParameter(0).getValue().SetAsString(Codigo);
			getConnection().execute(cmd);
			GetDados_ClientesReturns ret = new GetDados_ClientesReturns();
			ret.Nome = cmd.getParameter(1).getValue().GetAsString();
			ret.returnValue = cmd.getParameter(2).getValue().GetAsString();
			return ret;
		}

Obrigado.

A

Resolvido também

No delphi fiz assim o select retornando um DataSet na consulta
function TServerMethods1.ConsultaDadosCliente(Nome: string): TDataSet;
begin
  with CDS_Tabelas do
  begin
    Close;
    CommandText := ' SELECT CAST(CODIGO AS VARCHAR(30))AS CODIGO, NOME '+
                   '   FROM CLIENTES '+
                   '  WHERE ATIVO = ''Sim''  '+
                   '    AND UPPER(NOME) LIKE ' + AnsiUpperCase(QuotedStr(Nome + '%'));
    Open;
    Result := CDS_Tabelas;
  end;
end;
No java o método de busca passando o nome do cliente no parametro de saida e retornando o dataset
public TDataSet ConsultaDadosCliente(String Nome) throws DBXException {
      DSRESTCommand cmd = getConnection().CreateCommand();
      cmd.setRequestType(DSHTTPRequestType.GET);
      cmd.setText("TServerMethods1.ConsultaDadosCliente");
      cmd.prepare(get_TServerMethods1_ConsultaDadosCliente_Metadata());
      cmd.getParameter(0).getValue().SetAsString(Nome);
      getConnection().execute(cmd);
      return (TDataSet) cmd.getParameter(1).getValue().GetAsTable();
    }
chamando o metodo numa thread, passando para o parametro o edittext com nome ou parte do nome do cliente, para retornar na lista.
// busca parte do cliente
	private void buscaClientes() {
		dialog = ProgressDialog.show(ClientesListaActivity.this, "Aguarde...",
				"Pesquisando registros");

		new Thread() {
			@Override
			public void run() {
				DSRESTConnection conn = getConnection();
				TServerMethods1 serv = new TServerMethods1(conn);

				TDataSet ds;
				// limpa a lista a cada pesquisa
				list.clear();
				try {
					ds = serv
							.ConsultaDadosCliente(edBusca.getText().toString());
					while (ds.next()) {
						HashMap<String, String> item = new HashMap<String, String>();
						item.put("nome", ds.getValue("NOME").GetAsString());
						item.put("id", ds.getValue("CODIGO").GetAsString());
						list.add(item);
					}

					finalizaDialogo(false, "");

				} catch (Exception e) {
					finalizaDialogo(true, e.toString());
				}
			}

		}.start();

	}

             private void finalizaDialogo(final boolean temErro, final String msg) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				if (temErro)
					Toast.makeText(ClientesListaActivity.this, msg,
							Toast.LENGTH_LONG).show();
				else
					AtualizarTela();
				// finaliar o dialogo
				dialog.dismiss();
			}
		});
	}

	private void AtualizarTela() {
		String[] from = new String[] { "nome", "id" };
		int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
		int layoutNativo = android.R.layout.two_line_list_item;

		listItens.setAdapter(new SimpleAdapter(this, list, layoutNativo, from,
				to));

	}

Obrigado pessoal, quem precisar fazer algo parecido, esta ai.

Criado 29 de dezembro de 2012
Ultima resposta 4 de jan. de 2013
Respostas 4
Participantes 1