Separate address path from string

Asked

Viewed 1,039 times

2

On my application JAVA, on a screen, I have fields referring to the address, I have two means of registering this address, I can pick up automatically searching for the zip code most of the information or putting everything "manually".

The problem, is that often the zip code will not return you a result, or returns only some information, as is the case of the place where I live (it is a small District). So I decided to leave the option to put manually.

In the Database, I save separately Type and Name of Street.

To help understand the fields: Field Type of the patio (comboBox): Avenue, Street, Road and etc.

Field name of the Street: Paraná, Cruzeiro, Rio Grande do Sul and etc;

Seeking the zip code automatically it will fill the field referring to the name of the street. It will fill the field for example with Paraná Avenue. Automatically picking up it does not distinguish type of name. If save the data "taken" automatically, when the query is performed, it will not set in the fields referring to each content, example: Avenue arrow in combo and Paraná in TextField (street name).

What I want is to be able to separate the type from the name (take the avenue). The purpose of having this comboBox (type of street), is for when the inclusion is "manual", the user does not start to register the same type of street in different ways, as for example: Avenue, Av., Avn, Avenue, avenue and etc.

If there is a way I can meet these conditions in a simpler or different way, I am accepting suggestions.

I tried to separate using split(), but it does not distinguish the position, perhaps aggregating regular expression would be possible ?

Obs: in the simple example I put below, I did not put the option to pick automatically, since what I need is to know how to separate the contents inside the string.

Note: If the question is still "weird", I remove.

A very simple example of what I tried would be:

package testeCombo;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MainCombo extends JFrame implements ActionListener
{   
    private final String logradouro[] = {"<Selecione>", "Avenida", "Rua", "Estrada"};

    private JComboBox cmb = new JComboBox();
    private JTextField tf = new JTextField();    
    JPanel painel = new JPanel();
    JPanel painelBotao = new JPanel();
    private final JButton incluir = new JButton("OK");
    private final JButton consultar = new JButton("CONSULTAR");         
    private String salvaBD = "";
    JLabel label = new JLabel();
    JLabel label2 = new JLabel();

    public MainCombo() 
    {     
        setTitle("Combo + Text");
        setSize(550, 150);
        setResizable(false);         

        cmb = new JComboBox(logradouro);
        tf = new JTextField();        
        tf.setPreferredSize(new Dimension(110, 25));
        painel.add(cmb);
        painel.add(tf);   
        getContentPane().add("South", painelBotao);        
        painelBotao.setLayout(new GridLayout(1, 2));
        adicionaBotao(incluir);
        adicionaBotao(consultar);
        painel.add(label);        
        painel.add(label2);        
        add(painel);     
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void acao()
    {
        cmb.getSelectedItem();
        tf.getText();        
        salvaBD = (cmb.getSelectedItem() + " " + tf.getText());
        label.setText(salvaBD);
        cmb.setSelectedIndex(0);
        tf.setText("");        
    }

    public void consultar()
    {
        separa();
    }

    public void separa()//separa para quando consultar, o logradouro ir para o combo e o nome do logradouro pro TextField
    {     
        /*
        String [] separa = salvaBD.split(" ");
        String separado = separa[0].split(" ")[1];              
        label2.setText(" " + separado); 
        */        
        String[] arrayValores = salvaBD.split(" ");
        label2.setText(" " + Arrays.toString(arrayValores)); 
        //cmb.setSelectedIndex(); //setar valor no textField quando consulta   
        //tf.setValor(salvaBD);  //setar valor no textField quando consulta    
        label.setText("");// so para limpar o outro label
    }


    @Override
    public void actionPerformed(ActionEvent ae)
    {

        if (ae.getSource() == incluir) 
        {            
            acao();
        } 

        if (ae.getSource() == consultar) 
        {            
            consultar();
        } 
    }

    private void adicionaBotao(JButton botao) 
    {
        painelBotao.add(botao);
        botao.addActionListener(this);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(() -> 
        { 
            MainCombo combo = new MainCombo();
            combo.setVisible(true);
        });        
    }

    class textF extends JTextField
    {
        public void setValor(Object valor) 
        {
            setText("" + valor);
        }
    }        
}
  • Missing a lot of street, you know? Look at the post office website. http://www.buscacep.correios.com.br/sistemas/buscacep/buscaCep.cfm

  • Another thing, the query you do where? Generally based Ipps from the post office website return a json, with all the above link fields separated. Your query returns a single string with everything?

  • @diegofm was going to get a lot of stuff, that’s a simple example ! What I saw by that link is paid (the one from the post office). I’m using this one https://gitlab.com/parg/ViaCEP

  • So it’s simple: take the backyard, from a split to the first space, compare the type with all of the list that popularizes the combo and then arrow in the combo when the comparison is true :)

  • @diegofm then, how do I do pro split() pick up only the first position? I tried a few ways there in the example, but it did not work.

  • 1

    See: https://ideone.com/5tfgmF

  • @diegofm In my case, to get from the fields, I’ll have to do something like this : https://ideone.com/cp6ApT, I think for the textField this right, plus the combo ...

  • 1

    You’re complicating something easy. Just make one combo.setSelectedItem(log) before the break loop, and use the street array to populate the combo. You will compare it to the list, not the combo. Combobox accepts to receive an array as initializer, no need to add one by one, a simple new ComboBox(logradouro) already fills it in.

  • @diegofm worked almost right, it just did not arrow back with combo.setSelectedItem(log), I believe it is because I still use addItem, because new Combobox(backyard) did not work. combo.setSelectedItem(patio) tbm does not give.

  • @diegofm theoretically what has in log and backyard is not the msm thing? should not set in the combo then ?

  • 1

    I think our lines of reasoning are following a completely different path. logradouro which I refer to is the array of your code. log is only a temporary representation of each element of that array within the for. I will then try to base myself on the question code and what I showed you on ideone and answer with an example of how I believe it will work.

