我有一个问题,我试图用图表编程加速度计,但是当我运行应用程序时我得到了这些错误,不幸的是,程序已停止:
Process: com.example.egnasz.myapplication, PID: 7963
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.egnasz.myapplication/com.example.egnasz.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2534)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5643)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
at com.telerik.widget.palettes.ChartPalettes.dark(ChartPalettes.java:108)
at com.example.egnasz.myapplication.MainActivity.createChart(MainActivity.java:212)
at com.example.egnasz.myapplication.MainActivity.onCreate(MainActivity.java:111)
at android.app.Activity.performCreate(Activity.java:6100)
如何解决?
MainActivity:
public class MainActivity extends Activity implements SensorEventListener {
private static final int X_AXIS_INDEX = 0;
private static final int Y_AXIS_INDEX = 1;
private static final int Z_AXIS_INDEX = 2;
private int defaultCoolDown;
private int coolDown;
private int bufferSize;
private int currentAxisIndex = X_AXIS_INDEX;
private int framesCount = 0;
boolean stopped = true;
private SensorManager sensorManager;
private Sensor accelerometer;
private ViewGroup chartContainer;
private RadCartesianChartView chart;
private Queue<SeismicDataPoint> seismicActivityBuffer;
private List<SeismicDataPoint> allSeismicActivity;
@Override
public void onSensorChanged(SensorEvent event) {
if (this.stopped || this.coolDown-- > 0) {
return;
}
this.coolDown = this.defaultCoolDown;
if (this.seismicActivityBuffer.size() > this.bufferSize) {
this.seismicActivityBuffer.remove();
}
SeismicDataPoint point = new SeismicDataPoint(this.framesCount++, event.values[this.currentAxisIndex]);
this.seismicActivityBuffer.add(point);
this.allSeismicActivity.add(point);
this.chartContainer.removeAllViews();
this.chart = createChart(seismicActivityBuffer);
this.chartContainer.addView(chart);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// hide the actionBar
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
// To be tweaked for performance on different devices
Resources resources = getResources();
this.defaultCoolDown = Integer.parseInt(resources.getString(R.string.default_cool_down));
this.bufferSize = Integer.parseInt(resources.getString(R.string.buffer_size));
this.coolDown = this.defaultCoolDown;
setContentView(R.layout.activity_main);
this.sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
this.accelerometer = this.sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
this.seismicActivityBuffer = new LinkedList<SeismicDataPoint>();
this.allSeismicActivity = new ArrayList<SeismicDataPoint>();
// Adding points to fill the screen at initial state.
for (int i = -this.bufferSize; i < 0; i++) {
this.seismicActivityBuffer.add(new SeismicDataPoint(i, 0));
}
this.chartContainer = (ViewGroup) findViewById(R.id.chart_container);
this.chart = createChart(this.seismicActivityBuffer);
this.chartContainer.addView(this.chart);
Button startBtn = (Button) findViewById(R.id.start_btn);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stop();
stopped = false;
}
});
Button stopBtn = (Button) findViewById(R.id.stop_btn);
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stop();
}
});
Button resetBtn = (Button) findViewById(R.id.reset_btn);
resetBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
// The activity is forced to landscape, so X and Y are different in phone and tablet devices.
final RadioGroup axisSelectionMenu = (RadioGroup) findViewById(R.id.axis_selection);
axisSelectionMenu.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.axis_x:
currentAxisIndex = X_AXIS_INDEX;
break;
case R.id.axis_y:
currentAxisIndex = Y_AXIS_INDEX;
break;
case R.id.axis_z:
currentAxisIndex = Z_AXIS_INDEX;
break;
default:
throw new IllegalArgumentException("there are only 3 axes");
}
}
});
}
@Override
protected void onResume() {
super.onResume();
this.sensorManager.registerListener(this, this.accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
this.sensorManager.unregisterListener(this);
}
private RadCartesianChartView createChart(Iterable<SeismicDataPoint> dataPoints) {
RadCartesianChartView chart = new RadCartesianChartView(this);
LinearAxis vAxis = new LinearAxis();
// The maximum value of the accelerometer is 20 and the minimum -20, so give a bonus 10 to the vertical axis.
vAxis.setMaximum(30);
vAxis.setMinimum(-30);
CategoricalAxis hAxis = new CategoricalAxis();
hAxis.setShowLabels(false);
DataPointBinding categoryBinding = new DataPointBinding() {
@Override
public Object getValue(Object o) throws IllegalArgumentException {
return ((SeismicDataPoint) o).x;
}
};
DataPointBinding valueBinding = new DataPointBinding() {
@Override
public Object getValue(Object o) throws IllegalArgumentException {
return ((SeismicDataPoint) o).y;
}
};
LineSeries series = new LineSeries();
series.setCategoryBinding(categoryBinding);
series.setValueBinding(valueBinding);
series.setData(dataPoints);
CartesianChartGrid grid = new CartesianChartGrid();
chart.setGrid(grid);
chart.setVerticalAxis(vAxis);
chart.setHorizontalAxis(hAxis);
chart.getSeries().add(series);
chart.setPalette(ChartPalettes.dark());
chart.setEmptyContent("");
// Customize chart elements after adding them to the chart to override the application of the palette.
hAxis.setTickColor(Color.TRANSPARENT);
grid.setMajorYLinesRenderMode(GridLineRenderMode.INNER_AND_LAST);
vAxis.setLineColor(Color.TRANSPARENT);
return chart;
}
private void stop() {
this.stopped = true;
this.chartContainer.removeAllViews();
this.chart = createChart(this.allSeismicActivity);
this.chartContainer.addView(this.chart);
}
}
SeismicDataPoint:
public class SeismicDataPoint {
public int x;
public float y;
public SeismicDataPoint(int x, float y) {
this.x = x;
this.y = y;
}
}
activity_main.xml中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.egnasz.myapplication.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/side_menu">
<Button
android:layout_width="75dp"
android:layout_height="wrap_content"
android:text="Start"
android:id="@+id/start_btn" />
<Button
android:layout_width="75dp"
android:layout_height="wrap_content"
android:text="Stop"
android:id="@+id/stop_btn"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<Button
android:layout_width="75dp"
android:layout_height="wrap_content"
android:text="Reset"
android:id="@+id/reset_btn" />
<RadioGroup
android:id="@+id/axis_selection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<RadioButton
android:id="@+id/axis_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X-axis"
android:checked="true" />
<RadioButton
android:id="@+id/axis_y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y-axis"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<RadioButton
android:id="@+id/axis_z"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z-axis" />
</RadioGroup>
</LinearLayout>
<FrameLayout
android:paddingRight="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/chart_container"
android:layout_toRightOf="@id/side_menu"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp" />
</RelativeLayout>
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.egnasz.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
的build.gradle:
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
android {
compileSdkVersion 24
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.example.egnasz.myapplication"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile (name: 'Chart-2016.3.914-trial-release', ext: 'aar')
compile (name: 'Common-2016.3.914-trial-release', ext: 'aar')
compile (name: 'Primitives-2016.3.914-trial-release', ext: 'aar')
testCompile 'junit:junit:4.12'
}
答案 0 :(得分:1)
如果您不希望ActionBar
中有Activity
,则可以从代码中删除以下行:
// hide the actionBar
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
将AppTheme
的父级替换为:
Theme.AppCompat.Light.NoActionBar
答案 1 :(得分:0)
只需按Theme.AppCompat.Light.NoActionBar
替换您的AppTheme父级(并删除getWindow()
到.hide();
的行,或使用以下方法getSupportActionBar().hide();
,因为您正在使用AppCompat
,v4.Toolbar
替换为v7.Toolbar
,而getActionBar()
返回v4.Toolbar
,您无法使用它。
答案 2 :(得分:0)
扩展您activity as AppCompatActivity
,然后使用操作栏: -
getSupportActionBar().hide(); // for hiding
getSupportActionBar().show(); // for showing
希望有所帮助