user2953989
user2953989

Reputation: 2979

Adding a progress spinner to app while data from volley loads

I'm trying to add a progress spinner at the top of my app while data is being received from the volley. There may be an easier way to do this but this is what i've tried so far only I have a few errors. The first error being newsListView getting the error 'varied is accessed from within inner class, needs to be declared final'. and the string values cannot be resolved. Here is the class I made within the oncreate method:

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

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

        }
    };

}

and the progress bar appears in the activity_main.xml like so:

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

Upvotes: 3

Views: 4536

Answers (3)

BNK
BNK

Reputation: 24114

Here is the way I often do in my projects, IMO you can take a look and apply to your project, hope it helps!

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...
            mRequestQueue = Volley.newRequestQueue(this);
            mProgressBar = (ProgressBar) findViewById(R.id.progressBar);      
            mProgressBar.setVisibility(View.VISIBLE);     
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                    // do something...
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                    // do something...
                }
            });           
            mRequestQueue.add(jsonArrayRequest);
            ...
        }

Upvotes: 4

Hiren Patel
Hiren Patel

Reputation: 52800

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

    newsListView.setOnItemClickListener(itemClicked);

    EDANewsApp app = EDANewsApp.getInstance();

    nextStart = 0;
    updateListData(nextStart, 20);


}

private class Task extends AsyncTask<String, Integer, Boolean> {

    private ProgressDialog dialog;

            @Override
            protected void onPreExecute() {
                dialog.setMessage("Doing something, please wait.");
                dialog.show();
                layout.setVisibility(View.VISIBLE);
                newsListView.setVisibility(View.GONE);
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Boolean result) {
                dialog.dismiss();
                layout.setVisibility(View.GONE);
                newsListView.setVisibility(View.VISIBLE);
                adapter.notifyDataSetChanged();
                super.onPostExecute(result);
            }

            @Override
            protected Boolean doInBackground(String... params) {
                stringValues.add("String 1");
                stringValues.add("String 2");
                stringValues.add("String 3");
                stringValues.add("String 4");
                stringValues.add("String 5");

                try {
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }

Hope this will help you.

Upvotes: 0

Fakher
Fakher

Reputation: 2128

you declare your progressbar

    private ProgressDialog pDialog;
pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

you call you Volley request than when you get the response (either success or error event) you call the hidePDialog method

hidePDialog();


//method to hide progressbar
    private void hidePDialog() {
            if (pDialog != null) {
                pDialog.dismiss();
                pDialog = null;
            }
        }

don't forget to call the method in onDestroy() also

Upvotes: 2

Related Questions