java - 我想从 ListView 中选择用户名文本字段并使用该用户名删除 mysql 数据库中存在的数据

标签 java php android mysql listview

我想在 ListView 中显示 MySQL 表数据,还必须将删除按钮放在屏幕底部。用户必须选择列表项,然后单击删除按钮,应从 mysql 表和 ListView 中删除特定数据。我可以正确显示记录,但无法从列表项中选择用户名字段。

查看用户 Activity

public class ViewUser extends AppCompatActivity implements View.OnClickListener {

    private static final String VIEW_URL= "http://ajaygohel012.000webhostapp.com/ViewUser.php";

    ListView listUser;
    List<User> userlist;
    private Button btnDelete;

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

        listUser= findViewById(R.id.listUser);
        userlist= new ArrayList<>();
        btnDelete= (Button) findViewById(R.id.btnDelete);

        final TextView viewUserName = (TextView) findViewById(R.id.viewUserName);

        loadUserList();

        listUser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                listUser.setOnItemSelectedListener(this);
            }

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

            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String username = viewUserName.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                            try {
                                JSONObject js = new JSONObject(response);
                                boolean success = js.getBoolean("success");
                                if (success){
                                    finish();
                                    startActivity(getIntent());
                                }
                            }catch(JSONException e){
                                e.printStackTrace();
                            }
                    }
                };

                DeleteRequest deleteRequest= new DeleteRequest(username, responseListener);
                RequestQueue queue= Volley.newRequestQueue(ViewUser.this);
                queue.add(deleteRequest);
            }
        });
    }
    private void loadUserList(){
        final ProgressBar progressBar= (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);

        StringRequest stringRequest= new StringRequest(Request.Method.GET, VIEW_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressBar.setVisibility(View.INVISIBLE);

                try {
                    JSONObject jsonObject= new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");

                    for (int i=0;jsonArray.length()>i;i++){
                        final JSONObject j= jsonArray.getJSONObject(i);
                        User user=new User();

                        String name = j.getString("name");
                        String empcode = j.getString("empcode");
                        String location = j.getString("location");
                        String department = j.getString("department");
                        String username = j.getString("username");

                        user.setName(name);
                        user.setEmpcode(empcode);
                        user.setLocation(location);
                        user.setDepartment(department);
                        user.setUsername(username);
                        userlist.add(user);
                    }
                    ListViewAdapter adapter = new ListViewAdapter(userlist, ViewUser.this);
                    listUser.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ViewUser.this, error.getMessage(), Toast.LENGTH_SHORT);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    @Override
    public void onClick(View view) {
        if (view==btnDelete){
            finish();
            startActivity(new Intent(this, ViewUser.class));
        }
    }
}

删除请求

class DeleteRequest extends StringRequest{
    private static final String LOGIN_REQUEST_URL= "http://ajaygohel012.000webhostapp.com/DeleteUser.php";
    private Map<String, String> params;

    public DeleteRequest(String username, Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("username", username);
    }
    public Map<String, String> getParams(){
        return params;
    }

}

用户类

public class User {
    String name, empcode, location, department, username;

    public User(){
        this.name=name;
        this.empcode=empcode;
        this.location=location;
        this.department=department;
        this.username=username;
    }


    public String getName() {
        return name;
    }

    public String getEmpcode() {
        return empcode;
    }

    public String getLocation() {
        return location;
    }

    public String getDepartment() {
        return department;
    }

    public String getUsername() {
        return username;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmpcode(String empcode) {
        this.empcode = empcode;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

ListView 适配器

public class ListViewAdapter extends ArrayAdapter<User> {
    private List<User> userlist;
    private Context cntx;

    public ListViewAdapter(List<User> userlist, Context cntx){
        super(cntx, R.layout.list_item, userlist);
        this.userlist=userlist;
        this.cntx=cntx;
    }
    public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater inflater= LayoutInflater.from(cntx);
        View listViewitem= inflater.inflate(R.layout.list_item,null, true);

        TextView viewName= listViewitem.findViewById(R.id.viewName);
        TextView viewEmployeeCode= listViewitem.findViewById(R.id.viewEmployeeCode);
        TextView viewLocation= listViewitem.findViewById(R.id.viewLocation);
        TextView viewDepartment= listViewitem.findViewById(R.id.viewDepartment);
        TextView viewUserName= listViewitem.findViewById(R.id.viewUserName);

        User user=userlist.get(position);

        viewName.setText(user.getName());
        viewEmployeeCode.setText(user.getEmpcode());
        viewLocation.setText(user.getLocation());
        viewDepartment.setText(user.getDepartment());
        viewUserName.setText(user.getUsername());

        return listViewitem;
    }
}

删除用户 PHP

<?php
$connection = mysqli_connect("localhost", "abc", "xyz", "id3275958_user");


if(isset($_POST['username'])) {
$username = $_POST['username'];

$result = mysql_query("DELETE FROM user WHERE username = $username");

$response = array();

if (mysql_affected_rows() > 0) {
    $response["success"] = 1;
    $response["message"] = "User successfully deleted";
} else {
    $response["success"] = 0;
    $response["message"] = "No User found";
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
}
echo json_encode($response);
?>

我还制作了 php 脚本并给了我适当的回应。只希望从我的应用程序发送用户名。

最佳答案

您的代码工作正常...

Just want send username from my app is remaining.

我建议从 btnDelete 到你的 Activity。

btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String username = viewUserName.getText().toString();
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                        try {
                            JSONObject js = new JSONObject(response);
                            boolean success = js.getBoolean("success");
// TODO: you could add Response Here from your backend the remaining username
                            if (success){
                                finish();
                                startActivity(getIntent());
                            }
                        }catch(JSONException e){
                            e.printStackTrace();
                        }

           ...
        }
    });

喜欢的响应,然后显示或提示用户

username_count

String count = js.getString("username_count"); // Just convert into Int if you needed

关于java - 我想从 ListView 中选择用户名文本字段并使用该用户名删除 mysql 数据库中存在的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47217712/

相关文章:

java - 在 Web 方法、服务层或 DAO 层中创建服务响应?

php - 将当前月份和年份与时间戳进行比较

android - 有多少设备支持移动接入点?

javascript - Android(三星Galaxy)上的JQuery Mask输入插件,返回的keyCode始终为229

android - 使用硬件加速 Android MediaCodec 解码器的 native 代码中的访问冲突

java - 删除 Android 列表中的最后一项

Java - 解决大于内存限制的问题

java - 卡住了 String.replace java with regex

php - 不包含图像/img/溢出的圆 Angular : hidden;

php - 如何在mysql中使用多个group by with inner join