当前位置: 首页 > 知识库问答 >
问题:

如何在recyclerview中显示更多数据,并在recyclerview下方显示进度条

隆向晨
2023-03-14

我想要一个recyclerview,当第一个应用程序打开时,然后在创建时从服务器获取一些数据,当向上滚动时,会显示recyclerview下方的进度条,当向上滚动到服务器时再次点击URL,并在先前获取的数据下方获取更多数据。但我知道当我第二次点击URL时,它会刷新页面,并在第二次点击时只显示从服务器获取的数据,但我想要第一次和第二次点击的响应。

对不起,我说英语

以下是我的主要活动代码:

public class MainActivity extends AppCompatActivity {

public static String m_DealListingURL = "http://192.163.0.110:8080/ireward/rest/json/metallica/getDealListInJSON";
public static String s_szresult = " ";
public CJsonsResponse m_oJsonsResponse;
public int[] m_n_FormImage;
public String sz_RecordCount, sz_LastCount;
public int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
public int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
boolean isFirstTime;
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private List<User> mUsers = new ArrayList<>();
private UserAdapter mUserAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    mToolbar.setTitle("LoadMoreRecycleView");

    isFirstTime = true;
    //..............sending first hit ..................................
    new CDealDataSent().execute(m_DealListingURL);
    mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
    sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
    sz_LastCount = String.valueOf(m_n_DeafalutLastCount);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mUserAdapter = new UserAdapter();
    mRecyclerView.setAdapter(mUserAdapter);
    // Getting the string array from strings.xml
    m_n_FormImage = new int[]{
            R.drawable.amazon,
            R.drawable.whatsapp,
            R.drawable.zorpia,
            R.drawable.path,
            R.drawable.app_me,
            R.drawable.evernote,
            R.drawable.app_me};
    mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            Log.e("haint", "Load More");
            mUsers.add(null);
            mUserAdapter.notifyItemInserted(mUsers.size() - 1);

           //Load more data for reyclerview
            new Handler().postDelayed(new Runnable() {
                //                    @Override
                public void run() {
                    Log.e("haint", "Load More 2");

                    mUsers.remove(mUsers.size() - 1);
                    mUserAdapter.notifyItemRemoved(mUsers.size());

                    m_n_DefaultRecordCount = m_n_DefaultRecordCount + 5;
                    m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;

                    sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);
                    sz_LastCount = String.valueOf(m_n_DeafalutLastCount);

                    //...........sending second hit ./.................
                    new DealNext().execute(m_DealListingURL);

                    mUserAdapter.setLoaded();
                }
            }, 5000);
        }
    });
}
public String DealListing(String url, CRegistrationDataStorage login) {
    //sending deal data to retreive response from server

    InputStream inputStream = null;
    m_oJsonsResponse = new CJsonsResponse();
    try {
        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);
        String json = "";
        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("agentCode", "9555517456");
        jsonObject.put("pin", "05E0901648FD6439207FA74FC3E07734");
        jsonObject.put("recordcount", sz_RecordCount);
        jsonObject.put("lastcountvalue", sz_LastCount);
        //jsonObject.put("emailId", "nirajk1190@gmail.com");
        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();
        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);
        // 6. set httpPost Entity
        httpPost.setEntity(se);
        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Content-type", "application/json");
        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();
        // 9. receive response as inputStream
        inputStream = entity.getContent();
        System.out.println("InputStream....:" + inputStream.toString());
        System.out.println("Response....:" + httpResponse.toString());

        StatusLine statusLine = httpResponse.getStatusLine();
        System.out.println("statusLine......:" + statusLine.toString());
        ////Log.d("resp_body", resp_body.toString());
        int statusCode = statusLine.getStatusCode();
        // 10. convert inputstream to string
        if (statusCode == 200) {
            // 10. convert inputstream to string
            if (inputStream != null)
                s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
            //String resp_body =
            EntityUtils.toString(httpResponse.getEntity());
        } else
            s_szresult = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    System.out.println("resul.....:" + s_szresult);
    // 11. return s_szResult
    return s_szresult;
}
static class UserViewHolder extends RecyclerView.ViewHolder {
    public TextView tvName;
    public TextView tvEmailId;
    public ImageView appImage;

