I'm trying to show all my posts stored in Firebase but it seems impossible to display the information into the recycler. I just manage to recover the data from firebase, because the size of the recyclerview is correct as it contents only two elements which the number of post I currently have in my firebase table. But nothing is show into the recycler. You can see my firebase in the attachment. The error I'm receiving is:
W/ClassMapper: No setter/field for imagen found on class com.example.tfg_red_social_v0.clases.Publicacion
W/ClassMapper: No setter/field for nombreUsuario found on class com.example.tfg_red_social_v0.clases.Publicacion
W/ClassMapper: No setter/field for comentario found on class com.example.tfg_red_social_v0.clases.Publicacion
W/ClassMapper: No setter/field for postUid found on class com.example.tfg_red_social_v0.clases.Publicacion
W/ClassMapper: No setter/field for imagen found on class com.example.tfg_red_social_v0.clases.Publicacion
W/ClassMapper: No setter/field for nombreUsuario found on class com.example.tfg_red_social_v0.clases.Publicacion
W/ClassMapper: No setter/field for comentario found on class com.example.tfg_red_social_v0.clases.Publicacion
W/ClassMapper: No setter/field for postUid found on class com.example.tfg_red_social_v0.clases.Publicacion
Here you have my adapter
package com.example.tfg_red_social_v0.adaptadores
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.tfg_red_social_v0.R
import com.example.tfg_red_social_v0.clases.Publicacion
import com.example.tfg_red_social_v0.clases.Usuario
import com.example.tfg_red_social_v0.fragments.PerfilFragment
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
//DESCRIPCION GENERAL. MUESTRA LOS USUARIOS. AL PULSAR EN EL BOTON SE SIGUE/NO SIGUE USUARIO/ ADEMAS AL PULSAR EN UN
//USUARIO RECYCLERVIEW SE ABRE EL USUARIO
class PublicacionAdaptador(private var context: Context, private var publicacionLista: List<Publicacion> ): RecyclerView.Adapter<PublicacionAdaptador.ViewHolder>() {
//EMPEZAMOS RECUPERANDO LA IFNROMACIÓN DEL USUARIO ACTUAL
private var firebaseUser: FirebaseUser = FirebaseAuth.getInstance().currentUser!!
private lateinit var referenciaBD: DatabaseReference
//CREAMOS UNA CLASE PARA MANIPULAR EL ADAPTADOR QUE DEVOLVERA UN OBJETO DEL ADAPTADOR
class ViewHolder( itemView: View):RecyclerView.ViewHolder(itemView) {
var tvUsuario: TextView = itemView.findViewById(R.id.tv_usuario)
var ivPerfil : ImageView = itemView.findViewById(R.id.iv_perfil)
var ivImagen : ImageView = itemView.findViewById(R.id.iv_imagen)
var ivbLike : ImageButton = itemView.findViewById(R.id.ivb_like)
var ivbFavorita : ImageButton = itemView.findViewById(R.id.ivb_favorita)
var ivbComentario : ImageButton = itemView.findViewById(R.id.ivb_comentar)
var tvPublicacion: TextView = itemView.findViewById(R.id.txt_publicacion)
var tvLikes: TextView = itemView.findViewById(R.id.txt_likes)
var tvEscritor: TextView = itemView.findViewById(R.id.txt_escritor)
var tvComentario: TextView = itemView.findViewById(R.id.txt_comentarios)
}
//CUANDO SE CREA EL ADAPTADOR NECESITA CARGARSE CON EL LAYOUT CORRESPONDIENTE AL USUARIO ESTO SE LOGRA
//CON EL METODO onCreateViewHolder Y CARGAMOS EL LAYOUT DEL USUARIO
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =LayoutInflater.from(context).inflate(R.layout.publicacion,parent,false)
return ViewHolder(view)
}
//EL METODO onBindViewHolder MUESTRA POR PANTALLA LOS DATOS INDICADOS POR SU POSICION
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
firebaseUser =FirebaseAuth.getInstance().currentUser!!
val publicacion = publicacionLista[position]
holder.tvUsuario.text=firebaseUser.uid
println(publicacion.propietarioPublicacion)
Glide.with(context).load(publicacion.imagenPublicada).centerCrop().into(holder.ivPerfil)
//holder.tvUsuario.text = publicacion.propietarioPublicacion.replaceFirstChar { it.uppercase()}
holder.tvPublicacion.text = publicacion.contenidoPublicado
}
//GETITEMCOUNT SIMPLEMENTE CUENTA LOS ELEMENTOS QUE TIENEN EL RECYCLERVIEW
override fun getItemCount(): Int {
return publicacionLista.size
}
//ETA FUNCION RECIBE EL UID DEL USUARIO CONTENIDO EN EL RECYCLERWIEW Y LOS BUSCARA TOMANDO COMO BASE
//EL USUARIUO ATUTENTIFICADO. DE ESTA FORMA VEMOS SI EL USUARIO AUTENTIFICADO ESTA SIENDO SEGUIDO
//SI ES ASI CAMBIARA EL ESTADO DEL BOTON QUE A SIGUIENDO YA QUE POR DEFECTO ME DA LA OPCION DE SEGUIR
private fun comprobarSiSigue( u_id:String, btn_seguir:Button)
{
//NOS POSICIONAMOS EN EL HIJO CORRESPONDIENTE A SIGUIENDO DEL USUARIO AUTENTIFICADO
val followingRef = firebaseUser.uid.let{ it->
FirebaseDatabase.getInstance().reference.child("Seguir").child(it)
.child("Siguiendo")}
//EN CASO DE QUE SE ENCUENTRE ALGUN VALOR. COSA QUE EVALUAMOS CON ADDAVALUEEVENTELISTENER CAMBIAMOS
//RECUPERAMOS LOS DATOS DEL ESE VALOR CON SNAPSHOT Y SI EN ESE REGISTRO RECUPERADO LA UID QUE APARECE
//ES LA QUE PASAMOS POR PARAMETRO QUIERE DECIR QUE EL USUARIO IDENTIFICADO YA ESTA SIGUIENDO AL USUARIO
//DEL RECICLERVIEW ASI QUE CAMBIAMOS EL BOTN DE TEXTO Y COLOR. SI NO ESTA LA UID ES QUE NO LO SEGUIMOS
//ASI QUE CAMBIARIAMOS DE ESTADO OTRA VEZ EL BOTON
followingRef.addValueEventListener(object :ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.child(u_id).exists()){
btn_seguir.setText("Siguiendo")
btn_seguir.setBackgroundColor(Color.RED)
} else {
btn_seguir.setBackgroundColor(Color.GREEN)
btn_seguir.setText("Seguir")
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
This is my activity, which is in a fragment.
package com.example.tfg_red_social_v0.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tfg_red_social_v0.R
import com.example.tfg_red_social_v0.adaptadores.PublicacionAdaptador
import com.example.tfg_red_social_v0.clases.Publicacion
import com.example.tfg_red_social_v0.clases.Usuario
import com.example.tfg_red_social_v0.databinding.FragmentInicioBinding
import com.example.tfg_red_social_v0.databinding.FragmentPublicacionBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class InicioFragment : Fragment() {
//LUEGO RECUPERARMOS EL FRAGMENTO EN BINDING
private var recyclerView: RecyclerView? = null
private var publicacionAdaptador: PublicacionAdaptador? = null
private var mPublicacion: MutableList<Publicacion>? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_inicio, container, false)
recyclerView = view?.findViewById(R.id.rec_publicacion)
recyclerView?.setHasFixedSize(true)
recyclerView?.layoutManager = LinearLayoutManager(context)
// SE PUEDE PONER EN HORIZONTAL CON
// recyclerView?.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
mPublicacion = ArrayList()
publicacionAdaptador = context?.let { PublicacionAdaptador(it, mPublicacion as ArrayList<Publicacion>) }
recyclerView?.adapter = publicacionAdaptador
mostrarPublicacionesCompletos()
return view
}
private fun mostrarPublicacionesCompletos() {
val usuarioActual = FirebaseAuth.getInstance().currentUser!!
val uidActual = usuarioActual.uid
val publicacionRef = FirebaseDatabase.getInstance().getReference().child("Publicaciones")
Toast.makeText(context,"SE CONECTA A LA TABLA PUBLICACIONES", Toast.LENGTH_SHORT).show()
publicacionRef.addValueEventListener(object : ValueEventListener {
//CARGAMOS TODOS LOS DATOS DE LA TABLA POSTS EN EL RECYCLERVIEW DATACHANGE SE ENCARGA DE CARGAR LOS DATOS
override fun onDataChange(snapshot: DataSnapshot) {
mPublicacion?.clear()
//cada snapshop es un registro de una tabla
for (snapshot in snapshot.children) {
val publicacion = snapshot.getValue(Publicacion::class.java)
//PARA QUE EL EDITAR PERFIL FUNCION SOLO DE EDITAR HE PREFERIDO
//MOSTRAR AL USUARIO AUTENTIFICADO TAMBIEN EN LA LISTA DE USUARIOS
//PARA QUE SE SIGA ASI MISMO. INSTRAGARM FUNCIONA IGUAL Y TE PUEDES SEGUIR A TI MISMO
//if (publicacion!!.publicacioonId == uidActual){
mPublicacion?.add(publicacion!!)
//}
}
//notify se ejcuta al final para guardar los cambios
publicacionAdaptador?.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
//VER QUE HACE
}
})
}
}
This is my class to store data
It's just empty to store data
package com.example.tfg_red_social_v0.clases
class Publicacion(var publicacioonId: String ="", var propietarioPublicacion: String ="", var contenidoPublicado: String ="", var imagenPublicada: String="") {
}
My xml layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#090909">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_usuario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#000000"
android:text="TextView"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
<ImageView
android:id="#+id/iv_perfil"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_weight="1"
app:srcCompat="#drawable/camerab" />
</LinearLayout>
<ImageView
android:id="#+id/iv_imagen"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_weight="1"
android:background="#000000"
app:srcCompat="#drawable/galeria" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#000000"
android:orientation="horizontal">
<ImageButton
android:id="#+id/ivb_like"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_weight="1"
app:srcCompat="#drawable/add" />
<ImageButton
android:id="#+id/ivb_favorita"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_weight="1"
app:srcCompat="#drawable/add" />
<ImageButton
android:id="#+id/ivb_comentar"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_weight="1"
app:srcCompat="#drawable/add" />
</LinearLayout>
<TextView
android:id="#+id/txt_publicacion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#000000"
android:hint="#FFFFFF"
android:text="TextView"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
<TextView
android:id="#+id/txt_likes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#000000"
android:hint="#FFFFFF"
android:text="TextView"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
<TextView
android:id="#+id/txt_escritor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#000000"
android:hint="#FFFFFF"
android:text="TextView"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
<TextView
android:id="#+id/txt_comentarios"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#000000"
android:hint="#FFFFFF"
android:text="TextView"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
I've tried everything. Debugging. Searching for answering in other post but I can't find my mistake.
So please HELP!
Related
I thank you in advance for your help. I am not a professional developer. I'm a teacher. I'm looking to create an app that can time student performance. I want to start a general stopwatch and stop the stopwatch individually. But, I encounter a problem either I don't have a crash but I can't interact on the individual stop button or I have a crash of type "binding.btnStop make not null"
Can you tell me how I can interact between the adapter and the fragment to link the general and individual timers and to stop the individual timer?
Thank you in advance for your help
Here is my code:
EvalFragment.class
var mDisplay: Display? = null
var path: String? = null
val REQUEST_CODE = 1
var isPlay = false
var pauseOffSet :Long = 0
//Test chrono millisec
var isResume = false
private lateinit var handler: Handler
var tMilliSec = 0L
var tStart = 0L
var tBuff = 0L
var tUpdate = 0L
var sec: Int = 0
var min: Int = 0
var milliSec: Int = 0
//Pour accéder au fab
private var _binding: FragmentEvalBinding? = null
private val binding get() = _binding!!
private lateinit var mUserViewModel: UserViewModel
private lateinit var mUserEvalViewModel: UserEvalViewModel
private val args by navArgs<EvalFragmentArgs>()
private lateinit var btPlay: ImageButton
private lateinit var btnPause: ImageButton
private lateinit var btStop: ImageButton
private lateinit var chronomter: Chronometer
#RequiresApi(Build.VERSION_CODES.R)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentEvalBinding.inflate(inflater, container, false)
val view = binding.root
//Recyclerview pour afficher le custom row et les données
val adapter = EvalAdapter()
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerview_time)
recyclerView?.adapter = adapter
recyclerView?.layoutManager = LinearLayoutManager(requireContext())
mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
mUserEvalViewModel = ViewModelProvider(this).get(UserEvalViewModel::class.java)
chronomter = binding.chronometerGeneral
btPlay = binding.btStart
btStop = binding.btStop
btnPause = binding.btPause
handler = Handler()
btPlay.setOnClickListener {
if(!isResume){
tStart = SystemClock.uptimeMillis()
handler.postDelayed(runnable, 0)
chronomter.start()
binding.recyclerviewTime.chronometerIndividuel.start()
isResume = true
btStop.visibility = View.GONE
btPlay.setImageDrawable(resources.getDrawable(R.drawable.ic_pause))
} else {
tBuff += tMilliSec
handler.removeCallbacks(runnable)
chronomter.stop()
binding.recyclerviewTime.chronometerIndividuel.stop()
isResume = false
btStop.visibility = View.VISIBLE
btPlay.setImageDrawable(resources.getDrawable(R.drawable.ic_play))
}
}
btnPause.setOnClickListener {
pause()
}
btStop.setOnClickListener {
stop()
if(!isResume){
btPlay.setImageDrawable(resources.getDrawable(R.drawable.ic_play))
tMilliSec = 0L
tStart = 0L
tBuff = 0L
tUpdate = 0L
sec = 0
min = 0
milliSec = 0
chronomter.setText("00:00:00")
binding.recyclerviewTime.chronometerIndividuel.setText("00:00:00")
}
}
val userStart = args.currentUser.time
mUserEvalViewModel.readAllDataUserEval?.observe(viewLifecycleOwner, Observer { user ->
adapter.setDataEval(user)
})
val wm: WindowManager? =
activity?.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
mDisplay = wm!!.defaultDisplay
if (ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
), REQUEST_CODE
)
} else {
Toast.makeText(
requireContext(),
"Veuillez accepter les permissions",
Toast.LENGTH_SHORT
).show()
}
// Add menu
setHasOptionsMenu(true)
return view
}
val runnable: Runnable = object : Runnable {
override fun run() {
tMilliSec = SystemClock.uptimeMillis() - tStart
tUpdate = tBuff + tMilliSec
sec = (tUpdate/1000).toInt()
min= sec/60
sec = sec%60
milliSec = (tUpdate%100).toInt()
chronomter.setText(String.format("%02d", min)+":"
+ String.format("%02d", sec)+":"+String.format("%02d", milliSec))
handler.postDelayed(this, 60)
}
}
private fun clicSound() {
val mediaPlayer: MediaPlayer = MediaPlayer.create(context, R.raw.positive_notification)
mediaPlayer.start()
}
private fun pause() {
if (isPlay){
chronomter.stop()
pauseOffSet = SystemClock.elapsedRealtime() - chronomter.base
isPlay = false
btnPause.setBackgroundResource(R.drawable.ic_play)
Toast.makeText(context,"Chronomètre: en Pause !!",Toast.LENGTH_SHORT).show()
}
else{
chronomter.base = SystemClock.elapsedRealtime() - pauseOffSet
chronomter.start()
btnPause.setBackgroundResource(R.drawable.ic_pause)
Toast.makeText(context,"Chronomètre : en route !!",Toast.LENGTH_SHORT).show()
isPlay = true
}
}
private fun play() {
chronomter.base = SystemClock.elapsedRealtime() - pauseOffSet
chronomter.start()
btPlay.setBackgroundResource(R.drawable.ic_stop)
Toast.makeText(context,"Chronomètre déclenché !!",Toast.LENGTH_SHORT).show()
isPlay =true
}
private fun stop() {
chronomter.base = SystemClock.elapsedRealtime()
pauseOffSet = 0
chronomter.stop()
btPlay.setBackgroundResource(R.drawable.ic_play)
Toast.makeText(context, "Chronomètre arrêté !!", Toast.LENGTH_SHORT).show()
isPlay = false
}
private fun reset(){
chronomter.base = SystemClock.elapsedRealtime() - pauseOffSet
chronomter.stop()
btnPause.visibility = View.INVISIBLE
btPlay.setBackgroundResource(R.drawable.ic_play)
Toast.makeText(context,"Chronomter is Start !!",Toast.LENGTH_SHORT).show()
isPlay = false
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PackageManager.PERMISSION_GRANTED && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(requireContext(), "Permission Autorisée", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(requireContext(), "Permission Refusée", Toast.LENGTH_SHORT).show()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.delete_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_delete) {
// deleteAllEvals()
}
return super.onOptionsItemSelected(item)
}
}```
My EvalAdapter.class:
```class EvalAdapter: RecyclerView.Adapter<EvalAdapter.MyViewHolder>() {
var evalList = emptyList<UserWithEval>()
private lateinit var mUserViewModel: UserViewModel
private lateinit var mEvalViewModel: EvalViewModel
private lateinit var mUserWithEvalViewModel: UserEvalViewModel
private lateinit var firstName: String
private lateinit var lastName: String
private var idUser: Int = 0
private var user_id_reference: Int = 0
private var gru_id_reference: Int = 0
private var timeInterDepart = 0
private lateinit var chronoInd : Chronometer
private lateinit var chronoGeneral : Chronometer
private lateinit var context: Context
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
context = parent.context
return MyViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.custom_time, parent, false)
)
}
override fun getItemCount(): Int {
return evalList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItemUser = evalList[position]
holder.itemView.findViewById<TextView>(R.id.firstName_txt).text = currentItemUser.firstName.uppercase()
holder.itemView.findViewById<TextView>(R.id.lastName_txt).text = currentItemUser.lastName.uppercase()
chronoInd = holder.itemView.findViewById(R.id.chronometerIndividuel)
holder.itemView.findViewById<Button>(R.id.bt_stop_individuel).setOnClickListener {
chronoInd.stop()
}
}
fun setDataEval(user: List<UserWithEval>){
this.evalList = user
notifyDataSetChanged()
}
}```
fragment_eval.xml:
```<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
android:orientation="horizontal"
android:id="#+id/fragEval">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview_time"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/linearLayoutCompat"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_margin="30dp"
android:background="#drawable/bg_round"
android:gravity="center"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Chronometer
android:id="#+id/chronometerGeneral"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:format="00:00:00"
android:textColor="#color/white"
android:textSize="40sp"
android:textStyle="bold" />
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<ImageButton
android:id="#+id/bt_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/transparent_background"
android:src="#drawable/ic_play" />
<ImageButton
android:id="#+id/bt_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/transparent_background"
android:src="#drawable/ic_stop" />
<ImageButton
android:id="#+id/bt_pause"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/transparent_background"
android:src="#drawable/ic_pause" />
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
<EditText
android:id="#+id/editTextTempsDepart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/custom_input_eval"
android:drawableLeft="#drawable/ic_chrono"
android:hint=" 15 "
android:inputType="number"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="#+id/linearLayoutCompat"
app:layout_constraintEnd_toStartOf="#+id/linearLayoutCompat"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/validTempsDepart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/validate"
android:layout_marginLeft="20dp"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/editTextTempsDepart"
app:layout_constraintStart_toEndOf="#+id/editTextTempsDepart"
app:layout_constraintTop_toTopOf="#+id/editTextTempsDepart" />
<TextView
android:id="#+id/tvTempsPremierDepart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/custom_input"
android:text="00 sec"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/linearLayoutCompat"
app:layout_constraintTop_toBottomOf="#+id/linearLayoutCompat" />
</androidx.constraintlayout.widget.ConstraintLayout>
custom_time.xml:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
tools:context=".MainActivity">
//1ère ligne du chrono
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:layout_marginTop="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/bt_stop_individuel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:background="#drawable/shape_background"
android:text="#string/stop"
android:textColor="#color/white"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="#+id/firstName_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="#string/firstName"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lastName_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="#string/lastName"
android:textSize="25sp"
android:textStyle="bold" />
<Chronometer
android:id="#+id/chronometerIndividuel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:format="00:00:00"
android:text="00:00:00"
android:textSize="30sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
I am trying to display notes in my recycler view. the note body is like this:
Note Title in one text view
Note Content in the other text view below the title
So, this will get displayed in one Item and then the next note in the next item. But the issue is that,
one item is containing the note title, and the other one is containing its content.
Here is my NotesAdapter Class:
class NotesAdapter(private var noteView: ArrayList<String>):
RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {
inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val noteView : View =LayoutInflater.from(parent.context).inflate(R.layout.note_card,parent,false)
return MyViewHolder(noteView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
//Set data here
holder.itemView.apply {
note_title_TV.text = noteView[position]
note_content_TV.text = noteView[position]
}
}
override fun getItemCount(): Int {
return noteView.size
}
}
My Main Activity Class (This class contains my firebase code too, as I am reading data from there and storing that into a list) :
class HomeActivity : AppCompatActivity() {
var nList = ArrayList<String>();
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
val rootReference = Firebase.database.reference //app root in firebase database
val currentUser = FirebaseAuth.getInstance().currentUser
val uid = currentUser?.uid.toString()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
//Show user's name in welcome message
//get the name of user from firebase
val nameFromFirebase: FirebaseDatabase = FirebaseDatabase.getInstance()
var nameReference = rootReference.child("users").child(uid).child("name")
nameReference.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val result = snapshot.value
tv_User_Name.text = result.toString()
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
btn_createNote.setOnClickListener {
Intent(this, AddNoteActivity::class.java).also {
startActivity(it)
}
}
//Read notes from database
readNotesFromFirebaseDatabase()
//Updating Layout to display notes in RecyclerView
recyclerView = findViewById<RecyclerView>(R.id.rv_displayNotesInRecyclerView)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager=LinearLayoutManager(this)
//RecyclerView Adapter being passed the notes list
val adapter = NotesAdapter(nList)
rv_displayNotesInRecyclerView.adapter = adapter
}
fun readNotesFromFirebaseDatabase(){
val noteReference = rootReference.child("users").child(uid).child("Notes")
noteReference.addValueEventListener(object:ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
val noteContent = snapshot.child("noteContent").getValue(String::class.java)
val noteTitle = snapshot.child("noteTitle").getValue(String::class.java)
//Add Notes to the ArrayList of Notes
nList.add(noteTitle.toString())
nList.add(noteContent.toString())
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
Note_item XML Layout File:
<?xml version="1.0" encoding="UTF-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/prompt_cardview"
android:layout_width="390dp"
android:layout_height="89dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:minHeight="120dp"
app:cardCornerRadius="15dp"
app:cardElevation="3dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="384dp"
android:layout_height="match_parent"
android:minHeight="120dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/note_title_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:fontFamily="#font/lato"
android:lineHeight="22dp"
android:text="Title"
android:textAlignment="gravity"
android:textColor="#4F4B4B"
android:textSize="18sp"
android:textStyle="bold"
android:paddingLeft="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.037"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/note_content_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginStart="12dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="8dp"
android:fontFamily="#font/lato"
android:paddingLeft="5dp"
android:lineHeight="14dp"
android:singleLine="false"
android:text="#string/some_comments_are_here_to_stay_you_know"
android:textAlignment="center"
android:textColor=" #877B7B"
android:textSize="12sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/note_title_TV"
app:layout_constraintVertical_bias="0.0" />
<ImageButton
android:id="#+id/btn_edit"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/round_button_edit"
android:src="#drawable/icon_btn_edit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btn_delete"
app:layout_constraintHorizontal_bias="0.972"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/note_content_TV"
app:layout_constraintVertical_bias="1.0" />
<ImageButton
android:id="#+id/btn_delete"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/round_button_delete"
android:src="#drawable/icon_btn_delete"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.983"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/note_content_TV"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
I Also have made a Note Class (if it may be of any assistance) :
class Note (val noteContent:String , val noteTitle: String) {
}
This is my Firebase Database Note Entry, 1:https://i.stack.imgur.com/bixCW.png
Now, I am getting this output, 2: https://i.stack.imgur.com/VV7l7.png
P.S I know there are some posts regarding this like this one: How to create Multiple View Type in Recycler View but they are in Java and I am getting stuck while converting that here.
Try this:
Create a model class with 2 variables
class Notes{
val title: String = ""
val content: String = ""
}
after that creates an array list using that model class instead of String which looks like this:
val list: MutableList<Notes> = Notes()
val nots : Notes = Notes()
notes.title = "test"
notes.content = "Good Work!"
list.add(notes)
Once your list is created pass that list to adapter and you are good to go
class NotesAdapter(private var list: ArrayList<Note>):
RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {
inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val noteView : View = LayoutInflater.from(parent.context).inflate(R.layout.note_card,parent,false)
return MyViewHolder(noteView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.apply {
note_title_TV.text = list[position].title
note_content_TV.text = list[position].content
}
}
override fun getItemCount(): Int {
return list.size
}
}
The problem is solved.
Change the ArrayList from String to Note
And in the Main Activity Class, edited this block of code:
//Add Notes to the ArrayList of Notes
var note : Note
note.noteContent = noteTitle.toString()
note.noteTitle = noteTitle.toString()
In the NotesAdapter Class (Posting the complete correct code):
class NotesAdapter(private var noteView: ArrayList<Note>):
RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {
inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val noteView : View = LayoutInflater.from(parent.context).inflate(R.layout.note_card,parent,false)
return MyViewHolder(noteView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
//Set data here
holder.itemView.apply {
note_title_TV.text = noteView[position].noteContent
note_content_TV.text = noteView[position].noteTitle
}
}
override fun getItemCount(): Int {
return noteView.size
}
}
I'm trying to do Automatic image slider in fragment in kotlin.
I am trying to convert an activity to fragment. However runouithread is not working in fragments.Any possible solutions??
I tried couple of other things also. But not a possible solution, I can do image slide inside the fragment but not to dod the auomatic sliding....
My mainactivity()
package com.example.sliderimagemovie
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="409dp"
android:layout_height="290dp"
android:name="com.example.sliderimagemovie.HomeFragment"
android:id="#+id/fragment"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="441dp"/>
</android.support.constraint.ConstraintLayout>
slide_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="275dp">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp" app:srcCompat="#drawable/ic_launcher_background"
android:id="#+id/slide_image"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent" android:scaleType="centerCrop"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true" app:srcCompat="#drawable/ic_play_button"
android:id="#+id/glide_play_button"
app:layout_constraintTop_toTopOf="#+id/slide_image" android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="#+id/slide_image"
app:layout_constraintEnd_toEndOf="#+id/slide_image"
app:layout_constraintStart_toStartOf="#+id/slide_image" android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" app:backgroundTint="#color/colorAccent"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="100dp" app:srcCompat="#drawable/gradient_bg"
android:id="#+id/imageView3" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/movie_title" android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/glide_play_button"
app:layout_constraintBottom_toBottomOf="#+id/imageView3" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="24dp" android:layout_marginRight="24dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="24dp"
android:layout_marginStart="24dp" android:textSize="24sp" app:layout_constraintHorizontal_bias="0.0"
android:textColor="#android:color/holo_red_light"/>
</android.support.constraint.ConstraintLayout>
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:layout_width="0dp"
android:layout_height="275dp" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
android:id="#+id/view_pager_glide"/>
<android.support.design.widget.TabLayout
app:tabBackground="#drawable/indicator_item"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
android:layout_width="395dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/view_pager_glide" app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp" android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp" android:layout_marginRight="8dp" android:id="#+id/indicator">
</android.support.design.widget.TabLayout>
</android.support.constraint.ConstraintLayout>
</FrameLayout>
slide.kt
package com.example.sliderimagemovie.Model
class Slide(var image:Int, var title:String)
slidePagerAdapater.kt
package com.example.sliderimagemovie.Adapter
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.example.sliderimagemovie.Model.Slide
import com.example.sliderimagemovie.R
class SlidePagerAdapter:PagerAdapter {
var mContext: Context?=null
var mList:List<Slide>?=null
constructor(context: Context, list:List<Slide>)
{
mContext=context
mList=list
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
var inflater:LayoutInflater= mContext!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
var slideLayout:View =inflater.inflate(R.layout.slide_item,null)
var slideImage:ImageView =slideLayout.findViewById(R.id.slide_image)
var slideText:TextView=slideLayout.findViewById(R.id.movie_title)
slideImage.setImageResource(mList!!.get(position).image)
slideText.setText(mList!!.get(position).title)
container.addView(slideLayout)
//return super.instantiateItem(container, position)
return slideLayout
}
override fun isViewFromObject(p0: View, p1: Any): Boolean {
return p0 == p1
}
override fun getCount(): Int {
return mList!!.count()
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//super.destroyItem(container, position, `object`)
container.removeView(`object` as View)
}
}
HomeFragment.kt
package com.example.sliderimagemovie
import android.app.Application
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.sliderimagemovie.Adapter.SlidePagerAdapter
import com.example.sliderimagemovie.Model.Slide
import kotlinx.android.synthetic.main.fragment_home.*
import kotlin.concurrent.fixedRateTimer
class HomeFragment : Fragment() {
var lstSlides:MutableList<Slide> =ArrayList()
var sliderPage: ViewPager?=null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
sliderPage=view.findViewById(R.id.view_pager_glide)
lstSlides.add(Slide(R.drawable.spiderman,"Slide1 Spiderman"))
lstSlides.add(Slide(R.drawable.avenger,"Slide2 Avenger"))
lstSlides.add(Slide(R.drawable.frozen2,"Slide3 Frozen2"))
lstSlides.add(Slide(R.drawable.fastfurious,"Slide4 Fastfurious"))
lstSlides.add(Slide(R.drawable.joker,"Slide5 Joker"))
lstSlides.add(Slide(R.drawable.jumanji,"Slide6 Jumanji"))
lstSlides.add(Slide(R.drawable.terminator,"Slide7 Terminator"))
var adapter: SlidePagerAdapter = SlidePagerAdapter(context!!,this.lstSlides)
sliderPage!!.adapter=adapter
indicator.setupWithViewPager(sliderPage,true)
fixedRateTimer(name = "timer",initialDelay = 4000,period = 6000){
// I'm getting error over here. Since runOnUiThread wont work with fragment , I tried to run with //activity. but its not working. I tried couple of other things.
getactivity().runOnUiThread
{
public override fun run() {
if (sliderPage!!.currentItem < lstSlides.count() - 1) {
sliderPage!!.currentItem = sliderPage!!.currentItem + 1
} else {
sliderPage!!.currentItem = 0
}
}
})
}
return view
}
}
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 4 years ago.
I create a recyclerview in activity and when I'm trying to incorporate Fragment it giving me "Error E/RecyclerView: No adapter attached; skipping layout"
My old sample Output
My old sample Output
Now I wanted to place bottom navigation and Fragment. Below is my code
my Activity file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingView"
android:background="#color/colorAccent"
tools:context=".MainActivity">
<!-- <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
-->
<TextView
android:id="#+id/Voc"
android:layout_height="wrap_content"
android:text="Section 1"
android:layout_width="wrap_content"
android:paddingTop="3dp"
android:paddingBottom="3dp"
android:paddingLeft="10dp"
android:textSize="25sp"
app:layout_constraintTop_toTopOf="parent"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/Voc"
/>
<TextView
android:id="#+id/sep_id"
android:layout_height="wrap_content"
android:text="Section 2"
android:layout_width="wrap_content"
android:paddingTop="6dp"
android:paddingBottom="3dp"
android:textSize="25sp"
android:paddingLeft="10dp"
app:layout_constraintTop_toBottomOf="#id/my_recycler_view"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/speaking"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/sep_id"
android:paddingLeft="10dp"/>
</android.support.constraint.ConstraintLayout>
Recycler layout : row_post.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="120dp"
android:layout_height="120dp"
>
<!-- <LinearLayout
android:id="#+id/view_main_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"> -->
<ImageView
android:id="#+id/image_view_id_row"
android:layout_width="match_parent"
android:layout_marginRight="10dp"
android:src="#drawable/sp2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_height="90dp"
android:background="#color/colorPrimary"
android:scaleType="fitXY"
/>
<TextView
android:id="#+id/username"
android:text="Loading Username.."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
app:layout_constraintTop_toBottomOf="#id/image_view_id_row"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:textAlignment="center"
android:layout_marginRight="10dp"
/>
<!-- "
android:src="#drawable/sp1"-->
</android.support.constraint.ConstraintLayout>
Main Layout or landing page with Frame : activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/containerm"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/frame_layout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:layout_gravity="bottom"
android:layout_weight="0"
android:background="?android:attr/windowBackground"
app:itemBackground="#color/colorPrimary"
app:itemIconTint="#color/white"
app:itemTextColor="#color/white"
app:menu="#menu/navigation"/>
</LinearLayout>
kotlin class : FragmentCall(link to activity_main.xml)
package com.ammara.ammara.TEST
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.net.Uri
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
import com.ammara.ammara.ielts.model.Samples
class FragmentCall:Fragment() {
val TAG="Call Fragment"
override fun onAttach(context: Context?) {
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.activity_main,container,false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
override fun onStart() {
super.onStart()
}
override fun onResume() {
super.onResume()
}
override fun onPause() {
super.onPause()
}
override fun onStop() {
super.onStop()
}
override fun onDestroyView() {
super.onDestroyView()
}
override fun onDestroy() {
super.onDestroy()
}
override fun onDetach() {
super.onDetach()
}
}
kotlin class Main2Activity (link to activity_main2.xml)
package com.ammara.ammara.TEST
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import com.ammara.ammara.ielts.R.menu.navigation
import com.ammara.ammara.ielts.model.Samples
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main2.*
class Main2Activity : AppCompatActivity() {
var isFragmentOneLoaded=true
val manager=supportFragmentManager
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
ShowFragmentOne()
return#OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
ShowFragmentOne()
return#OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
ShowFragmentOne()
return#OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
ShowFragmentOne()
navigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}
fun ShowFragmentOne(){
val transaction=manager.beginTransaction()
val fragment=FragmentCall()
transaction.replace(R.id.frame_layout_id,fragment)
transaction.addToBackStack(null)
transaction.commit()
AlertDialog.Builder( this)
.setMessage(this.packageName)
.setPositiveButton("ok") { p0, p1 ->
}
.create()
.show()
}
}
Adaptor class link to row_post
package com.ammara.ammara.TEST
import android.content.Intent
import android.os.Parcel
import android.os.Parcelable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.ammara.ammara.TEST.model.Samples
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.row_post.view.*
import android.os.Bundle
import android.support.v4.content.ContextCompat.startActivity
class PostsAdapter (val posts: ArrayList<Samples>) : RecyclerView.Adapter<PostsAdapter.PostsViewHolder> (){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostsAdapter.PostsViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.row_post,parent,false)
val holder= PostsViewHolder(view)
view.setOnClickListener{
val intent= Intent(parent.context, SampleTest::class.java)
val extras = Bundle()
extras.putString("title",posts[holder.adapterPosition].title)
extras.putString("photoUrl",posts[holder.adapterPosition].photoUrl.toString())
intent.putExtras(extras)
parent.context.startActivity(intent)
}
return holder
}
override fun getItemCount() = posts.size
override fun onBindViewHolder(holder: PostsViewHolder, position: Int) {
holder.title.text=posts[position].title
holder.image.setImageURI(posts[position].photoUrl)
// Picasso.get().load(posts[position].photoUrl).into(holder.image)
}
class PostsViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val image: ImageView=itemView.findViewById(R.id.image_view_id_row)
val title: TextView=itemView.findViewById(R.id.username)
}
}
Now the problem is that....earlier I was having below lines of code in my activity, now activity is not getting call due to fragment. where do i put below line of code
val myImageList = intArrayOf(R.drawable.sp1, R.drawable.sp2, R.drawable.sp3, R.drawable.sp4, R.drawable.sp5, R.drawable.sp6, R.drawable.sp7, R.drawable.sp8, R.drawable.sp9, R.drawable.sp10)
val myImageList1 = arrayListOf("#drawable/sp1", "#drawable/sp2", "#drawable/sp3", "#drawable/sp4", "#drawable/sp5", "#drawable/sp6", "#drawable/sp7", "#drawable/sp8", "#drawable/sp9", "#drawable/sp10")
val myImageList2 = arrayListOf("sp1", "sp2", "sp3", "sp4", "sp5", "sp6", "sp7", "sp8", "sp9", "sp10")
val samples= arrayListOf<Samples>()
for (i in 0..9){
val imgUri = Uri.parse("android.resource://com.ammara.ammara.ielts/"+myImageList[i])
samples.add(Samples("Sample# $i", photoUrl=imgUri,price=1.99))
}
val vSpeaking= arrayListOf<Samples>()
for (i in 0..9){
val imgUri = Uri.parse("android.resource://com.ammara.ammara.ielts/"+myImageList[i])
vSpeaking.add(Samples("Sample# $i",photoUrl=imgUri,price=1.99))
}
my_recycler_view.layoutManager =LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false)
my_recycler_view.adapter = PostsAdapter(samples)
speaking.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false)
speaking.adapter = PostsAdapter(vSpeaking)
where do i put below line of code
Put it in the Fragment where you inflate the view containing the RecyclerView in onCreateView.
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.activity_main,container,false)
//your code here
return view
}
See https://developer.android.com/guide/components/fragments for information about when to do what in a fragment.
I want to develop an app which
Creates a file in external storage
2.Writes accelerometer readings to the file whenever start button is clicked
3.Stops writing when stop button is clicked
4.Reads the contents of the file on the click of read button
I don't know how to create a file in external storage and store the readings of accelerometer in it and later read the values from the file.
I tried the following code in MainACtivity.java
package com.example.startstopbuttonaccelerometerreading;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2;
RelativeLayout layout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title=(TextView)findViewById(R.id.name);
tv=(TextView)findViewById(R.id.xval);
tv1=(TextView)findViewById(R.id.yval);
tv2=(TextView)findViewById(R.id.zval);
}
public void onStartClick(View view) {
final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2]; // TODO apply the acceleration changes to your application.
textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;
try {
File myFile = new File("/sdcard/acc.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(acc);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'acc.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
// write on SD card file data in the text box
int sensorType = Sensor.TYPE_ACCELEROMETER;
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}// onClick
;
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
This is the activity_main.xml code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="#+id/relative" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="124dp"
android:text="Start"
android:onClick="onStartClick" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="37dp"
android:layout_toRightOf="#+id/button1"
android:text="Stop"
android:onClick="onStopClick" />
<TextView
android:textSize="30dp"
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:textSize="20dp"
android:layout_below="#+id/name"
android:id="#+id/xval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:textSize="20dp"
android:id="#+id/yval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/xval"
/>
<TextView
android:textSize="20dp"
android:id="#+id/zval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/yval"
/>
</RelativeLayout>
I wrote the permission in androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity is not getting compiled. The errors are acc and textview cant be resolved.
I want to know the code to create a file in external storage and write accelerometer readings to it and read data from the file.
I have rewrote your code as the following including AndroidManifest.xml, activity_main.xml and MainActivity.java.
There are three buttons in this program.
1.Start: Start to write three-axis data into acc.txt.
2.Stop: Stop writing data.
3.Read: Read all data in acc.txt
And I create a edit text to show the content in acc.txt after the Read button is clicked.
There are some delay time in this program. You can adjust it by yourself.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.so_problem"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.so_problem.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="#+id/relative" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="124dp"
android:text="Start"
android:onClick="onStartClick" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="37dp"
android:layout_toRightOf="#+id/button1"
android:text="Stop"
android:onClick="onStopClick" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/button2"
android:layout_centerVertical="true"
android:text="Read"
android:onClick="onReadClick" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp" />
<TextView
android:textSize="20dp"
android:layout_below="#+id/name"
android:id="#+id/xval"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:textSize="20dp"
android:id="#+id/yval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/xval" />
<TextView
android:textSize="20dp"
android:id="#+id/zval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/yval" />
<EditText
android:id="#+id/showval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/zval"
android:layout_alignRight="#+id/zval"
android:layout_below="#+id/button3"
android:layout_marginTop="18dp"
android:clickable="false"
android:cursorVisible="false"
android:editable="false"
android:ems="10"
android:freezesText="true"
android:inputType="none"
android:lines="8"
android:maxLines="1000"
android:scrollbars="vertical"
android:singleLine="false" />
</RelativeLayout>
MainActivity.java
package com.example.so_problem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener
{
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tvx,tvy,tvz;
EditText etshowval;
RelativeLayout layout;
private String acc;
private String read_str = "";
private final String filepath = "/mnt/sdcard/acc.txt";
private BufferedWriter mBufferedWriter;
private BufferedReader mBufferedReader;
private float x;
private float y;
private float z;
public static final int MSG_DONE = 1;
public static final int MSG_ERROR = 2;
public static final int MSG_STOP = 3;
private boolean mrunning;
private Handler mHandler;
private HandlerThread mHandlerThread;
private Handler uiHandler = new Handler(){
public void handleMessage(Message msg){
String str = (String) msg.obj;
switch (msg.what)
{
case MSG_DONE:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
break;
case MSG_ERROR:
Toast.makeText(getBaseContext(),str,
Toast.LENGTH_SHORT).show();
break;
case MSG_STOP:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
default:
break;
}
super.handleMessage(msg);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title = (TextView)findViewById(R.id.name);
tvx = (TextView)findViewById(R.id.xval);
tvy = (TextView)findViewById(R.id.yval);
tvz = (TextView)findViewById(R.id.zval);
etshowval = (EditText)findViewById(R.id.showval);
title.setText("Accelerator");
mHandlerThread = new HandlerThread("Working Thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(r);
}
private Runnable r = new Runnable(){
#Override
public void run ()
{
while(true)
{
if (mrunning)
{
Message msg1 = new Message();
try
{
WriteFile(filepath,acc);
msg1.what = MSG_DONE;
msg1.obj = "Start to write to SD 'acc.txt'";
}
catch (Exception e)
{
msg1.what = MSG_ERROR;
msg1.obj = e.getMessage();
}
uiHandler.sendMessage(msg1);
}
else
{
Message msg2 = new Message();
msg2.what = MSG_STOP;
msg2.obj = "Stop to write to SD 'acc.txt'";
uiHandler.sendMessage(msg2);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
public void onStartClick(View view)
{
start();
}
public void onStopClick(View view)
{
stop();
}
public void onReadClick(View view)
{
etshowval.setText(ReadFile(filepath));
}
private synchronized void start()
{
mrunning = true;
}
private synchronized void stop()
{
mrunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
#Override
public void onSensorChanged(SensorEvent sensorEvent)
{
// TODO Auto-generated method stub
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
x = sensorEvent.values[0];
y = sensorEvent.values[1];
z = sensorEvent.values[2];
acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
tvx.setText("X = "+ String.valueOf(x));
tvy.setText("Y = "+ String.valueOf(y));
tvz.setText("Z = "+ String.valueOf(z));
}
}
public void CreateFile(String path)
{
File f = new File(path);
try {
Log.d("ACTIVITY", "Create a File.");
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String ReadFile (String filepath)
{
mBufferedReader = null;
String tmp = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedReader = new BufferedReader(new FileReader(filepath));
// Read string
while ((tmp = mBufferedReader.readLine()) != null)
{
tmp += "\n";
read_str += tmp;
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return read_str;
}
public void WriteFile(String filepath, String str)
{
mBufferedWriter = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
mBufferedWriter.write(str);
mBufferedWriter.newLine();
mBufferedWriter.flush();
mBufferedWriter.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean FileIsExist(String filepath)
{
File f = new File(filepath);
if (! f.exists())
{
Log.e("ACTIVITY", "File does not exist.");
return false;
}
else
return true;
}
#Override
protected void onPause()
{
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
super.onPause();
}
}
textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;
You didn't declare the "textView" or "acc" variables anywhere
Even after fixing this issue, the code sample you provided above, will end in having a file with only the most recent sensor event records only.. because it creates a new file everytime a sensor event happens, writes the measurements to it, and closes it. When a new measurement is delivered a new file will be created using the same name and so will remove the old entry.
A Good practice to perform that task might be as follows:
Store the file stream as a private variable in your activity
In the start button's click event handler, open the file or create it if not existing .. and store its stream to the private variable of your activity..Also register listener to the accelerometer sensor events.
In the onSensorChanged event, append the new measurements to the file stream
In the stop button's click event handler, unregister the lisetener, and close the file stream.