使用Volley在Android

使用Volley在Android

本文介绍了使用Volley在Android Studio上显示MySQL数据的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习并尝试使用php将一些MySQL数据显示到php的android studio中.该应用程序正在正常运行,但未显示数据.我试图找出原因,但是几天没碰运气(可能是由于我还是Android Studio和Java的新手).

I am learning and trying to display some MySQL data using php to android studio using volley. The app is running with no errors but the data is not being displayed. I have tried to figure out why but had no luck for a few days (possibly due to I am still new to android studio and Java).

我的.sql是:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `test1`
--

CREATE TABLE `test1` (
  `name` varchar(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `moivename` varchar(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

--
-- Dumping data for table `test1`
--

INSERT INTO `test1` (`name`, `moivename`) VALUES
('ab', 'cd'),
('ef', 'gh');
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

我的api是:

<?php

$servername = "127.0.0.1";
$username   = "root";
$password   = "MyPW";
$dbname     = "testing";

// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8');

$sql = "SELECT * FROM test1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $rows = $result->fetch_all(MYSQLI_ASSOC);

    echo json_encode($rows);
} else {
    echo "no results found";
}

导入androidx.recyclerview.widget.RecyclerView;

import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String HI ="http://xxx/phpMyAdmin-5.0.4/Api.php" ;   //xxx is ip and the user name
    private List<List_Data> list_data;
    private RecyclerView rv;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv=(RecyclerView)findViewById(R.id.recyclerView);
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(this));
        list_data=new ArrayList<>();
        adapter=new MyAdapter(list_data);

        getMovieData();

    }

    private void getMovieData() {
StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        try {
            JSONArray array=new JSONArray(response);
            for (int i=0; i<array.length(); i++ ){
                JSONObject ob=array.getJSONObject(i);
                List_Data listData=new List_Data(ob.getString("name")
                        ,ob.getString("moivename"));
                list_data.add(listData);
            }
            adapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }

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

    }
});
    RequestQueue requestQueue= Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
}

JSON格式为:

 [{"name":"ab","moivename":"cd"},{"name":"ef","moivename":"gh"}]

适配器是:

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
    private List<List_Data>list_data;

    public MyAdapter(List<List_Data> list_data) {
        this.list_data = list_data;
    }

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

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        List_Data listData=list_data.get(position);
        holder.txtname.setText(listData.getName());
        holder.txtmovie.setText(listData.getMoviename());
    }

    @Override
    public int getItemCount() {

        return list_data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView txtname,txtmovie;
        public ViewHolder(View itemView) {
            super(itemView);
            txtname=(TextView)itemView.findViewById(R.id.txt_name);
            txtmovie=(TextView)itemView.findViewById(R.id.txt_moviename);
        }
    }
}

此外,我像这样设置类:

Also, I setup the class like so:

    public class List_Data {
    private String name;
    private String moviename;

    public List_Data(String name, String moviename) {
        this.name = name;
        this.moviename = moviename;
    }

    public String getName() {
        return name;
    }

    public String getMoviename() {
        return moviename;
    }
}

activity_main.xml是:

And the activity_main.xml is:

<RelativeLayout
    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=".MainActivity">

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

</RelativeLayout>

还有list_data.xml:

And list_data.xml:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <LinearLayout
            android:layout_marginLeft="10dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <TextView
                android:textColor="#111"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="name:"/>

            <TextView
                android:id="@+id/txt_name"
                android:textColor="#111"
                android:layout_marginLeft="10dp"
                style="@style/Base.TextAppearance.AppCompat.Medium"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_marginLeft="10dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
            <TextView
                android:textColor="#111"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="moivename:"/>

            <TextView
                android:id="@+id/txt_moviename"
                android:textColor="#111"
                android:layout_marginLeft="10dp"
                style="@style/Base.TextAppearance.AppCompat.Medium"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </LinearLayout>
    </LinearLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>

我有没有听错的地方吗?

Is there something wrong that I did not catch?

更新:按照建议将电影名称更改为电影名称,但应用程序仍不显示MySQL数据

日志猫:

2021-01-13 19:16:22.218 27201-27201/? I/fetchingtestin: Not late-enabling -Xcheck:jni (already on)
2021-01-13 19:16:22.330 27201-27201/? I/fetchingtestin: Unquickening 12 vdex files!
2021-01-13 19:16:22.353 27201-27201/? W/fetchingtestin: Unexpected CPU variant for X86 using defaults: x86
2021-01-13 19:16:23.338 27201-27201/com.example.fetchingtesting D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-01-13 19:16:23.339 27201-27201/com.example.fetchingtesting D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-01-13 19:16:23.398 27201-27228/com.example.fetchingtesting D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2021-01-13 19:16:23.437 27201-27228/com.example.fetchingtesting D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2021-01-13 19:16:23.447 27201-27228/com.example.fetchingtesting D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2021-01-13 19:16:23.586 27201-27201/com.example.fetchingtesting W/fetchingtestin: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2021-01-13 19:16:23.587 27201-27201/com.example.fetchingtesting W/fetchingtestin: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2021-01-13 19:16:23.768 27201-27225/com.example.fetchingtesting D/HostConnection: HostConnection::get() New Host Connection established 0xecf9ef50, tid 27225

推荐答案

android:usesCleartextTraffic ="true"

android:usesCleartextTraffic="true"

将其放入清单文件

https://developer.android.com/guide/topics/manifest/application-element#usesCleartextTraffic 对此进行检查

这篇关于使用Volley在Android Studio上显示MySQL数据的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:15