为什么AnyChart返回Null对象引用异常?

问题描述 投票:0回答:2

我一直在尝试使用AnyChart和MPAndroidChart创建简单饼图的一些教程:

但是,当我运行以上所有示例时,我得到一个例外:

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.anychart.AnyChartView$JsListener com.anychart.AnyChartView.getJsListener()' on a null object reference
        at com.anychart.APIlib.addJSLine(APIlib.java:27)
        at com.anychart.charts.Pie.<init>(Pie.java:34)
        at com.anychart.AnyChart.pie(AnyChart.java:130)
        at com.mpereira.savingstrackerapp.Activities.TestActivity.setupPieChart(TestActivity.java:37)
        at com.mpereira.savingstrackerapp.Activities.TestActivity.onCreate(TestActivity.java:33)

我已经相应地添加了依赖性,这是xml代码:

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:padding="10dp"
    tools:context=".Activities.TestActivity">

    <com.anychart.AnyChartView
        android:id="@+id/any_chart_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>

这里是活动代码:(来自https://www.youtube.com/watch?v=qWBA2ikLJjU

public class TestActivity extends AppCompatActivity {

    private static String TAG = "MainActivity";
    AnyChartView anyChartView;
    String[] months = {"Jan", "Feb", "Mar"};
    int[] earnings = {500, 800, 350};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate: starting to create chart");
        anyChartView = (AnyChartView) findViewById(R.id.any_chart_view);

        setupPieChart();
    }

    void setupPieChart(){
        Pie pie = AnyChart.pie();
        List<DataEntry> dataEntries = new ArrayList<>();
        for (int i=0;i<months.length; ++i){
            dataEntries.add(new ValueDataEntry(months[i], earnings[i]));
        }
        pie.data(dataEntries);
        anyChartView.setChart(pie);
    }
}

以下是屏幕截图:exception

我知道我们通常需要new关键字来创建对象,但是根据教程https://github.com/AnyChart/AnyChart-Android/wiki/Getting-started,在Pie pie = AnyChart.pie();中不需要它

赞赏有关如何修复它的任何提示。

android exception anychart
2个回答
1
投票

根据https://www.anychart.com/technical-integrations/samples/android-charts/教程,您的布局代码应像这样

  <com.anychart.anychart.AnyChartView
    android:id="@+id/any_chart_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

0
投票

检查您的XML(您正在使用相对布局),在主要活动中导入您正在使用的API级别,并确保已根据Gettings Started指南将AnyChart库正确添加到Gradle中。您的主要活动代码还可以,我已经根据您的代码成功构建了图表。

热门问题
推荐问题
最新问题