    public UserViewHolder(View itemView) {
        super(itemView);
        tvName = (TextView) itemView.findViewById(R.id.tvName);
        appImage = (ImageView) itemView.findViewById(R.id.appImage);
        tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
    }
}
static class LoadingViewHolder extends RecyclerView.ViewHolder {
    public ProgressBar progressBar;

    public LoadingViewHolder(View itemView) {
        super(itemView);
        progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
    }
}

class CDealDataSent extends AsyncTask<String, Void, String> {
    //  sending first hit to server ........................................
    public JSONObject m_oResponseobject;
    public ProgressDialog m_PDialog;
    public CRegistrationDataStorage oRegisterStorage;
    public User item;

    //      @Override
    protected void onPreExecute() {
        super.onPreExecute();
        m_PDialog = new ProgressDialog(MainActivity.this);
        m_PDialog.setMessage("Please wait while Loading Deals...");
        m_PDialog.setCancelable(false);
        m_PDialog.show();
    }

    @Override
    protected String doInBackground(String... urls) {
        return DealListing(urls[0], oRegisterStorage);// sending data to server...

    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        m_PDialog.dismiss();
        try {
            m_oResponseobject = new JSONObject(result);// getting response from server
            final JSONArray posts = m_oResponseobject.optJSONArray("dealList");

            mUsers = new ArrayList<User>();
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.getJSONObject(i);
                item = new User();
                item.setName(post.getString("dealname"));
                item.setEmail(post.getString("dealcode"));
                item.setImage(m_n_FormImage[i]);
                mUsers.add(item);

            }
            getResponse();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getResponse() throws JSONException {
        if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {

            mUserAdapter = new UserAdapter();//creating object of adapter and addd setting odata to adapter for use.
            mRecyclerView.setAdapter(mUserAdapter);//adding adapter to recyclerview
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
            Toast.makeText(MainActivity.this, "Connection not avaliable", Toast.LENGTH_SHORT).show();
        }

    }

}

//  sending second time hit  to server..................................
//  ...................................................................................
private class DealNext extends AsyncTask<String, Void, String> {
    public JSONObject m_oResponseobject;
    public CRegistrationDataStorage oRegisterStorage;
    public User item;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... urls) {
        //My Background tasks are written here

        synchronized (this) {

            return DealListing(urls[0], oRegisterStorage);
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            m_oResponseobject = new JSONObject(result);// getting response from server
            if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found"))
                return;
            final JSONArray posts = m_oResponseobject.optJSONArray("dealList");
            if (isFirstTime) {
                mUsers = new ArrayList<User>();
                isFirstTime = false;
            } else {
                mUsers.remove(mUsers.size() - 1);
                mUserAdapter.notifyItemRemoved(mUsers.size());
            }
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.getJSONObject(i);
                item = new User();
                item.setName(post.getString("dealname"));
                item.setEmail(post.getString("dealcode"));
                item.setImage(m_n_FormImage[i]);
                mUsers.add(item);
            //                  m_oAdapter.notifyDataSetChanged();
                mUserAdapter.notifyItemInserted(mUsers.size());
                mUserAdapter.setLoaded();

            }
            if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {

                mUserAdapter = new UserAdapter();//creating object of adapter and addd setting odata to adapter for use.
                mRecyclerView.setAdapter(mUserAdapter);//adding adapter to recyclerview
            } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
                Toast.makeText(MainActivity.this, "Connection not avaliable", Toast.LENGTH_SHORT).show();
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;

    private OnLoadMoreListener mOnLoadMoreListener;

    private boolean isLoading;
    private int visibleThreshold = 5;
    private int lastVisibleItem, totalItemCount;

    public UserAdapter() {
        final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                totalItemCount = linearLayoutManager.getItemCount();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();

                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                    if (mOnLoadMoreListener != null) {
                        mOnLoadMoreListener.onLoadMore();

                    }
                    isLoading = true;


                }
            }
        });
    }

    public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
        this.mOnLoadMoreListener = mOnLoadMoreListener;
    }

    @Override
    public int getItemViewType(int position) {
        return mUsers.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_ITEM) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_user_item, parent, false);
            return new UserViewHolder(view);
        } else if (viewType == VIEW_TYPE_LOADING) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_loading_item, parent, false);
            return new LoadingViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof UserViewHolder) {
            User user = mUsers.get(position);
            UserViewHolder userViewHolder = (UserViewHolder) holder;
            userViewHolder.tvName.setText(user.getName());
            userViewHolder.tvEmailId.setText(user.getEmail());
            userViewHolder.appImage.setImageResource(user.getImage());
        } else if (holder instanceof LoadingViewHolder) {
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
            loadingViewHolder.progressBar.setIndeterminate(true);
        }
    }

    @Override
    public int getItemCount() {
        return mUsers == null ? 0 : mUsers.size();
    }

    public void setLoaded() {
        isLoading = false;
    }
}

}

