帮我写一段代码,在Android studio中加载json文件并绘制图形
时间: 2023-03-30 10:03:06 浏览: 207
好的,以下是加载json文件并绘制图形的代码示例:
1. 首先,在Android Studio中创建一个新项目,并在app/build.gradle文件中添加以下依赖项:
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.github.mikephil:charting:3.1.'
2. 在MainActivity.java文件中添加以下代码:
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private RequestQueue mQueue;
private BarChart mChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChart = findViewById(R.id.chart);
mQueue = Volley.newRequestQueue(this);
jsonParse();
}
private void jsonParse() {
String url = "https://api.myjson.com/bins/1e7j9u";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
ArrayList<BarEntry> entries = new ArrayList<>();
for (int i = ; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
float value = (float) data.getDouble("value");
entries.add(new BarEntry(i, value));
}
BarDataSet dataSet = new BarDataSet(entries, "Data");
dataSet.setColor(Color.BLUE);
BarData barData = new BarData(dataSet);
mChart.setData(barData);
mChart.invalidate();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: ", error);
}
});
mQueue.add(request);
}
}
3. 在activity_main.xml文件中添加以下代码:
<?xml version="1." encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
这段代码将从指定的URL加载JSON数据,解析它,并将其用于绘制柱状图。您可以将URL替换为您自己的JSON数据源,并根据需要进行修改。
阅读全文