Итак, я начну с объяснения основной проблемы. Приложение работает как задумано, это функции по модульному принципу, но при объединении происходит разрыв потока информации.
У меня есть навбар, который "обновляет" фрагмент. В этом фрагменте перечислены лиги, и при нажатии на эти списки отображается классификационная лига. Возникает странная задержка: только после двух обновлений что-либо отображается, будь то лига удаления, лига присоединения и т. д. Так что я просто выложу сюда свой код в надежде, что кто-нибудь поумнее обнаружит ошибку. Заранее спасибо, если вам нужен более конкретный код, спросите, я просто подумал, что это наиболее важно для проблемы.
Вот код фрагмента:
package projeto.fantasyleague.fragments
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.textfield.TextInputEditText
import org.json.JSONException
import org.json.JSONObject
import projeto.fantasyleague.DashboardActivity
import projeto.fantasyleague.R
import projeto.fantasyleague.adapter.ClassificationAdapter
import projeto.fantasyleague.adapter.LeagueAdapter
import projeto.fantasyleague.model.ClassificationItem
import projeto.fantasyleague.model.League
import projeto.fantasyleague.utils.ApiConstants
class LeagueListFragment : Fragment() {
companion object {
lateinit var recyclerViewList : RecyclerView
lateinit var recyclerViewClassification : RecyclerView
val listaLigas = ArrayList()
val classification = ArrayList()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_league_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val sharedPreferences = requireContext().getSharedPreferences("pmLogin", Context.MODE_PRIVATE)
val currentUID = sharedPreferences.getInt("uid", -1) // Default to -1 if UID is not found
val authToken = sharedPreferences.getString("auth_token", "")
val inputInvitationCode: TextInputEditText = view.findViewById(R.id.input_invitation_code)
val inputLeagueName: TextInputEditText = view.findViewById(R.id.input_league_name)
val buttonJoinLeague: Button = view.findViewById(R.id.button_join_league)
val buttonCreateLeague: Button = view.findViewById(R.id.button_create_league)
// Set button click listeners
buttonJoinLeague.setOnClickListener {
val invitationCode = inputInvitationCode.text.toString()
if (invitationCode.isNotEmpty()) {
joinLeague(authToken!!, invitationCode)
} else {
Toast.makeText(context, "Please enter a valid invitation code", Toast.LENGTH_SHORT).show()
}
}
buttonCreateLeague.setOnClickListener {
val leagueName = inputLeagueName.text.toString()
if (leagueName.isNotEmpty()) {
createLeague(authToken!!, leagueName, )
} else {
Toast.makeText(context, "Please enter a league name", Toast.LENGTH_SHORT).show()
}
}
recyclerViewList = view.findViewById(R.id.recycler_leagues)
recyclerViewList.layoutManager = LinearLayoutManager(context)
recyclerViewClassification = view.findViewById(R.id.recycler_classification)
recyclerViewClassification.layoutManager = LinearLayoutManager(context)
if (!authToken.isNullOrEmpty()) {
fetchLeagues(authToken)
// After leagues are fetched, notify the adapter
recyclerViewList.adapter = LeagueAdapter(
listaLigas,
currentUID,
onClipboardClick = { invitationCode ->
val clipboardManager = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Invitation Code", invitationCode)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(requireContext(), "Invitation code copied to clipboard!", Toast.LENGTH_SHORT).show()
},
onTrashClick = { leagueId ->
deleteLeague(authToken, leagueId)
},
onLeagueClick = { leagueId ->
fetchClassification(authToken, leagueId)
}
)
recyclerViewList.adapter?.notifyDataSetChanged()
if (listaLigas.isNotEmpty()) {
fetchClassification(authToken, listaLigas[0].id)
recyclerViewClassification.adapter = ClassificationAdapter(classification, currentUID)
recyclerViewClassification.adapter?.notifyDataSetChanged()
}
}
}
private fun deleteLeague(authToken: String, leagueId: Int) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.DELETE_LEAGUE
val requestBody = JSONObject().apply {
put("leagueId", leagueId)
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.POST, url, requestBody,
{ response ->
try {
if (response.getBoolean("success")) {
Toast.makeText(requireContext(), "League deleted successfully!", Toast.LENGTH_SHORT).show()
fetchLeagues(authToken)
recyclerViewList.adapter?.notifyDataSetChanged()
} else {
Toast.makeText(requireContext(), "Failed to delete league.", Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing response: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error deleting league: ${error.networkResponse?.statusCode} - ${error.message}")
Toast.makeText(requireContext(), "Error deleting league ${error.message}", Toast.LENGTH_SHORT).show()
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
headers["Action"] = "DELETE"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun joinLeague(authToken: String, invitationCode: String) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.JOIN_LEAGUE
val requestBody = JSONObject().apply {
put("invitationCode", invitationCode)
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.POST, url, requestBody,
{ response ->
try {
if (response.getBoolean("success")) {
Toast.makeText(requireContext(), "Successfully joined the league!", Toast.LENGTH_SHORT).show()
fetchLeagues(authToken) // Refresh the list of leagues after joining
recyclerViewList.adapter?.notifyDataSetChanged()
} else {
Toast.makeText(requireContext(), "Failed to join the league.", Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing response: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error joining league: ${error.networkResponse?.statusCode} - ${error.message}")
Toast.makeText(requireContext(), "Error joining league", Toast.LENGTH_SHORT).show()
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun createLeague(authToken: String, leagueName: String) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.CREATE_LEAGUE
val requestBody = JSONObject().apply {
put("leaguename", leagueName)
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.POST, url, requestBody,
{ response ->
try {
if (response.getBoolean("success")) {
Toast.makeText(requireContext(), "League created successfully!", Toast.LENGTH_SHORT).show()
fetchLeagues(authToken) // Refresh the list of leagues after creation
recyclerViewList.adapter?.notifyDataSetChanged()
} else {
Toast.makeText(requireContext(), "Failed to create league.", Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing response: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error creating league: ${error.networkResponse?.statusCode} - ${error.message}")
Toast.makeText(requireContext(), "Error creating league", Toast.LENGTH_SHORT).show()
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
headers["Action"] = "POST"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun fetchLeagues(authToken: String) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.FETCH_LEAGUES
val jsonObjectRequest = object : JsonObjectRequest(
Method.GET, url, null,
{ response ->
try {
val leaguesArray = response.getJSONArray("leagues")
listaLigas.clear()
listaLigas.add(League(name = "Global League"))
for (i in 0 until leaguesArray.length()) {
val leagueObject = leaguesArray.getJSONObject(i)
val league = League(
id = leagueObject.getInt("LeagueID"),
name = leagueObject.getString("leaguename"),
ownerId = leagueObject.getInt("HostID"),
invitationCode = leagueObject.getString("invitationCode")
)
listaLigas.add(league)
}
Log.d("LeagueListFragment", "Leagues fetched successfully. Count: ${listaLigas.size}")
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing leagues JSON: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error fetching leagues: ${error.networkResponse?.statusCode} - ${error.message}")
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Action"] = "GET"
headers["Content-Type"] = "application/json"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun fetchClassification(authToken: String, leagueId: Int) {
val queue = Volley.newRequestQueue(requireContext())
var url = ""
val requestBody: JSONObject?
if(leagueId == -1){
url = ApiConstants.GENERAL_CLASSIFICATION
requestBody = null
}else{
url = ApiConstants.CLASSIFICATION
requestBody = JSONObject().apply {
put("leagueId", leagueId)
}
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.GET, url, requestBody,
{ response ->
try {
val classificationArray = response.getJSONArray("classification")
classification.clear()
for (i in 0 until classificationArray.length()) {
val classificationObject = classificationArray.getJSONObject(i)
val item = ClassificationItem(
rank = i + 1,
teamName = classificationObject.getString("teamname"),
teamID = classificationObject.getInt("TeamID"),
ownerID = classificationObject.getInt("userID"),
userName = classificationObject.getString("username"),
points = classificationObject.optString("totalPoints","0")
)
classification.add(item)
}
Log.d("LeagueListFragment", "Classification fetched successfully. Count: ${classification.size}")
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing classification JSON: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error fetching classification: ${error.networkResponse?.statusCode} - ${error.message}")
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
headers["Action"] = "GET"
return headers
}
}
queue.add(jsonObjectRequest)
}
}
Адаптер списка лиг
package projeto.fantasyleague.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import projeto.fantasyleague.R
import projeto.fantasyleague.model.League
class LeagueAdapter(
private val leagues: ArrayList,
private val currentUserId: Int,
private val onClipboardClick: (String) -> Unit,
private val onTrashClick: (Int) -> Unit,
private val onLeagueClick: (Int) -> Unit
) : RecyclerView.Adapter() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val leagueName: TextView = itemView.findViewById(R.id.text_league_name)
val iconCrown: ImageView = itemView.findViewById(R.id.icon_crown)
val iconClipboard: ImageView = itemView.findViewById(R.id.icon_clipboard)
val iconTrash: ImageView = itemView.findViewById(R.id.icon_trash)
val card: CardView = itemView.findViewById(R.id.cardLeague)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_league, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val league = leagues[position]
holder.leagueName.text = league.name
holder.card.setOnClickListener {
onLeagueClick(league.id)
}
if (league.id == -1) {
holder.card.setCardBackgroundColor(
ContextCompat.getColor(holder.card.context, R.color.ocean_blue)
)
}
// Show icons only for league owners
if (league.ownerId == currentUserId) {
holder.iconCrown.visibility = View.VISIBLE
holder.iconClipboard.visibility = View.VISIBLE
holder.iconTrash.visibility = View.VISIBLE
// Set click listeners
holder.iconClipboard.setOnClickListener {
onClipboardClick(league.invitationCode)
}
holder.iconTrash.setOnClickListener {
onTrashClick(league.id)
}
} else {
holder.iconCrown.visibility = View.GONE
holder.iconClipboard.visibility = View.GONE
holder.iconTrash.visibility = View.GONE
}
}
override fun getItemCount(): Int = leagues.size
}
Адаптер классификации
package projeto.fantasyleague.adapter
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import projeto.fantasyleague.R
import projeto.fantasyleague.databinding.ItemClassificationBinding
import projeto.fantasyleague.model.ClassificationItem
class ClassificationAdapter(private val items: ArrayList,private val currentUserId: Int) : RecyclerView.Adapter() {
// ViewHolder to hold the views
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txtRank: TextView = itemView.findViewById(R.id.text_rank)
val txtTeamName: TextView = itemView.findViewById(R.id.text_team_name)
val txtUserName: TextView = itemView.findViewById(R.id.text_user_name)
val txtPoints: TextView = itemView.findViewById(R.id.text_points)
val card: CardView = itemView.findViewById(R.id.classCard)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_classification, parent, false)
return ViewHolder(view)
}
// Bind the data to the ViewHolder
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Log.d("Adapter", "Binding data for position: $position")
val classif = items[position]
holder.txtRank.text = classif.rank.toString()
holder.txtTeamName.text = classif.teamName
holder.txtUserName.text = classif.userName
holder.txtPoints.text = classif.points.toString()
val rank = classif.rank
// Use a when statement to set the background color based on rank
val colorRes = when (rank) {
1 -> R.color.gold
2 -> R.color.silver
3 -> R.color.bronze
else -> R.color.white // Optional default color for ranks other than 1, 2, or 3
}
holder.card.setCardBackgroundColor(
ContextCompat.getColor(holder.card.context, colorRes)
)
}
// Return the total number of items in the list
override fun getItemCount(): Int {
return items.size
}
}
DashboardActivity
class DashboardActivity : AppCompatActivity() {
private val binding by lazy {
ActivityDashboardBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val nav = binding.navbar
// Set click listeners for navbar items
nav.navTrophy.setOnClickListener{
binding.fragmentContainer.removeAllViews()
Toast.makeText(this, "Trophy clicked!", Toast.LENGTH_SHORT).show()
}
nav.navLeagues.setOnClickListener{
binding.fragmentContainer.removeAllViews()
supportFragmentManager
.beginTransaction()
.replace(R.id.fragmentContainer, LeagueListFragment())
.commit()
Toast.makeText(this, "Leagues clicked!", Toast.LENGTH_SHORT).show()
}
nav.navTeam.setOnClickListener{
binding.fragmentContainer.removeAllViews()
Toast.makeText(this, "Team clicked!", Toast.LENGTH_SHORT).show()
}
}
}
````
Sorry about the dump!
Подробнее здесь: https://stackoverflow.com/questions/792 ... ay-android
Задержка отображения информации Android ⇐ Android
Форум для тех, кто программирует под Android
1732654101
Anonymous
Итак, я начну с объяснения основной проблемы. Приложение работает как задумано, это функции по модульному принципу, но при объединении происходит разрыв потока информации.
У меня есть навбар, который "обновляет" фрагмент. В этом фрагменте перечислены лиги, и при нажатии на эти списки отображается классификационная лига. Возникает странная задержка: только после двух обновлений что-либо отображается, будь то лига удаления, лига присоединения и т. д. Так что я просто выложу сюда свой код в надежде, что кто-нибудь поумнее обнаружит ошибку. Заранее спасибо, если вам нужен более конкретный код, спросите, я просто подумал, что это наиболее важно для проблемы.
Вот код фрагмента:
package projeto.fantasyleague.fragments
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.textfield.TextInputEditText
import org.json.JSONException
import org.json.JSONObject
import projeto.fantasyleague.DashboardActivity
import projeto.fantasyleague.R
import projeto.fantasyleague.adapter.ClassificationAdapter
import projeto.fantasyleague.adapter.LeagueAdapter
import projeto.fantasyleague.model.ClassificationItem
import projeto.fantasyleague.model.League
import projeto.fantasyleague.utils.ApiConstants
class LeagueListFragment : Fragment() {
companion object {
lateinit var recyclerViewList : RecyclerView
lateinit var recyclerViewClassification : RecyclerView
val listaLigas = ArrayList()
val classification = ArrayList()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_league_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val sharedPreferences = requireContext().getSharedPreferences("pmLogin", Context.MODE_PRIVATE)
val currentUID = sharedPreferences.getInt("uid", -1) // Default to -1 if UID is not found
val authToken = sharedPreferences.getString("auth_token", "")
val inputInvitationCode: TextInputEditText = view.findViewById(R.id.input_invitation_code)
val inputLeagueName: TextInputEditText = view.findViewById(R.id.input_league_name)
val buttonJoinLeague: Button = view.findViewById(R.id.button_join_league)
val buttonCreateLeague: Button = view.findViewById(R.id.button_create_league)
// Set button click listeners
buttonJoinLeague.setOnClickListener {
val invitationCode = inputInvitationCode.text.toString()
if (invitationCode.isNotEmpty()) {
joinLeague(authToken!!, invitationCode)
} else {
Toast.makeText(context, "Please enter a valid invitation code", Toast.LENGTH_SHORT).show()
}
}
buttonCreateLeague.setOnClickListener {
val leagueName = inputLeagueName.text.toString()
if (leagueName.isNotEmpty()) {
createLeague(authToken!!, leagueName, )
} else {
Toast.makeText(context, "Please enter a league name", Toast.LENGTH_SHORT).show()
}
}
recyclerViewList = view.findViewById(R.id.recycler_leagues)
recyclerViewList.layoutManager = LinearLayoutManager(context)
recyclerViewClassification = view.findViewById(R.id.recycler_classification)
recyclerViewClassification.layoutManager = LinearLayoutManager(context)
if (!authToken.isNullOrEmpty()) {
fetchLeagues(authToken)
// After leagues are fetched, notify the adapter
recyclerViewList.adapter = LeagueAdapter(
listaLigas,
currentUID,
onClipboardClick = { invitationCode ->
val clipboardManager = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Invitation Code", invitationCode)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(requireContext(), "Invitation code copied to clipboard!", Toast.LENGTH_SHORT).show()
},
onTrashClick = { leagueId ->
deleteLeague(authToken, leagueId)
},
onLeagueClick = { leagueId ->
fetchClassification(authToken, leagueId)
}
)
recyclerViewList.adapter?.notifyDataSetChanged()
if (listaLigas.isNotEmpty()) {
fetchClassification(authToken, listaLigas[0].id)
recyclerViewClassification.adapter = ClassificationAdapter(classification, currentUID)
recyclerViewClassification.adapter?.notifyDataSetChanged()
}
}
}
private fun deleteLeague(authToken: String, leagueId: Int) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.DELETE_LEAGUE
val requestBody = JSONObject().apply {
put("leagueId", leagueId)
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.POST, url, requestBody,
{ response ->
try {
if (response.getBoolean("success")) {
Toast.makeText(requireContext(), "League deleted successfully!", Toast.LENGTH_SHORT).show()
fetchLeagues(authToken)
recyclerViewList.adapter?.notifyDataSetChanged()
} else {
Toast.makeText(requireContext(), "Failed to delete league.", Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing response: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error deleting league: ${error.networkResponse?.statusCode} - ${error.message}")
Toast.makeText(requireContext(), "Error deleting league ${error.message}", Toast.LENGTH_SHORT).show()
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
headers["Action"] = "DELETE"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun joinLeague(authToken: String, invitationCode: String) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.JOIN_LEAGUE
val requestBody = JSONObject().apply {
put("invitationCode", invitationCode)
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.POST, url, requestBody,
{ response ->
try {
if (response.getBoolean("success")) {
Toast.makeText(requireContext(), "Successfully joined the league!", Toast.LENGTH_SHORT).show()
fetchLeagues(authToken) // Refresh the list of leagues after joining
recyclerViewList.adapter?.notifyDataSetChanged()
} else {
Toast.makeText(requireContext(), "Failed to join the league.", Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing response: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error joining league: ${error.networkResponse?.statusCode} - ${error.message}")
Toast.makeText(requireContext(), "Error joining league", Toast.LENGTH_SHORT).show()
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun createLeague(authToken: String, leagueName: String) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.CREATE_LEAGUE
val requestBody = JSONObject().apply {
put("leaguename", leagueName)
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.POST, url, requestBody,
{ response ->
try {
if (response.getBoolean("success")) {
Toast.makeText(requireContext(), "League created successfully!", Toast.LENGTH_SHORT).show()
fetchLeagues(authToken) // Refresh the list of leagues after creation
recyclerViewList.adapter?.notifyDataSetChanged()
} else {
Toast.makeText(requireContext(), "Failed to create league.", Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing response: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error creating league: ${error.networkResponse?.statusCode} - ${error.message}")
Toast.makeText(requireContext(), "Error creating league", Toast.LENGTH_SHORT).show()
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
headers["Action"] = "POST"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun fetchLeagues(authToken: String) {
val queue = Volley.newRequestQueue(requireContext())
val url = ApiConstants.FETCH_LEAGUES
val jsonObjectRequest = object : JsonObjectRequest(
Method.GET, url, null,
{ response ->
try {
val leaguesArray = response.getJSONArray("leagues")
listaLigas.clear()
listaLigas.add(League(name = "Global League"))
for (i in 0 until leaguesArray.length()) {
val leagueObject = leaguesArray.getJSONObject(i)
val league = League(
id = leagueObject.getInt("LeagueID"),
name = leagueObject.getString("leaguename"),
ownerId = leagueObject.getInt("HostID"),
invitationCode = leagueObject.getString("invitationCode")
)
listaLigas.add(league)
}
Log.d("LeagueListFragment", "Leagues fetched successfully. Count: ${listaLigas.size}")
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing leagues JSON: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error fetching leagues: ${error.networkResponse?.statusCode} - ${error.message}")
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Action"] = "GET"
headers["Content-Type"] = "application/json"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun fetchClassification(authToken: String, leagueId: Int) {
val queue = Volley.newRequestQueue(requireContext())
var url = ""
val requestBody: JSONObject?
if(leagueId == -1){
url = ApiConstants.GENERAL_CLASSIFICATION
requestBody = null
}else{
url = ApiConstants.CLASSIFICATION
requestBody = JSONObject().apply {
put("leagueId", leagueId)
}
}
val jsonObjectRequest = object : JsonObjectRequest(
Method.GET, url, requestBody,
{ response ->
try {
val classificationArray = response.getJSONArray("classification")
classification.clear()
for (i in 0 until classificationArray.length()) {
val classificationObject = classificationArray.getJSONObject(i)
val item = ClassificationItem(
rank = i + 1,
teamName = classificationObject.getString("teamname"),
teamID = classificationObject.getInt("TeamID"),
ownerID = classificationObject.getInt("userID"),
userName = classificationObject.getString("username"),
points = classificationObject.optString("totalPoints","0")
)
classification.add(item)
}
Log.d("LeagueListFragment", "Classification fetched successfully. Count: ${classification.size}")
} catch (e: JSONException) {
Log.e("LeagueListFragment", "Error parsing classification JSON: ${e.message}")
}
},
{ error ->
Log.e("LeagueListFragment", "Error fetching classification: ${error.networkResponse?.statusCode} - ${error.message}")
}
) {
override fun getHeaders(): MutableMap {
val headers = HashMap()
headers["Authorization"] = "Bearer $authToken"
headers["Content-Type"] = "application/json"
headers["Action"] = "GET"
return headers
}
}
queue.add(jsonObjectRequest)
}
}
Адаптер списка лиг
package projeto.fantasyleague.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import projeto.fantasyleague.R
import projeto.fantasyleague.model.League
class LeagueAdapter(
private val leagues: ArrayList,
private val currentUserId: Int,
private val onClipboardClick: (String) -> Unit,
private val onTrashClick: (Int) -> Unit,
private val onLeagueClick: (Int) -> Unit
) : RecyclerView.Adapter() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val leagueName: TextView = itemView.findViewById(R.id.text_league_name)
val iconCrown: ImageView = itemView.findViewById(R.id.icon_crown)
val iconClipboard: ImageView = itemView.findViewById(R.id.icon_clipboard)
val iconTrash: ImageView = itemView.findViewById(R.id.icon_trash)
val card: CardView = itemView.findViewById(R.id.cardLeague)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_league, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val league = leagues[position]
holder.leagueName.text = league.name
holder.card.setOnClickListener {
onLeagueClick(league.id)
}
if (league.id == -1) {
holder.card.setCardBackgroundColor(
ContextCompat.getColor(holder.card.context, R.color.ocean_blue)
)
}
// Show icons only for league owners
if (league.ownerId == currentUserId) {
holder.iconCrown.visibility = View.VISIBLE
holder.iconClipboard.visibility = View.VISIBLE
holder.iconTrash.visibility = View.VISIBLE
// Set click listeners
holder.iconClipboard.setOnClickListener {
onClipboardClick(league.invitationCode)
}
holder.iconTrash.setOnClickListener {
onTrashClick(league.id)
}
} else {
holder.iconCrown.visibility = View.GONE
holder.iconClipboard.visibility = View.GONE
holder.iconTrash.visibility = View.GONE
}
}
override fun getItemCount(): Int = leagues.size
}
Адаптер классификации
package projeto.fantasyleague.adapter
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import projeto.fantasyleague.R
import projeto.fantasyleague.databinding.ItemClassificationBinding
import projeto.fantasyleague.model.ClassificationItem
class ClassificationAdapter(private val items: ArrayList,private val currentUserId: Int) : RecyclerView.Adapter() {
// ViewHolder to hold the views
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txtRank: TextView = itemView.findViewById(R.id.text_rank)
val txtTeamName: TextView = itemView.findViewById(R.id.text_team_name)
val txtUserName: TextView = itemView.findViewById(R.id.text_user_name)
val txtPoints: TextView = itemView.findViewById(R.id.text_points)
val card: CardView = itemView.findViewById(R.id.classCard)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_classification, parent, false)
return ViewHolder(view)
}
// Bind the data to the ViewHolder
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Log.d("Adapter", "Binding data for position: $position")
val classif = items[position]
holder.txtRank.text = classif.rank.toString()
holder.txtTeamName.text = classif.teamName
holder.txtUserName.text = classif.userName
holder.txtPoints.text = classif.points.toString()
val rank = classif.rank
// Use a when statement to set the background color based on rank
val colorRes = when (rank) {
1 -> R.color.gold
2 -> R.color.silver
3 -> R.color.bronze
else -> R.color.white // Optional default color for ranks other than 1, 2, or 3
}
holder.card.setCardBackgroundColor(
ContextCompat.getColor(holder.card.context, colorRes)
)
}
// Return the total number of items in the list
override fun getItemCount(): Int {
return items.size
}
}
DashboardActivity
class DashboardActivity : AppCompatActivity() {
private val binding by lazy {
ActivityDashboardBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val nav = binding.navbar
// Set click listeners for navbar items
nav.navTrophy.setOnClickListener{
binding.fragmentContainer.removeAllViews()
Toast.makeText(this, "Trophy clicked!", Toast.LENGTH_SHORT).show()
}
nav.navLeagues.setOnClickListener{
binding.fragmentContainer.removeAllViews()
supportFragmentManager
.beginTransaction()
.replace(R.id.fragmentContainer, LeagueListFragment())
.commit()
Toast.makeText(this, "Leagues clicked!", Toast.LENGTH_SHORT).show()
}
nav.navTeam.setOnClickListener{
binding.fragmentContainer.removeAllViews()
Toast.makeText(this, "Team clicked!", Toast.LENGTH_SHORT).show()
}
}
}
````
Sorry about the dump!
Подробнее здесь: [url]https://stackoverflow.com/questions/79228225/delay-on-info-display-android[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия