How to get a value from a sentence in String

2

example I have a return of that WebService mode

  

"Success! User saved Id: 257"

All right, I'm getting the phrase like: Success! User saved. Id: 257

I just need to get the number or get the 257 the sentence is only used to confirm if you have done the recording

My code looks like this:

private void Cadastro(String login, String senha) {
    showProgressDialog();

    StringRequest strReq = new StringRequest(Request.Method.GET,
            Const.URL_CADASTRO_USUARIO+"/"+login+"/"+senha, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response.toString());
        //    msgResponse.setText(response.toString());
            hideProgressDialog();

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hideProgressDialog();
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

}
    
asked by anonymous 06.10.2014 / 16:42

2 answers

6

You can use the split class String .

If the phrase is in a string named Message:

String[] partes = Mensagem.split(":");

partes[0]; // terá: Sucesso! Usuario salvo. Id 
partes[1].trim(); // terá: 257
    
06.10.2014 / 17:38
1

There are several ways to do this!

Here's an example using substring and indexOf

In this case, we will find the character position ':' through the indexOf method.

Knowing your position, let's take the part of String that interests us (from: to the end) with substring

The method indexOf returns the exact position so we will take a house forward.

Using the method trim we remove spaces in bank:

  /*
   * Retorno que iremos trabalhar 
   */
   final String retorno = "Sucesso! Usuario salvo. Id: 257";

   // Pegamos a posição do : na String
   int posicaoDoisPontos = retorno.indexOf(':');

   // Caso ão ache os : na STring irá retornar -1
   if(posicaoDoisPontos > -1){
         // Vamos pegar a psoição a frente do : até o fim da String (seu tamanho)
         String idLiteral =  retorno.substring( (posicaoDoisPontos+1) , retorno.length() );
         // Transformamos a String em Integer
         Integer id = Integer.valueOf(idLiteral.trim());
         System.out.println(id);
    }else{
          System.out.println("Não foi possível formatar o valor!");
     }

View the code running on Ideone!

    
19.12.2016 / 16:39