简体   繁体   English

从Android中的自定义列表适配器调用活动方法?

[英]Calling a activity method from a custom list adapter in android?

On button click I am trying to send some data to my php script using the google's volley library. 在按钮上单击,我正在尝试使用Google的凌空库将一些数据发送到我的PHP脚本。 The method for sending the data is inside an Activity and I have written an interface to call the method from the custom list adapter. 发送数据的方法在Activity中,我编写了一个接口,以从自定义列表适配器调用该方法。

The following is my adapter code: 以下是我的适配器代码:

public class RoleList extends ArrayAdapter<String> {

    public static final String DELETEUSERINFO = VirtualMachineIp.VMIP_ADDRESS.trim() + "goldmine/getuserinfo.php";
    public static final String KEY_NAME = "name";
    public static final String KEY_ROLE = "role";
    private ArrayList<String> name;
    private ArrayList<String> username;
    private ArrayList<String> password;
    private ArrayList<String> role;
    private Activity context;

    public int getPos() {
        return pos;
    }

    public void setPos(int pos) {
        this.pos = pos;
    }

    int pos;

    public boolean isDelPressed() {
        return delPressed;
    }

    public void setDelPressed(boolean delPressed) {
        this.delPressed = delPressed;
    }

    boolean delPressed;

    private onDelCallback listener;

    public RoleList(Activity context, ArrayList<String> name, ArrayList<String> username, ArrayList<String> password, ArrayList<String> role, onDelCallback listener) {
        super(context, R.layout.role_list, name);
        this.context = context;
        this.name = name;
        this.username = username;
        this.password = password;
        this.role = role;
        this.listener = listener;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        final View listViewItem = inflater.inflate(R.layout.role_list, null, true);
        final TextView textViewName = (TextView) listViewItem.findViewById(R.id.tv_empname);
        final TextView textViewusername = (TextView) listViewItem.findViewById(R.id.tv_empusername);
        final TextView textViewPass = (TextView) listViewItem.findViewById(R.id.tv_emppassword);
        final TextView textViewRole = (TextView) listViewItem.findViewById(R.id.tv_emprole);
        Button edit = (Button) listViewItem.findViewById(R.id.btn_editRole);
        Button delete = (Button) listViewItem.findViewById(R.id.btn_delRole);


        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                setDelPressed(true);
                name.remove(position);
                username.remove(position);
                password.remove(position);
                role.remove(position);
                listener.deleteuser(position);
                notifyDataSetChanged();
                setPos(position);

            }
        });
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Emp Info", name.get(position) + " " + username.get(position) + " " + password.get(position) + " " + role.get(position));

                final Dialog dialog = new Dialog(getContext());
                dialog.setContentView(R.layout.userreg);
                dialog.setTitle("Edit Employee " + name.get(position) + " details");
                final String[] arraySpinner = new String[]{"Manager", "Stockist", "Cashier", "Accountant"};
                dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                final EditText emp_name = (EditText) dialog.findViewById(R.id.editTextName);
                final EditText emp_uname = (EditText) dialog.findViewById(R.id.editTextUserName);
                final EditText emp_pw = (EditText) dialog.findViewById(R.id.editTextPassword);
                final Spinner emp_role = (Spinner) dialog.findViewById(R.id.spinner_role);
                final TextView textRole = (TextView) dialog.findViewById(R.id.tv_selected_role);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, arraySpinner);
                emp_role.setAdapter(adapter);
                emp_role.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Toast.makeText(getContext(), "Role Selected is " + arraySpinner[position], Toast.LENGTH_SHORT).show();

                        String employee_role = arraySpinner[position];
                        textRole.setText(employee_role);

                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });


                emp_name.setText(name.get(position));
                emp_uname.setText(username.get(position));
                emp_pw.setText(password.get(position));
                emp_role.setSelection(position);

                Button buttoncancel = (Button) dialog.findViewById(R.id.buttonCancel);
                buttoncancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                Button buttonChange = (Button) dialog.findViewById(R.id.buttonRegister);
                buttonChange.setText("Change");
                buttonChange.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        textViewName.setText(emp_name.getText().toString());
                        textViewusername.setText(emp_uname.getText().toString());
                        textViewPass.setText(emp_pw.getText().toString());
                        textViewRole.setText(textRole.getText());
                        dialog.dismiss();

                    }
                });


                dialog.show();
            }
        });


        textViewName.setText(name.get(position));
        textViewusername.setText(username.get(position));
        textViewPass.setText(password.get(position));
        textViewRole.setText(role.get(position));

        return listViewItem;
    }

    public interface onDelCallback {
        void deleteuser(int pos);
    }



}

