You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从phpMyAdmin取数据在Android Studio(Java)实现Top5犯罪率柱状图

解决方案

一、修正PHP接口代码(Barrio.php)

原代码存在SQL字段错误、连接关闭变量名不匹配、未筛选前5条数据的问题,修正后代码如下:

<?php
include 'connection.php';

// 创建数据库连接
$con = mysqli_connect($hostname, $username, $password, $dbName);

if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

// SQL查询:统计各Barrio犯罪数,按数量降序取前5
$sql = "SELECT barrio_crime, COUNT(*) as count FROM report GROUP BY barrio_crime ORDER BY count DESC LIMIT 5";

$result = $con->query($sql);

$data = array();

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = array(
            "barrio_crime" => $row['barrio_crime'],
            "count" => $row['count']
        );
    }
}

// 关闭连接
$con->close();

// 返回JSON格式数据
header('Content-Type: application/json');
echo json_encode($data);
?>

二、完善Android布局文件(BarrioRate.xml)

原布局中两个TextView存在重叠问题,且有语法错误,修正后代码:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".BarrioRate"
    android:theme="@style/ThemeOverlay.AppCompat.DayNight.ActionBar">

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

        <TextView
            android:id="@+id/barrioRate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentEnd="true"
            android:layout_marginStart="0dp"
            android:gravity="center"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="0dp"
            android:fontFamily="sans-serif-black"
            android:text="@string/barrio_crime"
            android:textColor="@color/Poseidon"
            android:textSize="30sp"/>

        <TextView
            android:id="@+id/topBarrio"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/barrioRate"
            android:layout_alignParentStart="true"
            android:layout_alignParentEnd="true"
            android:layout_marginStart="0dp"
            android:gravity="center"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="0dp"
            android:fontFamily="sans-serif-black"
            android:text="Top 5 Barrio that have a highest Crimes"
            android:textColor="@color/Poseidon"
            android:textSize="18sp"/>

        <com.github.mikephil.charting.charts.BarChart
            android:id="@+id/barChart"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_below="@id/topBarrio"
            android:layout_marginTop="10dp"
            android:layout_marginStart="30dp"
            android:layout_marginEnd="30dp" />

    </RelativeLayout>
</ScrollView>

三、完成Android Java代码(BarrioRate.java)

1. 添加依赖

在app模块的build.gradle中添加以下依赖:

dependencies {
    // MPAndroidChart
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
    // OkHttp网络请求库
    implementation 'com.squareup.okhttp3:okhttp:4.10.0'
}

2. 完整Java代码

package com.example.mobile;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;

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

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BarrioRate extends AppCompatActivity {

    private BarChart barChart;
    // 替换为你的PHP接口实际地址
    private static final String API_URL = "http://your-server-ip/Barrio.php";

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

        barChart = findViewById(R.id.barChart);
        initChart();
        fetchDataFromAPI();
    }

    // 初始化图表基础配置
    private void initChart() {
        barChart.getDescription().setEnabled(false);
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        barChart.setTouchEnabled(true);
        barChart.setDragEnabled(true);
        barChart.setScaleEnabled(true);
    }

    // 从PHP接口获取数据
    private void fetchDataFromAPI() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API_URL)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(BarrioRate.this, "数据加载失败", Toast.LENGTH_SHORT).show());
                Log.e("BarrioRate", "API请求失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    String jsonData = response.body().string();
                    parseJsonData(jsonData);
                } else {
                    runOnUiThread(() -> Toast.makeText(BarrioRate.this, "数据获取失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    // 解析JSON并设置图表数据
    private void parseJsonData(String jsonData) {
        ArrayList<BarEntry> entries = new ArrayList<>();
        ArrayList<String> barrioLabels = new ArrayList<>();

        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                String barrio = obj.getString("barrio_crime");
                int count = obj.getInt("count");

                entries.add(new BarEntry(i, count));
                barrioLabels.add(barrio);
            }

            runOnUiThread(() -> {
                BarDataSet dataSet = new BarDataSet(entries, "犯罪总数");
                dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
                BarData barData = new BarData(dataSet);
                barData.setBarWidth(0.6f);

                barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(barrioLabels));
                barChart.setData(barData);
                barChart.invalidate();
            });

        } catch (JSONException e) {
            runOnUiThread(() -> Toast.makeText(BarrioRate.this, "数据解析失败", Toast.LENGTH_SHORT).show());
            Log.e("BarrioRate", "JSON解析错误: " + e.getMessage());
        }
    }
}

注意事项

  • 替换API_URL为你的PHP接口实际部署地址
  • 在AndroidManifest.xml中添加网络权限:<uses-permission android:name="android.permission.INTERNET"/>
  • 若使用Android 9及以上版本,需在AndroidManifest.xml的<application>标签中添加android:usesCleartextTraffic="true"(或配置HTTPS)

内容的提问来源于stack exchange,提问作者lalalalala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:18:12