Как передать ByteArray из действия в фрагмент (активность с вкладками), постоянно обновляющийся? - PullRequest
1 голос
/ 21 мая 2019

Я пытаюсь записать значения, полученные из действия, сохраняя их в byteArray для обработки и записывая их в метку фрагмента.

ByteArray собирает данные из уведомителя Bluetooth, поэтому он постоянно меняет свой контент.

Я показываю вам свой код, чтобы посмотреть, сможете ли вы мне помочь.

Эта функция включает матрицу с данными, то есть каждый раз, когда Bluetooth-уведомитель отправляет мне ByteArray с данными:

fun rellenarfases(arrayDatos: ByteArray) {

val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)

if (arrayDatos[0] == 0.toByte()) {
    //guardamos el valor en un array para mostrar
    arrayValores1 = arrayDatos
    //arrayValores1 = byteArrayOf(1.toByte(),2.toByte(),3.toByte())

    ///Envia el array al sectionPagerAdapter para luego mandarlo a su fragment correspondiente
    sectionsPagerAdapter.setArray(arrayValores1)

    sectionsPagerAdapter.notifyDataSetChanged()}

Это будет код SectionPagerAdapter, в этой части я получаю массив и в соответствии с первой позицией я определяю, в какой фрагмент я должен отправить ByteArray. Используя функцию setArray (), я собираю содержимое значения, заданного действием:

 class SectionsPagerAdapter(private val context: Context, fm: FragmentManager) : FragmentPagerAdapter(fm) {


//Nombre de las pestañas
private val TAB_TITLES = arrayOf(
    "l1",
    "l2",
    "l3",
    "l4"
)


var arrayValores = byteArrayOf(0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),
    0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),
    0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),
    0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte())

override fun getItem(position: Int): Fragment {
    // getItem is called to instantiate the fragment for the given page.
    // Return a PlaceholderFragment (defined as a static inner class below).
    if ( verArrayVacio(arrayValores) == true) {
        print ( "El array esta vacio")
    } else {
        if (position == 0) {
            if (arrayValores[0] == 0.toByte()) {
                //return PlaceholderFragment.newInstance2(byteArrayOf(1.toByte(),2.toByte(),3.toByte()))
                return PlaceholderFragment.newInstance2(arrayValores)
            }
        }
        if (position == 1) {
            //return PlaceholderFragment2.newInstance(position + 1)
            if (arrayValores[0] == 1.toByte()) {
                //return PlaceholderFragment.newInstance2(byteArrayOf(1.toByte(),2.toByte(),3.toByte()))
                return PlaceholderFragment.newInstance2(arrayValores)
            }
        }
        if (position == 2) {
            //return PlaceholderFragment3.newInstance(position + 1)
            if (arrayValores[0] == 2.toByte()) {
                //return PlaceholderFragment.newInstance2(byteArrayOf(1.toByte(),2.toByte(),3.toByte()))
                return PlaceholderFragment.newInstance2(arrayValores)
            }
        }
        if (position == 3) {
            //return PlaceholderFragment4.newInstance(position + 1)
            if (arrayValores[0] == 3.toByte()) {
                //return PlaceholderFragment.newInstance2(byteArrayOf(1.toByte(),2.toByte(),3.toByte()))
                return PlaceholderFragment.newInstance2(arrayValores)
            }
        }
    }
    return PlaceholderFragment.newInstance2(arrayValores)
}

//manda el valor del array
fun getArray(): ByteArray {
    return arrayValores
}

//Recoge el valor del array desde otro activity
fun setArray(array:ByteArray) {
    this.arrayValores = array
    print(arrayValores)
    getItem(arrayValores[0].toInt())
}

fun verArrayVacio(array: ByteArray) : Boolean {
    if (array.contentEquals(byteArrayOf(0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),
            0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),
            0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),
            0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte(),0.toByte())) == true) {
        return true
    } else {
        return false
    }
}

override fun getPageTitle(position: Int): CharSequence? {
    return context.resources.getString(TAB_TITLES[position])
}

//Numero de pestañas
override fun getCount(): Int {
    // Show 4 total pages.
    return 4
}

Это мой фрагмент, здесь через комплект я получаю ByteArray, и я пытаюсь нарисовать содержимое в TextView фрагмента, но я не могу заставить его рисовать что-либо, и то, что я хотел бы нарисовать и что каждый Когда содержимое ByteArray изменяется, оно становится Отправлять все обратно и изменять результат TextView:

    class PlaceholderFragment : Fragment() {

private lateinit var pageViewModel: PageViewModel


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    pageViewModel = ViewModelProviders.of(this).get(PageViewModel::class.java).apply {
        setIndex(arguments?.getInt(KEY_REG_TEXT) ?: 1)

    }
}



