RecyclerView没有加载数据

时间:2018-10-19 11:53:57

标签: php android android-recyclerview

我正在尝试使用来自php的数据加载我的recyclerview。但是由于某些未知的原因,它没有加载任何数据。我在其他活动中也使用了相同的代码,虽然可以正常工作,但对于本活动而言,它仍然是空白。我已经测试过我的php文件,效果很好。

这是我的活动代码:

public class Match_scoring extends AppCompatActivity implements TeamAdapter.onItemClickListener {

    public static String URL_data;
    public static String p_id;
    public static String p_name;

    TeamAdapter adapter;
    EditText editText;
    List<TeamItems> list_items;
    RecyclerView recyclerView;
    Button subs;

    TextView tv;

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

        URL_data = "http://prasaurus.com/trial_db_php/tbl_show_201_0_data.php";

        tv = (TextView)findViewById(R.id.url);
        tv.setText(URL_data);

        editText = (EditText)findViewById(R.id.mSearch_match);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                filter(s.toString());
            }
        });

        recyclerView = (RecyclerView)findViewById(R.id.total_players_recyclerView);

        recyclerView.setHasFixedSize(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        list_items = new ArrayList<>();

        adapter = new TeamAdapter(list_items,getApplicationContext());

        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(Match_scoring.this);

        loadRecyclerViewData();

    }

    private void loadRecyclerViewData() {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_data, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int success = jsonObject.getInt("success");
                    if (success == 1) {
                        JSONArray jsonArray = jsonObject.getJSONArray("Data");

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject_current = jsonArray.getJSONObject(i);
                            TeamItems teamItems = new TeamItems(
                                    jsonObject_current.getString("player_id"),
                                    jsonObject_current.getString("player_name"),
                                    jsonObject_current.getString("player_dob"),
                                    jsonObject_current.getString("position"),
                                    jsonObject_current.getString("team_id")
                            );
                            list_items.add(teamItems);
                        } adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(getApplicationContext(), "Please try again later.", Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG);
            }
        });

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

    }

    private void filter(String text){
        ArrayList<TeamItems> filteredList = new ArrayList<>();

        for (TeamItems item : list_items){
            if(item.getPlayer_name().toLowerCase().contains(text.toLowerCase())){
                filteredList.add(item);
            }
        }
        adapter.filterList(filteredList);
    }

    @Override
    public void onItemClick(int position) {
        TeamItems clickedItem = list_items.get(position);

        Intent details = new Intent(Match_scoring.this,ScoringDetails.class);
        p_id = clickedItem.getPlayer_id();
        p_name = clickedItem.getPlayer_name();

        startActivity(details);


    }
}

以下是相同的布局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"
    tools:context=".Match_scoring">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <EditText
        android:id="@+id/mSearch_match"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:hint="Search Player"

        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/total_players_recyclerView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="8dp"
        android:layout_marginVertical="8dp"
        android:layout_below="@id/mSearch_match"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/substitute"
        android:text="SUBS"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/total_players_recyclerView"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_below="@id/substitute"
            android:layout_centerHorizontal="true"
            android:id="@+id/url"/>

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

这是我的php脚本:

<?php
$servername = "prasaurus.com";
$username = "prasauru_fand";
$password = "[DB-PASSWORD]";
$dbname = "prasauru_trial_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$pair_id=$_POST['pair_id'];
$fixture=$_POST['fixture'];

$response = array();

$query = "select * from tbl_201_0_match_details";



$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) > 0){
    $response['success'] = 1;
    $Data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        array_push($Data , $row);
    }
        $response['Data'] = $Data;
}
else {
    $response['success'] = 0;
    $response['message'] = 'No data';
}

echo json_encode($response);    
mysqli_close($conn);


?>

1 个答案:

答案 0 :(得分:1)

我多次遇到这个问题。因为适配器上的notifyDatasetChanged()不能正常工作。

只需在recyclerview适配器中创建简单函数,并在可从网络调用获得数据时调用函数即可

public void updateDataset(List<Model> updatedData){
yourListWhichInflateData=updatedData;
notifyDatasetChanged();
}

只要活动中有可用数据或已更新数据,就使用适配器实例调用上述功能。