简体   繁体   English

Android / MySQL:Spinner 不从 MySQL 填充数据

[英]Android / MySQL: Spinner not populate data from MySQL

I have a problem with my code.我的代码有问题。 I already created a spinner that populates from the MySQL database.我已经创建了一个从 MySQL 数据库填充的微调器。 The PHP code seem not have problem at all since I run the link "localhost/latihan1/menu/php", the json string will display. PHP 代码似乎完全没有问题,因为我运行链接“localhost/latihan1/menu/php”,将显示 json 字符串。

the json display as follows: json 显示如下:

{"result":[{"username":"haha","name":"Bus Bisnis","course":"math","session":"20119"},{"username":"hihi","name":"Bus Ace","course":"fizik","session":"12817"},{"username":"m_ridwan","name":"Ridwan","course":"Komputer","session":"1920"},{"username":"m_iqbal","name":"Iqbal","course":"Sains","session":"2021"}]} {"result":[{"username":"haha","name":"Bus Bisnis","course":"math","session":"20119"},{"username":"hihi", "name":"Bus Ace","course":"fizik","session":"12817"},{"username":"m_ridwan","name":"Ridwan","course":"Komputer" ,"session":"1920"},{"username":"m_iqbal","name":"Iqbal","course":"Sains","session":"2021"}]}

But when I open the apps, The spinner doesn't shows the data.但是当我打开应用程序时,微调器不显示数据。 I dont know why.我不知道为什么。 Below is my code下面是我的代码

JAVA爪哇

public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{公共类 MainActivity 扩展 AppCompatActivity 实现 Spinner.OnItemSelectedListener{

    private Spinner spinner;
    private ArrayList<String> students;

    //JSON Array
    private JSONArray result;

    private TextView textViewName;
    private TextView textViewCourse;
    private TextView textViewSession;

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

        //Initializing the ArrayList
        students = new ArrayList<String>();

        spinner = findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(this);

        textViewName = findViewById(R.id.textViewName);
        textViewCourse = findViewById(R.id.textViewCourse);
        textViewSession = findViewById(R.id.textViewSession);

        getData();
    }

    private void getData(){
        StringRequest stringRequest = new StringRequest(Config.DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        JSONObject j = null;

                        try {
                            j = new JSONObject(response);

                            result = j.getJSONArray(Config.JSON_ARRAY);

                            getStudents(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

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

    private void getStudents(JSONArray j){
        for(int i=0;i<j.length();i++){
            try {
                JSONObject json = j.getJSONObject(i);

                students.add(json.getString(Config.TAG_USERNAME));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
    }

    private String getName(int position){
        String name="";
        try {

            JSONObject json = result.getJSONObject(position);

            name = json.getString(Config.TAG_NAME);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return name;
    }

    private String getCourse(int position){
        String course="";
        try {
            JSONObject json = result.getJSONObject(position);
            course = json.getString(Config.TAG_COURSE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return course;
    }

    private String getSession(int position){
        String session="";
        try {
            JSONObject json = result.getJSONObject(position);
            session = json.getString(Config.TAG_SESSION);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return session;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //Setting the values to textviews for a selected item
        textViewName.setText(getName(position));
        textViewCourse.setText(getCourse(position));
        textViewSession.setText(getSession(position));
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        textViewName.setText("");
        textViewCourse.setText("");
        textViewSession.setText("");
    }
}

menu.php菜单.php

<?php 

    require_once "koneksi.php";

    $query = mysqli_query($con, "SELECT * FROM kendaraan ORDER BY id ASC");

    $students = array();    

    while($row = mysqli_fetch_array($query)){
        array_push($students,array(
            'username'=>$row['username'],
            'name'=>$row['name'],
            'course'=>$row['course'],
            'session'=>$row['session']
        ));
    }

    echo json_encode(array('result'=>$students));
    mysqli_close($con);
?>

I executed your code in my android studio.我在我的 android studio 中执行了你的代码。 I looks like that your network call is unable to fetch data (result remains null).我看起来您的网络调用无法获取数据(结果仍然为空)。 Check my code for reference.检查我的代码以供参考。 I replaced your network call with static data.我用静态数据替换了您的网络调用。

package com.attiq.testapp;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

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

import java.util.ArrayList;

public class Main5Activity extends AppCompatActivity implements Spinner.OnItemSelectedListener {
private Spinner spinner;
private ArrayList<String> students;

//JSON Array
private JSONArray result;

private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;

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

    //Initializing the ArrayList
    students = new ArrayList<String>();

    spinner = findViewById(R.id.spinner);
    spinner.setOnItemSelectedListener(this);

    textViewName = findViewById(R.id.textViewName);
    textViewCourse = findViewById(R.id.textViewCourse);
    textViewSession = findViewById(R.id.textViewSession);

    getData();
}

private void getData(){
    String json= "{\"result\":[{\"username\":\"haha\",\"name\":\"Bus Bisnis\",\"course\":\"math\",\"session\":\"20119\"},{\"username\":\"hihi\",\"name\":\"Bus Ace\",\"course\":\"fizik\",\"session\":\"12817\"},{\"username\":\"m_ridwan\",\"name\":\"Ridwan\",\"course\":\"Komputer\",\"session\":\"1920\"},{\"username\":\"m_iqbal\",\"name\":\"Iqbal\",\"course\":\"Sains\",\"session\":\"2021\"}]}";
    try {
        JSONObject jsonObject = new JSONObject(json);
        result= jsonObject.getJSONArray("result");
        getStudents(result);
    } catch (Exception e){
        e.printStackTrace();
    }
}

private void getStudents(JSONArray j) {
    for (int i = 0; i < j.length(); i++) {
        try {
            JSONObject json = j.getJSONObject(i);

            students.add(json.getString(Config.TAG_USERNAME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, students));
}

private String getName(int position) {
    String name = "";
    try {

        JSONObject json = result.getJSONObject(position);

        name = json.getString(Config.TAG_NAME);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return name;
}

private String getCourse(int position) {
    String course = "";
    try {
        JSONObject json = result.getJSONObject(position);
        course = json.getString(Config.TAG_COURSE);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return course;
}

private String getSession(int position) {
    String session = "";
    try {
        JSONObject json = result.getJSONObject(position);
        session = json.getString(Config.TAG_SESSION);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return session;
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    //Setting the values to textviews for a selected item
    textViewName.setText(getName(position));
    textViewCourse.setText(getCourse(position));
    textViewSession.setText(getSession(position));
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
    textViewName.setText("");
    textViewCourse.setText("");
    textViewSession.setText("");
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM