Convert String to Integer on Android

0

Galera, I had already opened a question regarding this subject but in java ( Here ), I could not solve it and now in an android apk I have the same problem.

I have a service with a thread running a socket server, in it using ResultReceiver match the information to a textview, this information is String's from a java client on the pc, in order to manipulate this data received using a switch I want to convert the String to an integer (If you have another way to do ...).

But in the conversation using the method parseInt the application of the error, What I'm programming from a pc with less than 1gb of ram, can not open the emulator so little see the error log. Besides the more like and socket connection the android eclipse emulator does not have the ability to emulate wifi. I know it was an error when converting. I commented this section and the program ran normal.

I do not know if this is the correct way to manipulate the received data, but I think it does not disturb the main thread;

If someone can test and see why the conversion is not successful, or if someone already knows the problem by looking at the code and can identify, the codes are as follows:

Here is the service class that runs the thread with the socket server

package com.example.palioteste;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;

public class ServidorSocketIntent extends IntentService{

    public int porta = 9955;
    public Socket conexao;
    public boolean ativo;
    public String clientSentence;
    private ResultReceiver rr;


    public ServidorSocketIntent() {

        super("ServidorSocketIntentThread");

        ativo = true;
        clientSentence = "";

    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId){


     rr = intent.getParcelableExtra("receiver");

   return(super.onStartCommand(intent, flags, startId));
    }



    @Override
    protected void onHandleIntent(Intent intent) {


        ServerSocket welcomeSocket = null;
           try {
            welcomeSocket = new ServerSocket(porta);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

while (ativo) {
    try{   

  Socket connectionSocket = null;
        conexao = welcomeSocket.accept();


   BufferedReader inFromClient = null;

    inFromClient = new BufferedReader(new InputStreamReader( conexao.getInputStream() ));

    clientSentence = inFromClient.readLine();

    //clientSentence = inFromClient.readLine();

    Bundle b = new Bundle();
    b.putString("resposta", clientSentence);

    rr.send(1, b);

    } catch(Exception e ){

    } 

    try {
        conexao.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}


    }

}

Here is the MainActivity:

package com.example.palioteste;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.ResultReceiver;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements ServiceConnection{

        private ServiceConnection connection;    
        private RespostaCliente respostafinal;
        private ImageButton imageButtonLigar;
        private ImageButton imageButtonDesligar;
        static TextView feedback;
        private  ResultReceiverListener rr;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       connection = this;



       imageButtonLigar = (ImageButton) findViewById(R.id.imageButtonLigar);

        imageButtonDesligar = (ImageButton) findViewById(R.id.imageButtonDesligar);

        feedback = (TextView) findViewById(R.id.feedback);


        imageButtonLigar.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {


        abrirSocket rodar = new abrirSocket("2");
                rodar.execute();

                imageButtonLigar.setVisibility(View.INVISIBLE);
                imageButtonDesligar.setVisibility(View.VISIBLE);        
            }

        });



        imageButtonDesligar.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {



                abrirSocket rodar = new abrirSocket("3");
                rodar.execute();

                imageButtonLigar.setVisibility(View.VISIBLE);
                imageButtonDesligar.setVisibility(View.INVISIBLE);  
            }

        });

        //bindService(new Intent("Socket_Resposta"),connection , Context.BIND_AUTO_CREATE);//Context.BIND_AUTO_CREATE
        //inicia o servico binder para obter conexao com a thread rodando dentro do servico

          startService();





    }





    public void startService(){

        rr = null;
        rr = new ResultReceiverListener(null);


        Intent it = new Intent ("Socket_RespostaIntent");
        it.putExtra("receiver", rr);

        startService(it);

        }


    public void stopService (View view){
        Intent it = new Intent ("Socket_RespostaIntent");
        stopService(it);
        it.putExtra("desligar", 1);
        startService(it);

    }

    /*public void startService(View view){
        Intent it = new Intent("Servico_Teste");
        startService(it);
    }
    */


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }






    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }




    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

    }


    @Override
    public void onServiceDisconnected(ComponentName name) {

    }


    private class ResultReceiverListener extends ResultReceiver{
          public ResultReceiverListener(Handler handler) {
            super(handler);
        }

    @Override
        protected void onReceiveResult(int resultcode, Bundle bundle){

           if (resultcode == 1){
           final String resposta = bundle.getString("resposta");

        //metodo que recebe a resposta e atualiza a ui
           runOnUiThread(new Runnable(){
          public void run(){
             // feedback.setText("Resposta do Cliente: "+ resposta);
               int respostaint = Integer.parseInt(resposta);

          switch(respostaint){

         case 1:
            feedback.setText("O resultado e 1");
            \executa outros metodos             

           break;

         case 2:
           feedback.setText("Resposta 2");
          \executa outras funcoes
           break;

}

          }
                    });
                }
        }


    }



}

Here's Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.palioteste"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="16" />

        <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>



    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:screenOrientation="landscape"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:label="ServidorSocket" android:name="ServidorSocket">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
                <action android:name="Socket_Resposta"/>
            </intent-filter>
        </service>
        <service android:label="ServidorSocketIntent" android:name="ServidorSocketIntent">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
                <action android:name="Socket_RespostaIntent"/>
            </intent-filter>
        </service>
    </application>

</manifest>
    
asked by anonymous 04.10.2017 / 23:23

2 answers

2

First check that the string is not null, as this will cause an error, since there is no empty number. Then do the conversion inside a try to be able to do treatments:

if(sNum!=null)
  try {
   int num = Integer.parseInt(sNum)
 }
 catch(NumberFormatException e){
   //Log.i();
 }
    
04.10.2017 / 23:58
0

It is best to use a google lib that is guava.

Git link

To add:

dependencies { compile 'com.google.guava:guava:23.1-jre' // or, for Android: compile 'com.google.guava:guava:23.1-android' }

So to do this conversion is enough:

Integer tryParse(String string)

Example usage:

Integer number = Ints.tryParse("23");

No need for null validation, empty and possible exception.

    
12.10.2017 / 11:58