How to pick a phrase value in String

Asked

Viewed 694 times

2

example have a return this way from Webservice

"Success! Saved user. Id: 257"

all right I’m picking up the phrase as : Success! Saved user. Id: 257

need only take the number or is to take the 257 the phrase only serves to confirm if you made the recording

My Code is 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);

}

2 answers

6


You can use the method split class String.

If the phrase is in a string with the name Message:

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

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

1

There are several ways to perform this operation!

Follow an example using substring and index

In this case, we will find the Character position ':' through the method index .

Knowing your position, we’ll take the part of String that interests us (from : until the end) with the substring

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

With the method Trim we remove the 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!");
     }

See code running on Ideone!

Browser other questions tagged

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