override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_informes, container, false)


    //recoge el valor del array pasado por el sectionPagerAdapter a traves del Bundle
    val message = arguments!!.getByteArray(KEY_REG_TEXT)

    val instTension: TextView = root.findViewById(R.id.instTension)
    val maxTension: TextView = root.findViewById(R.id.maxTension)
    val minTension: TextView = root.findViewById(R.id.minTension)
    val instCorriente: TextView = root.findViewById(R.id.instCorriente)
    val maxCorriente: TextView = root.findViewById(R.id.maxCorriente)
    val minCorriente: TextView = root.findViewById(R.id.minCorriente)
    val instActiva: TextView = root.findViewById(R.id.instActiva)
    val maxActiva: TextView = root.findViewById(R.id.maxActiva)
    val minActiva: TextView = root.findViewById(R.id.minActiva)
    val instInductiva: TextView = root.findViewById(R.id.instInductiva)
    val maxInductiva: TextView = root.findViewById(R.id.maxInductiva)
    val minInductiva: TextView = root.findViewById(R.id.minInductiva)
    val instCapacitiva: TextView = root.findViewById(R.id.instCapacitiva)
    val maxCapacitiva: TextView = root.findViewById(R.id.maxCapacitiva)
    val minCapacitiva: TextView = root.findViewById(R.id.minCapacitiva)
    val instAparente: TextView = root.findViewById(R.id.instAparente)
    val maxAparente: TextView = root.findViewById(R.id.maxAparente)
    val minAparente: TextView = root.findViewById(R.id.minAparente)
    val instFactor: TextView = root.findViewById(R.id.instFactor)
    val maxFactor: TextView = root.findViewById(R.id.maxFactor)
    val minFactor: TextView = root.findViewById(R.id.minFactor)
    val instCoseno: TextView = root.findViewById(R.id.instCoseno)
    val maxCoseno: TextView = root.findViewById(R.id.maxCoseno)
    val minCoseno: TextView = root.findViewById(R.id.minCoseno)


    if (message[1] == 0.toByte()) {

        instTension.text = convertirValores(message[2],message[3],message[4],message[5])
        var test = convertirValores(message[2],message[3],message[4],message[5])
        Log.e("VALORESI",test)
        instCorriente.text = convertirValores(message[6],message[7],message[8],message[9])
        instActiva.text = convertirValores(message[10],message[11],message[12],message[13])
        instInductiva.text = convertirValores(message[14],message[15],message[16],message[17])
        instCapacitiva.text = convertirValores(message[18],message[19],message[20],message[21])
        instAparente.text = convertirValores(message[22],message[23],message[24],message[25])
        instFactor.text = convertirValores(message[26],message[27],message[28],message[29])
        instCoseno.text = convertirValores(message[30],message[31],message[32],message[33])

    }

    if (message[1] == 1.toByte()) {

        maxTension.text = convertirValores(message[2],message[3],message[4],message[5])
        var test = convertirValores(message[2],message[3],message[4],message[5])
        Log.e("VALORESI",test)
        maxCorriente.text = convertirValores(message[6],message[7],message[8],message[9])
        maxActiva.text = convertirValores(message[10],message[11],message[12],message[13])
        maxInductiva.text = convertirValores(message[14],message[15],message[16],message[17])
        maxCapacitiva.text = convertirValores(message[18],message[19],message[20],message[21])
        maxAparente.text = convertirValores(message[22],message[23],message[24],message[25])
        maxFactor.text = convertirValores(message[26],message[27],message[28],message[29])
        maxCoseno.text = convertirValores(message[30],message[31],message[32],message[33])

    }

    if (message[1] == 2.toByte()) {

        minTension.text = convertirValores(message[2],message[3],message[4],message[5])
        var test = convertirValores(message[2],message[3],message[4],message[5])
        Log.e("VALORESI",test)
        minCorriente.text = convertirValores(message[6],message[7],message[8],message[9])
        minActiva.text = convertirValores(message[10],message[11],message[12],message[13])
        minInductiva.text = convertirValores(message[14],message[15],message[16],message[17])
        minCapacitiva.text = convertirValores(message[18],message[19],message[20],message[21])
        minAparente.text = convertirValores(message[22],message[23],message[24],message[25])
        minFactor.text = convertirValores(message[26],message[27],message[28],message[29])
        minCoseno.text = convertirValores(message[30],message[31],message[32],message[33])

    }

    return root
}

fun convertirValores(byte1 : Byte, byte2: Byte, byte3: Byte,byte4: Byte) : String{

    var byteArray = byteArrayOf(byte1,byte2,byte3,byte4)

    val convertirString = String(byteArray, StandardCharsets.UTF_8).replace(0.toChar().toString(), "")

    return convertirString
}

companion object {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */


    //private const val ARG_SECTION_NUMBER = "section_number"

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    @JvmStatic
    var  KEY_REG_TEXT = "text"



    fun newInstance2(array: ByteArray): PlaceholderFragment {
        val frag = PlaceholderFragment()

        var args: Bundle? = Bundle()
        frag.getArguments()
        if (args == null)
            args = Bundle()

        args.putByteArray(KEY_REG_TEXT, array)

        frag.setArguments(args)

        return frag
    }
}

Также вступает в игру (хотя я не знаю, что это) ViewModel, для которого я при необходимости оставляю код:

     class PageViewModel : ViewModel() {


private val _index = MutableLiveData<Int>()


    var instTension : LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var maxTension: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minTension: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var instCorriente: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var maxCorriente: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minCorriente: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var instActiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var maxActiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minActiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }

    var instInductiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }

    var maxInductiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minInductiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }

    var instCapacitiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var maxCapacitiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minCapacitiva: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var instAparente: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var maxAparente: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minAparente: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var instFactor: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var maxFactor: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minFactor: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var instCoseno: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var minCoseno: LiveData<String> = Transformations.map(_index) {
        "$it"
    }
    var maxCoseno: LiveData<String> = Transformations.map(_index) {
        "$it"
    }




fun setIndex(index: Int) {
    _index.value = index
}
...