暂时还没有答案

 类似资料:
  • 问题内容: 我需要添加一个可以列出an元素的位置,并且我发现有一种更新更好的显示列表的方法- 。 我的问题是如何在我的应用程序中实现这一点。我发现我需要使用,但是我不太了解如何正确实现整个过程。 如果你想知道,我指的是这个的文档的例子,这是我一直在读。 编辑: 更新我的代码后,它说它无法解析该符号: 所以我以为我把它放错了地方(很可能),实际上我把它放到Adapter类的末尾,就在Method之后

  • 我在StackOverflow上看到了一些类似的事件。然而,这些似乎都不适用于我的情况。我遇到的问题是,我的RecyclerView正在工作,但没有显示任何内容。我已经运行了多个测试,试图找出它不工作的原因,但所有测试都支持它正常工作的事实。 getItemCount中的日志返回3,这是正确的数字。我只是不明白为什么它没有显示。我回头看了我在以前的活动中做的回收器视图,它们都在一定程度上匹配(其他

  • 问题内容: 使用 在现有数据库中显示数据的最佳方法是什么? 答案中没有包含全部解释,因此,我添加了此问与答样式,以便可以将其链接到注释中。 问题答案: 假设你具有一个如下所示的Firestore数据库结构: 看起来也像这样的模型类: 包含的文件也如下所示: 要显示所有产品名称,请按照以下步骤操作。 首先,你需要RecyclerView在你的活动中找到并进行如下设置LinearLayoutManag

  • 我使用的是一个模板,我用一个改装2请求替换了占位符数据,该请求从URL解析数据的JSON文件,并将其放入对象列表中。我遇到了一个问题,首先执行改装调用并返回items=0,然后使用值items=0进一步执行代码,在调试器中执行了许多步骤后,它返回调用并显示正确的响应(items=12),但适配器/RecycleView操作似乎已经执行,并且它们不使用延迟到达的解析数据。 主要活动。Java语言 改

  • 使用Android在中显示现有Firestore数据库中的数据的最佳方法是什么?

  • 这是我现在面临的一个奇怪的问题。从我的应用程序中,我从JSON文件中从链接中获取数据,然后用Volley解析它。现在我想在一个看起来不起作用的RecyclerView上显示数据,我很高兴我的代码很好,但是有些东西似乎不起作用,我找不到它。 这是活动代码 HomeActivity.java: 这是我从适配器中扩展的布局,并从JSON文件中设置数据 和适配器类相关的代码,我猜: @Override p