How to send data from an Activity to a class?

1

I have the following code and I want to retrieve the id from a list of only option but when using the getStringExtra("indice") method the data is null

Does anyone know how to fix it please? The code is as follows:

public class MainActivity extends AppCompatActivity{

    private TextView ePromCliSuc,eTimePromSis,eClientesFila,eTimeEspera;
    private String data[];
    private ImageView img1,img2,img3,img4;
    private Hilo hilo;
    private int idHora;
    private ImageButton btnSalir,btnInfo;
    private final String[] horas = {"9:00 - 10:00 ","10:00 - 11:00","11:00 - 12:00",
                                    "12:00 - 13:00", "13:00 - 14:00","14:00 - 15:00","15:00 - 16:00",
                                    "17:00 - 18:00","18:00 - 19:00","19:00 - 20:00"};
    private final String Mensaje = "QueueSimulation es una aplicación cliente " +
                                    "diseñada para recibir datos de la simulacion " +
                                    "de lineas de espera en tiempo.\nAutores: "+
                                    "\nAntonio Lopez Aurelio\nHernandez Islas Adrian";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        asigna();
        actionImagen();
        IntentFilter filtro1 = new IntentFilter(ReceptorOperacion.ACTION_RESP);
        filtro1.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(new ReceptorOperacion(), filtro1);
        hilo = new Hilo();
        hilo.start();

    }

    public void asigna(){
        ePromCliSuc = (TextView) findViewById(R.id.ePromCliSu);
        eTimePromSis = (TextView) findViewById(R.id.eTimeProm);
        eClientesFila = (TextView) findViewById(R.id.eClientesEnFila);
        eTimeEspera = (TextView) findViewById(R.id.eTimeEspera);
        btnSalir = (ImageButton) findViewById(R.id.imageButton2);
        btnInfo = (ImageButton) findViewById(R.id.imageButton3);
        img1 = (ImageView) findViewById(R.id.imageView2);
        img2 = (ImageView) findViewById(R.id.imageView);
        img3 = (ImageView) findViewById(R.id.imageView3);
        img4 = (ImageView) findViewById(R.id.imageView4);


    }

    public void actionImagen(){
        img1.setBackgroundResource(R.drawable.animereloj);
        AnimationDrawable frameAnimation1 = (AnimationDrawable) img1.getBackground();

        img2.setBackgroundResource(R.drawable.animeprom);
        AnimationDrawable frameAnimation2 = (AnimationDrawable) img2.getBackground();

        img3.setBackgroundResource(R.drawable.animecola);
        AnimationDrawable frameAnimation3 = (AnimationDrawable) img3.getBackground();

        img4.setBackgroundResource(R.drawable.animetimeaprox);
        AnimationDrawable frameAnimation4 = (AnimationDrawable) img4.getBackground();

        frameAnimation1.start();
        frameAnimation2.start();
        frameAnimation3.start();
        frameAnimation4.start();
    }
     //Este metodo es el que guarda el valor
    public void pasarDato(int id){
        Intent aux = new Intent(this,IntenteServiceOperacion.class);
        aux.putExtra("indice",id);

    }

    public void salir(View v){
            finish();
    }

    public void info(View z){
        AlertDialog.Builder alerta = new AlertDialog.Builder(MainActivity.this);
        alerta.setMessage(Mensaje)
                .setCancelable(false)
                .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
        AlertDialog dialogo = alerta.create();
        dialogo.setTitle("Información");
        dialogo.show();
    }

    public void eligeHora(View z){

        AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this);


        dialogo.setTitle("Selecciona Hora")
        .setItems(horas, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //Este metodo lo utilizo para guardar el dato seleccionado
                pasarDato(i);

            }
        });
        dialogo.create().show();
    }

    public void RecibeMensaje(){
        Intent intento = new Intent(this,IntenteServiceOperacion.class);
        startService(intento);
    }

    class ReceptorOperacion extends BroadcastReceiver {
        public static final String ACTION_RESP = "mx.edu.itoaxaca.intent.action.RESPUESTA_OPERACION";
        @Override
        public void onReceive(Context context, Intent intent) {
            String textoRes = intent.getStringExtra("respuesta");
            if(textoRes != null){
                asignarDatos(textoRes);
            }
        }

        public void asignarDatos(String datos){
            if(datos.length()>0) {
                data = datos.split(",");
                ePromCliSuc.setText(data[0]+" Clientes");
                eTimePromSis.setText(data[1]+" Seg.");
                eClientesFila.setText(data[2]+" Clientes");
                eTimeEspera.setText(data[3]+" Seg.");
            }
        }
    }

    class Hilo extends Thread{
        @Override
        public void run() {
            while (true){
                try {
                    RecibeMensaje();
                    sleep(100);
                }catch (InterruptedException ex){

                }catch (Exception ex){}
            }
        }
    }
}

And I want to send them to this class:

public class IntenteServiceOperacion extends IntentService {

    private Socket socket;
    private BufferedReader entrada;
    private PrintWriter salida;
    private String mensaje,mnsjSalida;
    private Intent intento;
    private final String IP = "192.168.0.15";
    private final int PORT = 7;
    public IntenteServiceOperacion(String name){
        super("IntenteServiceOperacion");
    }

    public IntenteServiceOperacion(){
        super("");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
            try{
                //Aqui es donde en teoria recupero el dato
                mnsjSalida = intent.getStringExtra("indice");
            }catch(Exception es){
                //Toast.makeTex,mnsjSalida,Toast.LENGTH_SHORT).show();
            }

            try {
                socket = new Socket(IP,PORT);
                entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                salida = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
                salida.println(mnsjSalida);
                mensaje = entrada.readLine();


            }catch (IOException e){}
             catch (Exception ex){}
        intento = new Intent();
        intento.setAction(MainActivity.ReceptorOperacion.ACTION_RESP);
        intento.putExtra("respuesta",((mensaje == null)?"":mensaje));
        sendBroadcast(intento);
    }


}
    
asked by Adrian Hernandez Islas 06.12.2017 в 05:37
source

2 answers

0

If you want to send data from the Activity to a Service , this can be done through the Intent in a Bundle:

Intent serviceIntent = new Intent(this, IntenteServiceOperacion.class)
 serviceIntent.putExtra("indice", id);
 startService(serviceIntent);

the sent values are received within the onStartCommand() method of your service:

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

    int indice = intent.getIntExtra("indice");

    ...
    ...

}
    
answered by 06.12.2017 / 11:46
source
0

When you send the value of your class to the next you need startActivity(aux); to start the process.

You have it like this:

 //Este metodo es el que guarda el valor
    public void pasarDato(int id){
        Intent aux = new Intent(this,IntenteServiceOperacion.class);
        aux.putExtra("indice",id);

    }

And it should be:

 //Este metodo es el que guarda el valor
    public void pasarDato(int id){
        Intent aux = new Intent(this,IntenteServiceOperacion.class);
        aux.putExtra("indice",id);
        startActivity(aux)
    }

And to receive:

  try{
    int myId;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    if(bundle != null){
        myId = bundle.getInt("indice"); // ahora puedes usar myId
    }                    
    }catch(Exception es){
        //Toast.makeTex,"ha ocurrido un error",Toast.LENGTH_SHORT).show();
    }
    
answered by 06.12.2017 в 06:38