在排球数据加载时向应用添加进度微调器

时间:2015-12-17 13:42:48

标签: java android xml android-volley

我尝试在应用程序顶部添加进度微调器,同时从排球中接收数据。可能有一种更简单的方法可以做到这一点,但这是我迄今为止尝试的只有一些错误。第一个错误是newsListView得到的错误变化是从内部类中访问的,需要被声明为final'。并且无法解析字符串值。这是我在oncreate方法中创建的类:

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

        }
    };

}

,进度条出现在activity_main.xml中,如下所示:

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

3 个答案:

答案 0 :(得分:3)

以下是我经常在项目中使用的方式,IMO你可以看看并申请你的项目,希望它有所帮助!

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

答案 1 :(得分:1)

您声明了进度条

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

你称之为Volley请求,而不是当你得到响应(成功或错误事件)时,你调用hidePDialog方法

hidePDialog();


//method to hide progressbar
    private void hidePDialog() {
            if (pDialog != null) {
                pDialog.dismiss();
                pDialog = null;
            }
        }
不要忘记在onDestroy()中调用该方法

答案 2 :(得分:0)

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

希望这会对你有所帮助。