Я пытаюсь отобразить индикатор выполнения при получении данных из API, но он не отображается. Я предполагаю, что у меня просто вызов индикатора выполнения не в том месте, но ничего из того, что я сделал до сих пор, не устранило проблему. Ниже приведен код активности. Все, что я хочу, - это чтобы индикатор выполнения был виден до загрузки данных.
package com.hmadland.paranoia
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_profile.*
import org.json.JSONObject
import com.android.volley.AuthFailureError
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.hmadland.paranoia.R.layout.activity_profile
class Profile : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
//get token from login
val token = intent.getStringExtra("token")
//get email to find PlayerID in sharedPref
val email = intent.getStringExtra("email")
//get PlayerID from sharedPref
val mypref = getSharedPreferences(email, Context.MODE_PRIVATE)
val PlayerID = mypref.getString(email, "")
val progressBar: ProgressBar = this.progressBar1
// task is run on a thread
Thread(Runnable {
// dummy thread mimicking some operation whose progress cannot be tracked
// display the indefinite progressbar
[email protected](java.lang.Runnable {
progressBar1.visibility = View.VISIBLE
})
// performing operation
try {
var url = "https://elimination.azurewebsites.net/api/Players/GetPlayer?id = "+ PlayerID
val que = Volley.newRequestQueue(this@Profile)
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET, url, null,
Response.Listener<JSONObject> { response ->
//get UserName
userName.text = response.get("UserName").toString()
//get profile
profile.text = response.get("Profile").toString()
//get photo
Glide.with(this).load(response.get("PhotoUrl")).into(ProfilePic)
//round photo
Glide.with(this).load(response.get("PhotoUrl")).apply(RequestOptions.circleCropTransform()).into(ProfilePic)
},
Response.ErrorListener { error -> Log.e("error is ", "" + error) }
)
//This is for Headers If Needed
@Throws(AuthFailureError::class)
fun getHeaders(): Map<String, String> {
val params = HashMap<String, String>()
params.put("Content-Type", "application/json; charset=UTF-8")
params.put("token", token)
return params
}
que.add(jsonObjectRequest)
} catch (e: InterruptedException) {
e.printStackTrace()
}
// when the task is completed, make progressBar gone
[email protected](java.lang.Runnable {
progressBar1.visibility = View.GONE
})
}
).start()
///////////buttons to other views//////////////////////////////
//go to current target view
CurrentGame.setOnClickListener{
val intent = Intent(this, Target::class.java)
intent.putExtra("token", token)
intent.putExtra("email", email)
startActivity(intent)
}
Inventory.setOnClickListener{
val intent = Intent(this, com.hmadland.paranoia.Inventory::class.java)
startActivity(intent)
}
coming.setOnClickListener{
val intent = Intent(this, UpcomingGames::class.java)
startActivity(intent)
}
////////////////////////////////////////////////////////////////////
}
}
Это 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"
tools:context = "com.hmadland.paranoia.Profile">
<ScrollView xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:background = "@color/colorPrimary"
android:fitsSystemWindows = "true"
tools:layout_editor_absoluteX = "16dp"
tools:layout_editor_absoluteY = "101dp">
<LinearLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical"
android:paddingLeft = "24dp"
android:paddingRight = "24dp"
android:paddingTop = "56dp"
>
<ProgressBar
android:id = "@+id/progressBar1"
android:layout_width = "match_parent"
android:layout_height = "46dp"
android:padding = "10dp"
/>
<ImageView
android:id = "@+id/ProfilePic"
android:layout_width = "match_parent"
android:layout_height = "132dp"
android:layout_centerHorizontal = "true"
android:adjustViewBounds = "true"
android:maxHeight = "300px"
android:maxWidth = "450px"
android:minHeight = "300px"
android:minWidth = "450px" />
<TextView
android:id = "@+id/userName"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:textAlignment = "center"
android:textColor = "@color/colorAccent"
android:textSize = "18sp"
android:textStyle = "bold" />
<TextView
android:id = "@+id/profile"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:paddingBottom = "12dp"
android:paddingTop = "12dp"
android:textColor = "@color/colorAccent"
android:textSize = "20sp"
android:textStyle = "bold" />
<LinearLayout
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal"
android:gravity = "center"
>
<Button
android:id = "@+id/CurrentGame"
android:layout_width = "90dp"
android:layout_height = "80dp"
android:layout_margin = "10dp"
android:background = "@drawable/round"
android:fontFamily = "monospace"
android:text = "Target"
android:textColor = "@color/colorAccent"
android:textSize = "18sp"
android:textStyle = "bold" />
<Button
android:id = "@+id/Inventory"
android:layout_width = "90dp"
android:layout_height = "80dp"
android:layout_margin = "10dp"
android:background = "@drawable/round"
android:fontFamily = "monospace"
android:text = "Stats"
android:textColor = "@color/colorAccent"
android:textSize = "18sp"
android:textStyle = "bold" />
</LinearLayout>
<LinearLayout
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal"
android:gravity = "center">
<Button
android:id = "@+id/coming"
android:layout_width = "90dp"
android:layout_height = "80dp"
android:layout_margin = "10dp"
android:shape = "oval"
android:background = "@drawable/round"
android:fontFamily = "monospace"
android:text = "Games"
android:textColor = "@color/colorAccent"
android:textSize = "18sp"
android:textStyle = "bold" />
<Button
android:id = "@+id/edit"
android:layout_width = "90dp"
android:layout_height = "80dp"
android:layout_margin = "10dp"
android:background = "@drawable/round"
android:fontFamily = "monospace"
android:text = "Edit"
android:textColor = "@color/colorAccent"
android:textSize = "18sp"
android:textStyle = "bold" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
Вы должны добавить свой xml-макет, в который вы включили progressBar1 и полный код активности.
ProgressBar извините
Я думаю, это связано с тем фактом, что Volley.newRequestQueue(this@Profile) возвращает RequestQueue, который ставит запрос на выполнение через его метод add. Однако метод add немедленно возвращается, не дожидаясь выполнения самого вызова.
Поскольку в вашем коде вы запускаете изменение видимости индикатора выполнения непосредственно после вызова add, вы, вероятно, не видите, что полоса отображается вообще (потому что весь код работает слишком быстро, чтобы заметить). Что вы, вероятно, захотите, так это скрыть полосу в обратном вызове Response.Listener (и, вероятно, также в Response.ErrorListener), потому что это обратные вызовы, которые Volley вызовет по завершении (с ошибкой или нет).
Таким образом, вы помещаете запрос в очередь и показываете индикатор выполнения, когда Volley завершает работу, он сообщит вам об этом через обратные вызовы, и это будет место, где можно снова скрыть индикатор выполнения.
Вы имеете в виду Spinner (developer.android.com/guide/topics/ui/controls/spinn er) или ProgressBar?