[英]Adding a progress dialog to app whilst loading data from a volley
我正在嘗試向我的應用程序添加一個進度對話框,同時它從一個截擊加載數據。 我嘗試了幾種方法,但我目前正在關注本教程http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/並希望它看起來像那里使用的例子。 到目前為止,請有人看看我的代碼! 我沒有收到錯誤,但它不像示例那樣顯示。 如您所見,我在 onCreate 中創建了該方法,並在響應偵聽器中調用了 hide 方法。
謝謝!
主活動.java
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
LinearLayout layout;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading Articles...");
pDialog.show();
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
@Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
private SearchView.OnQueryTextListener searchQueryListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent(MainActivity.this, SearchResultsActivity.class);
searchIntent.putExtra("query", query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
hidePDialog();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
hidePDialog();
}
};
}
活動_main.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:id="@+id/newsListItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/progressbar_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Loading data..." />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#C0C0C0" />
</LinearLayout>
<GridView
android:id="@+id/newsFeedList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
試試下面的代碼
ProgressDialog pd = ProgressDialog.show(context,null,"Please wait");
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if(pd!=null && pd.isShowing())
pd.dismiss();
// Code
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(pd!=null && pd.isShowing())
pd.dismiss();
// Code
});
app.requestQueue.add(jsonRequest);
嘗試這個:
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
順便說一句,您應該對AsyncTask
進行介紹,並且應該在該任務中顯示ProgressDialog
。
private ProgressBarCircularIndetermininate pBar;
pBar = (ProgressBarCircularIndetermininate) getView().findViewById(R.id.progressBarCircularIndetermininate);
private void makeJsonRequest() {
showProgressDialog();
StringRequest strReq = new StringRequest(Method.POST, URL.DASHBOARD, new Response.Listener<String>(){
@Override
public void onResponse(String response){
try {
} catch (JSONException e) {
e.printStackTrace();
}
}
hideProgressDialog();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
AppController.getInstance().volleyErrorHandler(error);
hideProgressDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userID);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT, NUMOFATTEMPT, BACKOFMULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showProgressDialog() {
if (!pBar.isShown())
pBar.setVisibility(View.VISIBLE);
}
private void hideProgressDialog() {
if (pBar.isShown())
pBar.setVisibility(View.GONE);
}
我知道我在這個主題上遲到了(晚了 5 年 5 個月),但這可能會對未來的讀者有所幫助。 要做到這一點很容易。 在從 volley 創建StringRequest
之前,只需先創建一個進度對話框。
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Set Title");
progressDialog.setMessage("Set A Message");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// There are 3 styles, You'll figure it out :)
progressDialog.setCancelable(false);
progressDialog.setIcon(R.drawable.open_food_facts_symbol);
然后在創建字符串請求后,覆蓋onRespose
方法並在那里關閉進度對話框。(將請求添加到請求隊列時,您將顯示進度對話框)
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
progressDialog.dismiss();
}
});
或者在使用這樣的 Lamda 表達式時也是如此,
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, response ->
{
progressDialog.dismiss();
});
然后在添加ErrorListeners
和用戶代理后,在將StringRequest
添加到隊列后顯示進度對話框。
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
progressDialog.show();
就是這樣。 全部完成。 這是完整的代碼。
private void parseApiData(String productBarcode)
{
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Connecting To the Database");
progressDialog.setMessage("We are not establishing a Connection to the Open Food Facts Database...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.setIcon(R.drawable.open_food_facts_symbol);
//progressDialog.
String url = "this will be your url..";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, response ->
{
progressDialog.dismiss();
}
} catch (JSONException e) {
progressDialog.dismiss();
e.printStackTrace();
} catch (Exception e) {
progressDialog.dismiss();
statusCode = 0;
}
}, volleyError -> {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError)
{
Toast.makeText(context, "Connection Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof AuthFailureError)
{
Toast.makeText(context, "Authentication/ Auth Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof ServerError)
{
Toast.makeText(context, "Server Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof NetworkError)
{
Toast.makeText(context, "Network Error !", Toast.LENGTH_LONG).show();
}
else if (volleyError instanceof ParseError)
{
Toast.makeText(context, "Parse Error !", Toast.LENGTH_LONG).show();
}
activity.finish();
})
{
//Assigning the User Agent
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("User-Agent:", "Your custom user agent here");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
progressDialog.show();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.