Show 6 more comments

1 answer

2


If it’s a pattern of every address you refer to (I believe it is, the mail-based Apis are usually like this), to separate the type of street you can use the method split(), passing a space as a separator. Then, from the resulting array, take the first index, it will be the type.

Once with the separate type, just compare with the ones in your array logradouros to select the option in JComboBox.

Based on your example, I made changes to 2 methods only, to illustrate:

public void consultar() {
    String retorno = JOptionPane.showInputDialog("Consulta");
    separa(retorno);
}

public void separa(String retorno) {

    if (retorno != null) {
        retorno = retorno.trim();
        String logTipo = retorno.split(" ")[0];

        for (String log : logradouros) {
            if (log.equalsIgnoreCase(logTipo)) {
                cmb.setSelectedItem(log);
                break;
            }
        }
        label2.setText(retorno.substring(retorno.indexOf(" "), retorno.length()));
        cmb.setEnabled(false);

    }
}

Notice that I used equalsIgnoreCase to avoid comparisons such as "street" and "street" false returns.

With these changes, the code works this way:

inserir a descrição da imagem aqui

On the line:

label2.setText(retorno.substring(retorno.indexOf(" "), retorno.length()));

I am separating the rest of the backyard without the type, cutting the address string from the first space right after the type until the end. The trim() is to remove unnecessary spaces at the beginning and end of the string.

  • It presents me with a mistake, but it does not make the application to work, so I think it has no problem, more, just for conscience disengagement, is it because it leaves the condition of the go at some point? The error is: Exception in thread "AWT-Eventqueue-0" java.lang.Stringindexoutofboundsexception: String index out of range: -1 at java.lang.String.substring(String.java:1960) (...)

  • @Gustavosantos indexof returns -1 if it does not find the charsequence entered as parameter, in the case of this code, the blank space. Check in which type of address this occurs, if there is no blank space as separate between type and street, nor the split will work.

  • Despite the error it continues to work, the error occurs when I set the name of the street that is already separated. fieldNomeLogradouro.setText(return.substring(return.indexof(" "), return.length()));

  • 1

    @Gustavosantos anyway, needs to be solved. If you have no way to ensure that the address always arrives in format tipo logradouro(separated by a space), then this line must be removed and the easiest in this case is to fill the field with the whole string

  • 1

    all right, I’ll still try to solve, in case I don’t solve, I’ll change the way you do as you’re suggesting, thank you ! :)

Browser other questions tagged

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