如何在单击recyclerview项目时获取sqlite的id?

时间:2016-02-11 05:51:11

标签: android sqlite android-recyclerview

这是我的疑问,当我点击recyclerview项目需要获取我保存在sqlite中的任务ID我怎么能这样做,例如当我点击回收站视图需要将该值传递到下一页并需要更新该值我怎么能到目前为止,我尝试过这样做:

public class Task extends Fragment  {
    private static final String MY_PREFERENCE_KEY = "yogan";
    private List<Model_Task_List> model_task_lists;

    private RecyclerView recyclerView;
    Task_List_Adapter taskadapter;
    private RecyclerView.LayoutManager layoutManager;
    SharedPreferences sharedPreferences;
    private RecyclerView.Adapter adapter;
    RequestQueue yog;
    String user_id;
    AppController app;
    RequestQueue queue;
    String Url;
    Task_DB task_db = null;
    Database_SF_APP database_sf_app;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(layoutManager);
        if (model_task_lists == null) {
            model_task_lists = new ArrayList<Model_Task_List>();
        }
        Calendar c = Calendar.getInstance();
        System.out.println("Current time => " + c.getTime());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = df.format(c.getTime());
        int hour=c.get(Calendar.HOUR_OF_DAY);
        String hours=Integer.toString(hour);
        database_sf_app = new Database_SF_APP(getActivity().getBaseContext());
        int count=database_sf_app.getTaskCount();
        sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
        user_id = sharedPreferences.getString("user_id", null);
        model_task_lists=database_sf_app.getTaskListById(user_id);
        taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
        recyclerView.setAdapter(taskadapter);
        if(taskadapter!=null){
            taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
                @Override
                public void yog(View v, int position) {


                }
            });
        }
        queue = Volley.newRequestQueue(getContext());
        Url = "http://xxx.xx.x.xx/xxx/GetActivitiesByUserID.svc/getlist/Task/" + user_id +"/" +null+"/"+hours;
        ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
        if (nf != null && nf.isConnected()) {
            Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
            JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.POST, Url, new JSONObject(),
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            String server_response = response.toString();
                            try {
                                JSONObject json_object = new JSONObject(server_response);
                                JSONArray json_array = new JSONArray(json_object.getString("TaskResult"));
                                for (int i = 0; i < json_array.length(); i++) {
                                    Model_Task_List modelobj = new Model_Task_List();
                                    JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
                                    modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
                                    modelobj.setTaskID(json_arrayJSONObject.getInt("TaskID"));
                                    modelobj.setUserName(json_arrayJSONObject.getString("DueDate"));
                                    modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
                                    modelobj.setUserid(json_arrayJSONObject.getString("Owner"));
                                    database_sf_app.insertorUpdate(modelobj);


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

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();

                        }
                    });

            //Creating request queue

            queue.add(jsonObjRequest);

        }

        //sync operation
        //a union b
        //a server
        //b local storage

        //a only - insert local
        //b only - send to server
        //a = b do nothing

        //result
        //bind


        return view;
    }


    @Override
    public void onResume()
    {
            super.onResume();
    }


    @Override
    public void onStop() {

        super.onStop();
    }

}

这是我的TaskAdapter:

import android.content.Context;
        import android.support.v7.widget.RecyclerView;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageView;
        import android.widget.TextView;

        import java.util.List;

public class Task_List_Adapter extends RecyclerView.Adapter<Task_List_Adapter.MyViewHolder>  {
    private List<Model_Task_List> dataSet;
    private    Context context;

    private static data yog;

    Model_Task_List modelTaskList=new Model_Task_List();

    public void remove(int position)
    {
        dataSet.remove(position);
        notifyItemRemoved(position);
    }
    public void edit(int position){
        dataSet.set(position, modelTaskList);
        notifyItemChanged(position);
    }

    public void setOnItemClickListener(data listener) {
        this.yog = listener;
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder  {
        // Model_Task_List Model_Task_List=new Model_Task_List();
        TextView textname;
        TextView textaddress;
        TextView textphnum;
        TextView textdegree;
        TextView textemail;
        ImageView call;
        data datas;

        public MyViewHolder(final View itemView) {
            super(itemView);
            this.textname = (TextView) itemView.findViewById(R.id.subject);
            this.textaddress = (TextView) itemView.findViewById(R.id.username);
            this.textphnum = (TextView) itemView.findViewById(R.id.status);


            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(yog!=null){
                        yog.yog(itemView,getLayoutPosition());
                    }
                }
            });

            // this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);

        }



    }
    public interface data
    {
        void yog(View v,int position);
    }
    public Task_List_Adapter(List<Model_Task_List> data,Context context) {

        this.dataSet = data;
        this.context=context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.task_list_view, parent, false);

        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        TextView textViewName = holder.textname;
        TextView textViewaddress = holder.textaddress;
        TextView textViewphnum = holder.textphnum;
        TextView textdegree = holder.textdegree;
        TextView textemail=holder.textemail;

        textViewName.setText("Subject:"+dataSet.get(position).getSubject());
        textViewaddress.setText("DueDate"+dataSet.get(position).getUserName());
        textViewphnum.setText("Status:"+dataSet.get(position).getTaskStatus());


    }




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

获取身份证是正确的方式:

    taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
                @Override
                public void yog(View v, int position) {

Model_Task_List model_task_list=(Model_Task_List)model_task_lists.get(position);


                    String yog=model_task_list.getSubject().toString();
                   int yogeshs=model_task_list.getTaskID();
                    String yogan=Integer.toString(yogeshs);
                    Toast.makeText(getContext(),yogan,Toast.LENGTH_SHORT).show();
                }
            });
        }
Where i make recyclerview clickable how to get id of sqlite when i click and need to pass the value to next page 

3 个答案:

答案 0 :(得分:2)

您在recyclerview中显示的对象

在您的情况下,代码必须在TaskAdapter中,

将id放在该对象中,因此当您单击它时,您将获得该对象,以便从该对象中检索ID

clickedObjecj.getId();

答案 1 :(得分:0)

在onBindViewHolder中定义onClick不是一个好习惯

正确的方法是在适配器类中声明一个接口,并在Activity上实现它,使用接口我们可以传递值

步骤1:  用于OnItemClickListener接口的Decalre监听器

private OnItemClickListener mListener;

第2步:声明一个接口,该接口会将我们的点击和数据从适配器转发到我们的活动

public interface OnItemClickListener {
        void onItemClick(int elementId);
    }
    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

第3步:定义ViewHolder的点击并传递ID

 //Assigning on click listener on the item and passing the ID value of the item
            itemView.setOnClickListener(new View.OnClickListener() { // we can handle the click as like we do in normal
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        int elementId = dataSet.get(getAdapterPosition()).getTaskID(); // Get the id of the item on that position
                        mListener.onItemClick(elementId); // we catch the id on the item view then pass it over the interface and then to our activity
                        }
                    }
            });

第4步:在活动中实施TaskAdapter.OnItemClickListener

步骤6:onItemClick方法,您将获取值

 @Override
    public void onItemClick(int itemId) {
        Log.d(TAG, "onItemClick: "+String.valueOf(itemId));
    }

答案 2 :(得分:0)

首先,您必须将“光标位置”设置为被点击的位置

Ex: Cursor products <- storing a set of data

将光标设置为单击的位置,例如RecyclerView单击事件中的位置值

products.moveToPosition(position);

然后照常使用getString

String name = products.getString(products.getColumnIndex("NAME"));

希望它会有所帮助