I have a problem with two EditText
in particular, these are in a fragment
, the first time I arrive at the fragment, these are empty I assign them a number
( ej: et1 = 1, et2 = 2; )
I do all the operations in a normal way, I leave the fragment
and replace it with another one, when I return to the fragment
with the EditText
and I return them to enter values
( ej: et1 = 5, et2 = 6;)
when doing a et1.getText().toString();
it returns the value 1 instead of the new value that is 5
What could I be doing wrong?
the value of EditText
are assigned by user
I enclose the code for a better understanding
public class ConfigPackingFragment extends Fragment {
private EditText cantidad_espesor, cantidad_ancho, bt;
private ImageView chk1, chk2;
private Button buton;
private String code, RutCrea;
private Toolbar toolbar;
private ArrayList<Double> arrayListEspesor = new ArrayList<>();
private ArrayList<Double> arrayListAncho = new ArrayList<>();
private int contadorEspesor = 0, contadorAncho = 0,ID_UPDATE = 0,dispo;
// BLUETOOTH
private BluetoothDevice[] btArray;
private BluetoothAdapter bluetoothAdapter;
View view;
private int REGUEST_ENABLE_BLUETOOTH=1;
private static final String APP_NAME = "BTchat";
private static final UUID MY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address = null;
private BluetoothSocket btSocket = null;
private ConnectedThread mConnectedThread;
final int handlerState = 0;
private StringBuilder recDataString = new StringBuilder();
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_lista_datos, container, false);
bindUI();
cantidad_espesor.requestFocus();
/*cantidad_ancho.setText(null);
cantidad_espesor.setText(null);
cantidad_espesor.getText().clear();
cantidad_ancho.getText().clear();*/
SharedPreferences prefs = Objects.requireNonNull(getActivity()).getSharedPreferences("config_tel", Context.MODE_PRIVATE);
code = prefs.getString("codigo_busqueda", "");
ID_UPDATE = prefs.getInt("id_update", 0);
dispo = prefs.getInt("id_dispo", 0);
RutCrea = prefs.getString("rut_user", "");
bt.setText("");
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
Objects.requireNonNull(activity.getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Class nuevoFragmento = DetailFragment.class;
cambiarFragment(nuevoFragmento);
}
});
buton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
comenzarCiclo();
}
});
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REGUEST_ENABLE_BLUETOOTH);
}
if (bluetoothAdapter.isEnabled()) {
pairedDevice();
}
}
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_config_packing, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.btn_list_bt:
Class nuevoFragmento = ListaBT.class;
cambiarFragment(nuevoFragmento);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void cambiarFragment( Class fragmentClass){
Fragment fragment = null;
try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
}catch (Exception e){
e.printStackTrace();
}
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.detailsContainer, fragment)/*.addToBackStack(null)*/.commit();
// .addToBackStack(null)
}
Handler handler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
// recDataString.append(readMessage); //keep appending to string until ~
// int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
// if (endOfLineIndex > 0) { // make sure there data before ~
// String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
bt.setText(readMessage);
if (bt.getText().length() > 0){
asignarMedidas();
}
// int dataLength = dataInPrint.length(); //get length of data received
// txtStringLength.setText("Tamaño del String = " + String.valueOf(dataLength));
/* if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
String sensor1 = recDataString.substring(6, 10); //same again...
String sensor2 = recDataString.substring(11, 15);
String sensor3 = recDataString.substring(16, 20);
if(sensor0.equals("1.00"))
sensorView0.setText("Encendido"); //update the textviews with sensor values
else
sensorView0.setText("Apagado"); //update the textviews with sensor values
sensorView1.setText(sensor1);
sensorView2.setText(sensor2);
sensorView3.setText(sensor3);
//sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}*/
// recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
// dataInPrint = " ";
// }
}
return true;
}
});
@Override
public void onResume() {
super.onResume();
destruirTodo();
if (bluetoothAdapter != null) {
if (bluetoothAdapter.isEnabled()) {
pairedDevice();
}
}
}
public void destruirTodo(){
contadorAncho = 0;
contadorEspesor = 0;
arrayListEspesor = null;
arrayListAncho = null;
}
@Override
public void onPause() {
super.onPause();
destruirTodo();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(MY_UUID);
//creates secure outgoing connecetion with BT device using UUID
}
private void pairedDevice(){
// Add previosuly paired devices to the array
SharedPreferences prefs = Objects.requireNonNull(getActivity()).getSharedPreferences("config_tel", Context.MODE_PRIVATE);
String addrs = prefs.getString("mac", "");
if (!TextUtils.isEmpty(addrs)) {
BluetoothDevice devices = bluetoothAdapter.getRemoteDevice(addrs);
try {
btSocket = createBluetoothSocket(devices);
Toasty.success(Objects.requireNonNull(getActivity()), "Conectado a " + devices.getName(), Toast.LENGTH_LONG, true).show();
} catch (IOException e) {
Toasty.error(Objects.requireNonNull(getActivity()), "La creacción del Socket fallo", Toast.LENGTH_LONG, true).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
// mConnectedThread.write("x");
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
handler.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
/* public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toasty.error(Objects.requireNonNull(getActivity()), "La Conexión fallo", Toast.LENGTH_LONG,true).show();
// Objects.requireNonNull(getActivity()).finish();
}
}*/
}
private void asignarMedidas(){
int maxEspesor, maxAncho;
System.out.println(cantidad_ancho.getText().toString() + "__"+ cantidad_espesor.getText().toString());
if(cantidad_espesor.getText().length() <= 0 || cantidad_ancho.getText().length() <= 0) {
Toast.makeText(Objects.requireNonNull(getActivity()), "Debe ingresar ambos valores antes de comenzar", Toast.LENGTH_LONG).show();
}else
{
if (contadorEspesor == 0){ arrayListEspesor = new ArrayList<>(); }
if (contadorAncho == 0){ arrayListAncho = new ArrayList<>(); }
try {
Double numeroBT = Double.parseDouble(bt.getText().toString());
maxAncho = Integer.parseInt(cantidad_ancho.getText().toString());
maxEspesor = Integer.parseInt(cantidad_espesor.getText().toString());
System.out.println("NUMERO MAXIMO ESPESOR " + Integer.parseInt(cantidad_ancho.getText().toString()));
System.out.println("NUMERO MAXIMO ANCHO " + Integer.parseInt(cantidad_espesor.getText().toString()));
contadorEspesor++;
//mientras el contador de espesor (que es el primero) sea menor o igual al espesor este sumará +1 y se agregará un nuevo valor a el array de espesor
if (contadorEspesor <= maxEspesor) {
arrayListEspesor.add(numeroBT);
}
//cuando el contador de espesor sea mayor o igual
if (contadorEspesor > maxEspesor) {
contadorAncho++;
chk1.setVisibility(View.VISIBLE);
if (contadorAncho <= maxAncho) {
arrayListAncho.add(numeroBT);
}
}
if (arrayListEspesor.size() == maxEspesor && arrayListAncho.size() == maxAncho) {
chk2.setVisibility(View.VISIBLE);
final Paquete paquete = new Paquete();
AsyncTask.execute(new Runnable() {
@Override
public void run() {
final List<Paquete> pqt = InfoPacking.myAppDB.myDao().getPaquete(code);
Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
@Override
public void run() {
if (pqt.size() > 0) {
for (Paquete pqte : pqt) {
paquete.setEtiqueta(pqte.getEtiqueta());
}
} else {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
paquete.setEtiqueta(timeStamp);
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date da = new Date();
String fechaFinal = df.format(da);
paquete.setEspesor(arrayListEspesor);
paquete.setAncho(arrayListAncho);
List<Paquete> getPack = InfoPacking.myAppDB.myDao().getPaqueteById(ID_UPDATE);
for (Paquete paquete1 : getPack) {
paquete.setEtiqueta(paquete1.getEtiqueta());
paquete.setHumedad(paquete1.getHumedad());
paquete.setDetFam(paquete1.getDetFam());
paquete.setLargo(paquete1.getLargo());
paquete.setDescProd(paquete1.getDescProd());
paquete.setIdPaquete(paquete1.getIdPaquete());
paquete.setFecha(paquete1.getFecha());
paquete.setNombProd(paquete1.getNombProd());
paquete.setObservacion(paquete1.getObservacion());
paquete.setDispo(dispo);
paquete.setRutCrea(RutCrea);
paquete.setFechaDisp(fechaFinal);
}
try {
int numero = InfoPacking.myAppDB.myDao().updatePaquetes(paquete);
if (numero > 0) {
showAlertForObservaciones("Todo Bien", "Todos los datos se han guardado en el telefono correctamente", code, ID_UPDATE);
}
} catch (Exception e) {
e.getMessage();
e.getStackTrace();
System.out.println("ERROR DE LA BD" + e);
Toast.makeText(getActivity(), "No se insertaron las medidas", Toast.LENGTH_SHORT).show();
}
}
});
}
});
Toasty.success(Objects.requireNonNull(getActivity()), " TOMA FINALIZADA CON EXITO ", Toast.LENGTH_SHORT, true).show();
}
}catch (Exception e) {
Toasty.error(Objects.requireNonNull(getActivity()), "error de datos, debe ser un numero decimal", Toast.LENGTH_SHORT, true).show();
}
}
}
private void showAlertForObservaciones(String title, String message, final String codigo, final int id_paquete ) {
View viewInfalted = LayoutInflater.from(Objects.requireNonNull(getActivity())).inflate(R.layout.alert_empty, null);
final AlertDialog builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
.setView(viewInfalted)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Aceptar", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).setNegativeButton("cancelar",null).create();
builder.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button b = builder.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bndl = new Bundle();
bndl.putString("codigo", codigo);
bndl.putInt("idPaquete", id_paquete);
Fragment nuevoFragmento = new ObservacionesFragment();
assert getFragmentManager() != null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
nuevoFragmento.setArguments(bndl);
transaction.replace(R.id.detailsContainer, nuevoFragmento);
// transaction.addToBackStack(null);
transaction.commit();
builder.dismiss();
}
});
}
});
builder.setCancelable(false);
builder.show();
}
private void comenzarCiclo() {
cantidad_espesor.setEnabled(false);
cantidad_ancho.setEnabled(false);
}
private void bindUI(/*View view*/){
buton= view.findViewById(R.id.button_datos);
bt= view.findViewById(R.id.bt);
cantidad_ancho = view.findViewById(R.id.et_diametro_cant);
cantidad_espesor = view.findViewById(R.id.et_espesor_cant);
chk1 = view.findViewById(R.id.chk_espesor);
chk2 = view.findViewById(R.id.chk_ancho);
toolbar = view.findViewById(R.id.toolbar);
RecyclerView listaMedidas = view.findViewById(R.id.lista_medidas);
}
}
when receiving a value by means of bluethooth a function is activated, in this function I call the edittext previously filled by the user
maxAncho = Integer.parseInt(cantidad_ancho.getText().toString());
maxEspesor = Integer.parseInt(cantidad_espesor.getText().toString());