繁体   English   中英

在从截击加载数据的同时向应用程序添加进度对话框

[英]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.

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