首页 > 解决方案 > Recycler View无法显示mysql数据

问题描述

请帮我处理这段代码。我想显示来自mysql的数据并将其显示到android。我在我的 mysql 中插入数据并在我的 android 上显示我的 mysql 中有多少数据,以便我知道我的 android 应用程序是否可以从 mysql 读取我的所有数据,但是当我运行我的 android 应用程序时,它说没有数据。请帮我

安卓代码...

data_list = new ArrayList<>();
    load_data_from_server();
    gridLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(gridLayoutManager);

    adapter = new CustomAdapter(this, data_list);
    recyclerView.setAdapter(adapter);

if (adapter.getItemCount() == 0){
        Toast.makeText(this, "Empty", Toast.LENGTH_SHORT).show();
    }

private void load_data_from_server() {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://192.168.43.147/webapp/travelplanning.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                JSONArray array = new JSONArray(response.body().string());

                for(int i = 0; i < array.length(); i++){
                    JSONObject object = array.getJSONObject(i);
                    MyData data = new MyData(object.getInt("ID"), object.getString("AttractionName"), object.getString("Location"));

                    data_list.add(data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            adapter.notifyDataSetChanged();
        }
    };
}

适配器...

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<MyData> my_data;

public CustomAdapter(Context context, List<MyData> my_data) {
    this.context = context;
    this.my_data = my_data;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.travel_planning_card, parent, false);
    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.id.setText(my_data.get(position).getId());
    holder.attractionName.setText(my_data.get(position).getAttractioName());
    holder.location.setText(my_data.get(position).getLocation());
}

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

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView attractionName, location, id;
    public ImageView image;


    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        attractionName = itemView.findViewById(R.id.tvAttractionName);
        location = itemView.findViewById(R.id.tvLocation);
        id = itemView.findViewById(R.id.tvID);
    }
}

}

构造函数...

package com.example.tourismolocal;

public class MyData {
private int id;
private String attractioName, location, image;

public MyData(int id, String attractioName, String location) {
    this.id = id;
    this.attractioName = attractioName;
    this.location = location;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getAttractioName() {
    return attractioName;
}

public void setAttractioName(String attractioName) {
    this.attractioName = attractioName;
}

public String getLocation() {
    return location;
}

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

}

布局...

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
tools:context=".travelplanning"
android:background="@drawable/img_banner">

<FrameLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="120dp"
    android:layout_marginEnd="10dp"
    android:layout_marginBottom="60dp"
    android:background="@drawable/square"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/recTravel">

        </androidx.recyclerview.widget.RecyclerView>

    </LinearLayout>
</FrameLayout>

<EditText
    android:id="@+id/etSearchAttraction"
    android:layout_width="0dp"
    android:layout_height="38dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="72dp"
    android:autofillHints=""
    android:background="@drawable/searchdestination"
    android:drawableStart="@drawable/icon_search1"
    android:ems="10"
    android:hint="@string/etsearchdestination"
    android:inputType="textPersonName"
    android:paddingStart="10dp"
    app:layout_constraintEnd_toStartOf="@+id/btnAddAttraction"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:focusable="false"/>

<Button
    android:id="@+id/btnAddAttraction"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="5dp"
    android:layout_marginEnd="10dp"
    android:background="@drawable/icon_plus"
    app:layout_constraintBaseline_toBaselineOf="@+id/etSearchAttraction"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/etSearchAttraction" />

<FrameLayout
    android:id="@+id/frameLayout2"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/navbar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@drawable/nav_topborder"></LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:orientation="horizontal"
        android:paddingTop="1dp">

        <Button
            android:id="@+id/btnAttraction"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_places"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/attract"
            android:textAllCaps="false"
            android:textColor="#2d3e52"
            android:textSize="9dp" />

        <Button
            android:id="@+id/btnTrips"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_trips"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/trips"
            android:textAllCaps="false"
            android:textColor="#A6A3A3"
            android:textSize="9dp" />

        <Button
            android:id="@+id/btnWishlist"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_wishlist"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/wishlist"
            android:textAllCaps="false"
            android:textColor="#A6A3A3"
            android:textSize="9dp" />
    </LinearLayout>


</FrameLayout>

<ImageView
    android:id="@+id/imgUser"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="15dp"
    android:src="@drawable/icon_mainuser"
    app:layout_constraintStart_toEndOf="@+id/imageView4"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ImageView
    android:id="@+id/imageView6"
    android:layout_width="0dp"
    android:layout_height="25dp"
    android:layout_marginTop="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/img_logowhite" />

卡片布局...

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

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgAttraction"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher_round"
        android:layout_margin="10dp"/>

    <LinearLayout
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="320dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tvAttractionName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Attraction Name"
                android:textSize="20dp"
                android:textColor="#000000"/>

            <TextView
                android:id="@+id/tvLocation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Location"
                android:textSize="20dp"
                android:textColor="#000000"/>
        </LinearLayout>

        <TextView
            android:id="@+id/tvID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ID"
            android:textSize="26dp"
            android:textColor="#000000"
            android:layout_marginTop="7dp"
            android:textAlignment="textEnd"
            android:visibility="invisible"/>

        <TextView
            android:id="@+id/tvRate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:text="Rating"
            android:textAlignment="textEnd"
            android:textColor="#000000"
            android:textSize="26dp" />

    </LinearLayout>

</androidx.cardview.widget.CardView>

PHP 文件....

<?php
require "init.php";

if(mysqli_connect_error($con))
{
    echo "Failed to connect";
}

$query = "Select id, attractionname, location from attraction";
$result = mysqli_query($con, $query);

if($result){
    while($row=mysqli_fetch_array($result)){
       $flag[]=$row;
    }

    print(json_encode($flag));
}
mysqli_close($con);
?>

标签: phpandroidmysqlandroid-recyclerview

解决方案


你不能这样。因为,您不会更改 AsyncTask 中的 ui 操作。尝试这个。

private void load_data_from_server() {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://192.168.43.147/webapp/travelplanning.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                JSONArray array = new JSONArray(response.body().string());
                List<MyData> list = new ArrayList<>();
                for(int i = 0; i < array.length(); i++){
                    JSONObject object = array.getJSONObject(i);
                    MyData data = new MyData(object.getInt("ID"), object.getString("AttractionName"), object.getString("Location"));

                    list.add(data);
                }
                setListData(list);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
        }
    };
}

private void setListData(List<MyData> list) {
  data_list.addAll(list);
  adapter.notifyDataSetChanged();
}

推荐阅读