【问题标题】:I'm trying to show data from MySQL table to my Android app using listview, but it's now showing data我正在尝试使用 listview 将 MySQL 表中的数据显示到我的 Android 应用程序,但它现在正在显示数据
【发布时间】:2018-04-21 11:13:39
【问题描述】:

我想在android中将MySQL表数据显示到listview

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

我认为解析JSON对象有问题。

活动

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

ListviewAdapter

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 代码示例,它返回 JSON 字符串并使用 POST 并在 SQL Select 查询中包含 Where(如果您希望过滤响应),如果您希望查看是吗?
  • 检查我的新 php 脚本...打开那个 url 你会得到我想要的数据...我认为现在的问题是 java Jsonarray 解析..@YvesLeBorg
  • 请展示您从 PHP 代码收到的 JSON 响应的示例。这个JSONArray userArray= new JSONArray(response); 不会给你一个错误吗?
  • [{"name":"ajay","empcode":"1234","location":"Pune","department":"Technology","username":"acg"} ,{"name":"Ajay","empcode":"a123","location":"Goa","department":"Finance","username":"acg12"}] @Barns52
  • @AjayGohel ...请不要添加信息作为评论,而是编辑您的问题。

标签: java php android mysql listview


【解决方案1】:

诚然,您可能不需要在 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);

         }

【讨论】:

  • 更好 :) 或者,OP 可以使用 JSONObject 作为传递的依赖项向 User 添加一个构造函数,并在构造函数中管理播种。
  • 我必须在哪里定义arrayMessage? @Barns52
  • @AjayGohel :: 抱歉,arrayMessage 应该是 userArray 。请检查我编辑的回复。
猜你喜欢
  • 2021-12-19
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 2022-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多