The following code should ideally get called when the button inside the list is pressed: 理想情况下,按下列表内的按钮时,应调用以下代码:

@Override
    public void deleteuser(final int pos)
    {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, DELETEUSERINFO, new Response.Listener<String>() {
            @Override
            public void onResponse(String response)
            {
                String resp = response.toString().trim();
                if (resp.equals("UNABLE TO DELETE USER"))
                {
                    Log.d("UNABLE TO DEL",resp);
                }else if (resp.equals("USER DELETED SUCCESSFULLY"))
                {
                    Toast.makeText(UserRegistration.this, "USER DELETED SUCCESSFULLY", Toast.LENGTH_SHORT).show();
                }

            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Toast.makeText(UserRegistration.this, "Please check your internet connection", Toast.LENGTH_LONG).show();
                    }
                }){

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put(KEY_NAME, employee_name.get(pos));
                params.put(KEY_ROLE,employee_role.get(pos));
                return params;
            }
        };
        RequestQueue rq = Volley.newRequestQueue(this);
        rq.add(stringRequest);
    }

I set the adapter inside parseUserinfo() which runs on response of getUserinfo() which I call inside onCreate().getUserinfo() is used to request data from the remote server. 我设置内部parseUserinfo(),它运行在的响应适配器getUserinfo()其余内调用onCreate().getUserinfo()是用来从所述远程服务器请求数据。

This is how I set the adapter: 这是我设置适配器的方式:

 RoleList roleList = new RoleList(UserRegistration.this, employee_name, emp_username, emp_password, employee_role,UserRegistration.this);
 userList.setAdapter(roleList);

I want to know if I am calling the adapter in the right place. 我想知道我是否在正确的地方调用适配器。 Do I need to call it again? 我需要再打一次吗?

Any help or suggestion is appreciated. 任何帮助或建议,表示赞赏。 Thank you. 谢谢。

There are certain ways through which u can call your activity method from adapter: 您可以通过某些方式从适配器调用您的活动方法:

  1. when u create an constructor of adapter at that time you can pass your activity object in its parameters and then use that object in your adapter. 当您当时创建适配器的构造函数时,可以在其活动对象中传递其活动对象,然后在适配器中使用该对象。

  2. If u create a interface in adapter you must implement that interface in your respective activity and then you can pass your activity object through adapter constructor and can use your required method. 如果在适配器中创建接口,则必须在各自的活动中实现该接口,然后可以通过适配器构造函数传递活动对象,并可以使用所需的方法。

public RoleList(Activity context, ArrayList name, ArrayList username, ArrayList password, ArrayList role, onDelCallback listener) { } In the above constructor u must pass the Respective Activity object for example MyActvity mActivity rather then passing the generic Activity object. 公共RoleList(活动上下文,ArrayList名称,ArrayList用户名,ArrayList密码,ArrayList角色,onDelCallback侦听器){}在上面的构造函数中,您必须传递各自的Activity对象,例如MyActvity mActivity,而不是传递通用的Activity对象。 As i hope your method is available in MyActvity class and also considering you had implement the interface on MyActvity class. 我希望您的方法在MyActvity类中可用,并希望您已经在MyActvity类上实现了接口。

You can perform your delete task of your activity in adapter like this 您可以像这样在适配器中执行活动的删除任务

delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                UserRegistration act = (UserRegistration) context;
                act.deleteuser(position);
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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