如何使用 API 增加 android 应用中的访问者数量

How to increment the visitors count in an android app by using an API

我正在制作一个关于故事的应用程序,它将在 API (getstories.php) 的帮助下在列表视图中显示故事列表。我正在使用 volley 库和回收器视图。我还想实现访问者或视图计数,这意味着只要用户单击特定列表项,它就会将视图增加一个。对于该访问者增量计数,我有一个额外的 API,即 (incrementviews.php)。 我已经在代码中实现了它,如果我向下滚动,它会更新整个列表项视图计数。但我希望每当用户单击特定列表项时,该特定列表项应该将视图增加一个而不是整个列表项。谁能帮我修改一下?

代码在JAVA

这是我的代码:- Adapter.class

public class StoriesAdapter extends RecyclerView.Adapter<StoriesAdapter.ViewHolder> {

    private static final String HP = "http://......./incrementviews.php?story_id=";
    private List<StoriesModel> storiesModels;
    private Context context;

    public StoriesAdapter(List<StoriesModel> storiesModels, Context context) {
        this.storiesModels = storiesModels;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.row, parent, false); 
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        StoriesModel storiesModel = storiesModels.get(position);

        holder.header.setText(storiesModel.getTitle());
       
        holder.views.setText(storiesModel.getViews());
        holder.story.setText(storiesModel.getStory());


        //getViewCount method initialization
        final String story_id = storiesModel.getStoryId();
        getViewCountData(story_id, holder);

        

        holder.relativeLayout.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DetailActivity.class);
                intent.putExtra("header",storiesModel.getTitle());
              
                intent.putExtra("views",storiesModel.getViews());

              intent.putExtra("story",storiesModel.getStory());

                context.startActivity(intent);
            }
        });


    }

    //Get view count Method
    private void getViewCountData(final String story_id , ViewHolder holder){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, HP + story_id, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject o = array.getJSONObject(i);
                        String textCount = o.getString("views");
                        holder.views.setText(textCount);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams(){

                Map<String, String>parms = new HashMap<String, String>();
                parms.put("story_id",story_id);
                return parms;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
    }



    @Override
    public int getItemCount() {
        return storiesModels.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        public TextView header;
      
        public TextView views;

       public TextView story;

       //public LinearLayout linearLayout; //old of rowitem.xml

        public RelativeLayout relativeLayout;


        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            header = (TextView) itemView.findViewById(R.id.header);
          
           views = (TextView) itemView.findViewById(R.id.views);

            story = (TextView) itemView.findViewById(R.id.story);

            //linearLayout = (LinearLayout) itemView.findViewById(R.id.linear_layout);//old of rowitem.xml

            relativeLayout = (RelativeLayout) itemView.findViewById(R.id.Newlinear_layout);

        }
    }
}


这是MainActivity.class:-

public class StoriesFragment extends Fragment {

    private static final String URL_DATA = "https://......./getstories.php";
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    List<StoriesModel> storiesModels;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_stories, container, false);

        recyclerView = view.findViewById(R.id.recycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        storiesModels = new ArrayList<>();

        loadRecyclerViewData();


        return view;
    }

    private void loadRecyclerViewData(){
        ProgressDialog progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Please wait...");
        progressDialog.show();

        //fetch the data from the server

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                URL_DATA,

                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("data");

                            for(int i =0; i<array.length(); i++){
                                JSONObject o = array.getJSONObject(i);
                                StoriesModel item = new StoriesModel    (
                                        o.getString("story_id"),
                                        o.getString("title"),
                                        o.getString("views"),
                                        
                                        o.getString("story")
                                       


                                );
                                storiesModels.add(item);
                            }

                            adapter = new StoriesAdapter(storiesModels, getContext());
                            recyclerView.setAdapter(adapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
//                        Toast.makeText(getContext(), VolleyError.getMessage())
                        Toast.makeText(getContext(), (CharSequence) new VolleyError(), Toast.LENGTH_LONG).show();

                    }
    });
        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

    }
}


如果您在 DetailActivity 中展示故事,那么您可以简单地在 DetailActivity Activity 中实现增加观众计数 api。一旦用户达到这个 activity 并且他在屏幕上停留了几秒钟,您可以简单地调用增量视图计数 api.

所以你要做的是在 DetailActivity 的 onCreate 中创建并发送你的截击请求。

我找到了您会满意的解决方案,并且从我这边来看它运行良好。所以这是代码:- 仅在适配器 class 中更改:-

public class StoriesAdapter extends RecyclerView.Adapter<StoriesAdapter.ViewHolder> {

private static final String HP = "http://......./incrementviews.php?story_id=";
private List<StoriesModel> storiesModels;
private Context context;

public StoriesAdapter(List<StoriesModel> storiesModels, Context context) {
    this.storiesModels = storiesModels;
    this.context = context;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row, parent, false); 
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    StoriesModel storiesModel = storiesModels.get(position);

    holder.header.setText(storiesModel.getTitle());
   
    holder.views.setText(storiesModel.getViews());
    holder.story.setText(storiesModel.getStory());


    //getViewCount method initialization
    final String story_id = storiesModel.getStoryId();
    

    

    holder.relativeLayout.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("header",storiesModel.getTitle());
          
            intent.putExtra("views",storiesModel.getViews());

          intent.putExtra("story",storiesModel.getStory());

            context.startActivity(intent);
            getViewCountData(story_id, holder);

        }
    });


}

//Get view count Method
private void getViewCountData(final String story_id , ViewHolder holder){
    StringRequest stringRequest = new StringRequest(Request.Method.POST, HP, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String, String> getParams(){

            Map<String, String>parms = new HashMap<String, String>();
            parms.put("story_id",story_id);
            return parms;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}



@Override
public int getItemCount() {
    return storiesModels.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

    public TextView header;
  
    public TextView views;

   public TextView story;

   //public LinearLayout linearLayout; //old of rowitem.xml

    public RelativeLayout relativeLayout;


    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        header = (TextView) itemView.findViewById(R.id.header);
      
       views = (TextView) itemView.findViewById(R.id.views);

        story = (TextView) itemView.findViewById(R.id.story);

        //linearLayout = (LinearLayout) itemView.findViewById(R.id.linear_layout);//old of rowitem.xml

        relativeLayout = (RelativeLayout) itemView.findViewById(R.id.Newlinear_layout);

    }
}

}