简体   繁体   中英

Adding a progress dialog to app whilst loading data from a volley

I'm trying to add a progress dialog to my app whilst it loads data from a volley. I've tried a few ways but i'm currently following this tutorial http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/ and was hoping it would look like the example used there. Please could someone take a look at my code so far! i'm not getting errors but it is not displaying like the example. As you can see i've created the method in onCreate and called the hide method in my response listeners.

Thank you!

MainActivity.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();

        }
    };

}

activity_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>

Try Below Code

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);

Try this:

progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);

By the way, you should have an introduction with AsyncTask and should display ProgressDialog in that task.

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);
        }

I know I am late for this topic(5 years, 5 months late), but this might help future readers. It's quite easy to do this. Just create a Progress Dialog first before creating the StringRequest from volley.

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);

Then after creating the String request, override the onRespose method and DISMISS the progress dialog there.(You'll be showing the Progress Dialog when you add the request to the request queue)

 StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() 
{
        @Override
        public void onResponse(String response) 
        {
            progressDialog.dismiss();
        }
});

Or this will be the same when using Lamda expressions like this,

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, response -> 
{
       progressDialog.dismiss();
});

Then after adding the ErrorListeners and the user agents, show the Progress Dialog after adding the StringRequest to the queue.

RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
progressDialog.show();

That's it. All done. Here's the full code.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM