java - 我正在尝试使用 ListView 将 MySQL 表中的数据显示到我的 Android 应用程序,但它现在正在显示数据

标签 java php android mysql listview

我想将 MySQL 表数据显示到 listview 中在安卓中。

我使用 UserClass对于模型,ListViewAdapter用于列表适配器和 ViewUser class 是将显示 ListView 的主类.我正在使用 PHP 脚本从 MySQL 获取数据。

我认为在解析 JSON 对象时存在一些问题。

Activity

public class ViewUser extends AppCompatActivity {

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

ListView listUser;
List<User> userlist;

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

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

    loadUserList();
}
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 {
                JSONArray userArray= new JSONArray(response);


                for (int i=0;userArray.length()<i;i++){
                    JSONObject userObject = userArray.getJSONObject(i);
                    User user=new User();
                   user.getName();
                   user.getEmpcode();
                   user.getLocation();
                   user.getDepartment();
                   user.getUsername();
                    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);
}
}

用户类

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;
}
}

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") or die("Error " . mysqli_error($connection));

$sql = "select name,empcode,location,department,username from user";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}
echo json_encode($emparray);

mysqli_close($connection);
?>

JSON

[{
"name": "ajay",
"empcode": "1234",
"location": "Pune",
"departmnt": "Technology",
"username": "acg"
 }, {
"name": "Ajay",
"empcode": "a123",
"location": "Goa",
"department": "Finance",
"username": "acg12"
}
]

item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/viewName"
    android:layout_width="100dp"
    android:layout_height="28dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.067"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.017" />

<TextView
    android:id="@+id/viewEmployeeCode"
    android:layout_width="100dp"
    android:layout_height="31dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.533"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.017" />

<TextView
    android:id="@+id/viewLocation"
    android:layout_width="100dp"
    android:layout_height="33dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.97"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.017" />

<TextView
    android:id="@+id/viewDepartment"
    android:layout_width="100dp"
    android:layout_height="27dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.1"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.087" />

<TextView
    android:id="@+id/viewUserName"
    android:layout_width="100dp"
    android:layout_height="29dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.533"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.087" />
</android.support.constraint.ConstraintLayout>

最佳答案

诚然,您可能不需要在 PHP 中添加顶级数组,但它对我有用。

    // Add a top level array object to contain your rows of data
    $response["data"] = array();

while ($row = mysqli_fetch_assoc($result)) {
    $data = array(); // Your return array
    $data["name"] = $row["name"]
    $data["empcode"] = $row["empcode"];
    $data["location"] = $row["location"];
    $data["department"] = $row["department"];
    $data["username"] = $row["username"];

    // pushes a new row onto your array with each iteration
    array_push($response["data"], $data);
}
// Echo your response
echo json_encode($response);

现在您可以像这样解析您的 JSON 响应:

   try {
        JSONObject oResponse = new JSONObject(response)
        JSONArray userArray = oResponse.getJSONArray("data");


        for (int i=0;userArray.length()<i;i++){
             final JSONObject o = userArray.getJSONObject(i);
             User user=new User();

            // You must know what type you expect from your response
            // eg. String, int, ...
            String name= o.optString("name", "");
            String empcode= o.optString("empcode", "");
            String location= o.optString("location", "");
            String department= o.optString("department", "");
            String username= o.optString("username", "");
            // You need to add the setter to your model class
            user.setName(name);
            user.setEmpcode(empcode);
            // ... and so on ...
            userlist.add(user);

         }

关于java - 我正在尝试使用 ListView 将 MySQL 表中的数据显示到我的 Android 应用程序,但它现在正在显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185257/

相关文章:

java - Android Studio 0.8.2 URI 有一个权限组件

java - 通过 awselb 使用 ssl 时的 neo4j java 驱动程序问题

php - Xpath路径帮助

android - 具有主/详细流程的 fragment 中的可扩展 ListView

android - 所有屏幕尺寸的资源文件夹名称

java - 如何让自签名证书代码只执行一次?

java - 带 Jersey 的 JAX-RS 无法在 JBoss AS 中工作

php 创建文件并作为附件发送而不实际创建文件

PHP,如何将 func-get-args 值作为参数列表传递给另一个函数?

android - 在 Android 上的 OpenGL ES 中绘制四边形