我已经在网上和 stackoverflow 上搜索了它,但我找不到我的问题的解决方案。在我的应用程序中,我记录加速度计数据(x、y 和 z),将它们写入数据库,然后从另一个名为 generateFeatures 的扩展 mainActivity 的类中从数据库获取的加速度计数据生成一些特征(我从 mainActivity 派生它的原因是使用数据库类并在其中使用 sqlite 命令)。在我的主要活动(它的名称是 MainActivity)中,我将其用作成员字段并初始化 generateFeatures 类以在其中生成功能。但是当我启动应用程序时。它崩溃并发出。
12-27 21:03:16.735: E/AndroidRuntime(27236): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.coordinates/com.example.coordinates.MainActivity}: java.lang.NullPointerException
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.ActivityThread.access$600(ActivityThread.java:140)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.os.Looper.loop(Looper.java:137)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.ActivityThread.main(ActivityThread.java:4898)
12-27 21:03:16.735: E/AndroidRuntime(27236): at java.lang.reflect.Method.invokeNative(Native Method)
12-27 21:03:16.735: E/AndroidRuntime(27236): at java.lang.reflect.Method.invoke(Method.java:511)
12-27 21:03:16.735: E/AndroidRuntime(27236): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
12-27 21:03:16.735: E/AndroidRuntime(27236): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
12-27 21:03:16.735: E/AndroidRuntime(27236): at dalvik.system.NativeStart.main(Native Method)
12-27 21:03:16.735: E/AndroidRuntime(27236): Caused by: java.lang.NullPointerException
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:228)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
12-27 21:03:16.735: E/AndroidRuntime(27236): at com.example.coordinates.generateFeatures.<init>(generateFeatures.java:25)
12-27 21:03:16.735: E/AndroidRuntime(27236): at com.example.coordinates.MainActivity.onCreate(MainActivity.java:93)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.Activity.performCreate(Activity.java:5184)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
12-27 21:03:16.735: E/AndroidRuntime(27236): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
12-27 21:03:16.735: E/AndroidRuntime(27236): ... 11 more
这是 mainActivity 类:
public class MainActivity extends FragmentActivity implements SensorEventListener,dialogFragement.NoticeDialogListener {
private SensorManager sm;
private Sensor myAccelerometer;
private VeriTabani veritabani;
private SQLiteDatabase db;
private FragmentManager fm;
private ContentValues myContentValues;
private generateFeatures gf;
private ArrayList<Float> valuesX;
private ArrayList<Float> valuesY;
private ArrayList<Float> valuesZ;
private ArrayList<Float> zamanDiyagrami;
private float totalX,totalY,totalZ,averageX,averageY,averageZ,stdX,stdY,stdZ,aadX,aadY,aadZ,averageResultantAcc,maxX,maxY,maxZ;
TextView x;
TextView y;
TextView z;
Button b1,b2,b3;
private String dosyaAdi;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myContentValues=new ContentValues();
fm=getFragmentManager();
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
x=(TextView)findViewById(R.id.textView4);
y=(TextView)findViewById(R.id.textView5);
z=(TextView)findViewById(R.id.textView6);
sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
myAccelerometer= sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, myAccelerometer,50000);
veritabani= new VeriTabani(this);
db=veritabani.getWritableDatabase();
valuesX= new ArrayList<Float>();
valuesY= new ArrayList<Float>();
valuesZ= new ArrayList<Float>();
zamanDiyagrami= new ArrayList<Float>();
gf=new generateFeatures(dosyaAdi);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
grafikGoruntule();
}
});
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
verileriSil();
}
});
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
createDialog();
}
});
}
public void createDialog(){
sm.unregisterListener(this);
DialogFragment dialog = new dialogFragement();
dialog.show(fm, "MyDialogFragment");
sm.registerListener(this, myAccelerometer,50000);
}
public void verileriSil(){
try{
db.delete("Koordinatlar", null, null);
db.delete("Features", null, null);
}
catch(SQLException ex){
ex.printStackTrace();
Toast toast=Toast.makeText(getBaseContext(),"Silme işlemi sırasında bir hata oluştu"+" "+ex.toString(),Toast.LENGTH_SHORT);
toast.show();
}
Toast toast= Toast.makeText(getBaseContext(), "Silme işlemi başarılı",Toast.LENGTH_SHORT);
toast.show();
}
public void grafikGoruntule(){
sm.unregisterListener(this);
startActivity(getIntent(this));
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float xGoster,yGoster,zGoster;
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
xGoster=(event.values[0]);
yGoster=(event.values[1]);
zGoster=(event.values[2]);
x.setText(Float.toString(xGoster));
y.setText(Float.toString(yGoster));
z.setText(Float.toString(zGoster));
kayitEkle(xGoster,yGoster,zGoster,System.currentTimeMillis());
}
}
public void kayitEkle(float xKoor,float yKoor,float zKoor,long zamanMiliSaniye){
ContentValues degerler= new ContentValues();
degerler.put("xKoor", xKoor);
degerler.put("yKoor", yKoor);
degerler.put("zKoor", zKoor);
degerler.put("zaman", zamanMiliSaniye);
try{
db.insertOrThrow("Koordinatlar", null, degerler);
}
catch(SQLException ex){
ex.printStackTrace();
}
}
private void dosyayaYaz(){
Cursor dataReader;
File myFile;
myFile= new File("sdcard/"+dosyaAdi.toString()+".csv");
try {
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("X Koor;Y Koor;Z Koor");
myOutWriter.append("\n");
dataReader=db.rawQuery("SELECT * FROM Koordinatlar", null);
while(dataReader.moveToNext()){
Float xDeg=(dataReader.getFloat(dataReader.getColumnIndex("xKoor")));
Float yDeg=(dataReader.getFloat(dataReader.getColumnIndex("yKoor")));
Float zDeg=(dataReader.getFloat(dataReader.getColumnIndex("zKoor")));
myOutWriter.append(String.format("%f",xDeg)+";"+String.format("%f",yDeg)+";"+String.format("%f",zDeg));
myOutWriter.append("\n");
}
myOutWriter.close();
fOut.close();
Toast toast=Toast.makeText(getBaseContext(), "Koordinat değerleri başarıyla dosyaya yazıldı, feature değerleri üretiliyor...Lütfen bekleyiniz...",Toast.LENGTH_SHORT);
toast.show();
}
catch(IOException ex){
Toast toast=Toast.makeText(getBaseContext(), "Dosyaya yazma sırasında bir hata oluştu"+" "+ex.toString(),Toast.LENGTH_LONG);
toast.show();
}
gf.letsRollOut();
}
protected void onPause() {
// is called when a different Activity instance is going to be visible
// and the current Activity has stopped interacting with the user
super.onPause();
sm.unregisterListener(this);
}
protected void onResume() {
//is called when the Activity object and its views become interactive with the user
super.onResume();
sm.registerListener(this, myAccelerometer,50000);
}
protected void onStop() {
//is called when an activity is no longer visible to, or interacting with, the user
super.onStop();
sm.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public Intent getIntent(Context context){
Cursor dataReader;
valuesX.clear();
valuesY.clear();
valuesZ.clear();
float zamanIndis=(float) 0.0;
String sqlIfadesi="SELECT * FROM Koordinatlar WHERE zaman>=((SELECT MAX(zaman) FROM Koordinatlar)-10000)";
dataReader=db.rawQuery(sqlIfadesi, null);
int veriSayisi;
veriSayisi=dataReader.getCount();
while(dataReader.moveToNext()){
valuesX.add(dataReader.getFloat(dataReader.getColumnIndex("xKoor")));
valuesY.add(dataReader.getFloat(dataReader.getColumnIndex("yKoor")));
valuesZ.add(dataReader.getFloat(dataReader.getColumnIndex("zKoor")));
zamanIndis=zamanIndis+1;
zamanDiyagrami.add(zamanIndis);
}
TimeSeries series = new TimeSeries("Line1");
for( int i = 0; i < veriSayisi; i++)
{
series.add(zamanDiyagrami.get(i), valuesX.get(i));
}
TimeSeries series2 = new TimeSeries("Line2");
for( int i = 0; i < veriSayisi; i++)
{
series2.add(zamanDiyagrami.get(i), valuesY.get(i));
}
TimeSeries series3 = new TimeSeries("Line3");
for( int i = 0; i < veriSayisi; i++)
{
series3.add(zamanDiyagrami.get(i), valuesZ.get(i));
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(series2);
dataset.addSeries(series3);
series.setTitle("X Coor");
series2.setTitle("Y Coor");
series3.setTitle("Z Coor");
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
XYSeriesRenderer renderer2 = new XYSeriesRenderer();
XYSeriesRenderer renderer3 = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(renderer2);
mRenderer.addSeriesRenderer(renderer3);
renderer.setColor(Color.GREEN);
renderer.setPointStyle(PointStyle.DIAMOND);
renderer2.setColor(Color.BLUE);
renderer2.setPointStyle(PointStyle.DIAMOND);
renderer3.setColor(Color.RED);
renderer3.setPointStyle(PointStyle.DIAMOND);
return ChartFactory.getLineChartIntent(context, dataset, mRenderer, "Koordinatlar");
}
public void onDialogPositiveClick(DialogFragment dialog) {
EditText et=(EditText)dialog.getDialog().findViewById(R.id.editText1);
dosyaAdi=et.getText().toString();
dosyayaYaz();
}
public void onDialogNegativeClick(DialogFragment dialog) {
dialog.dismiss();
sm.registerListener(this, myAccelerometer,50000);
}
}
这是 generateFeatures 类:
public class generateFeatures extends MainActivity{
private ContentValues myContentValues;
private float totalX,totalY,totalZ,averageX,averageY,averageZ,stdX,stdY,stdZ,aadX,aadY,aadZ,averageResultantAcc,maxX,maxY,maxZ;
private VeriTabani veritabani;
private SQLiteDatabase db;
private String dosyaAdi;
public generateFeatures(String dosyaAdi){
veritabani= new VeriTabani(this);
db=veritabani.getWritableDatabase();
this.dosyaAdi=dosyaAdi;
}
public void letsRollOut(){
boolean bitti=false;
Cursor firstTimeHandler=db.rawQuery("SELECT MIN(zaman) FROM Koordinatlar", null);
firstTimeHandler.moveToFirst();
long firstTime= firstTimeHandler.getLong(0);
long nextTime=firstTime+3000;
Cursor lastTimeHandler=db.rawQuery("SELECT MAX(zaman) FROM Koordinatlar", null);
lastTimeHandler.moveToFirst();
long lastTime=lastTimeHandler.getLong(0);
while(!bitti){
calculateAverage(firstTime,nextTime);
calculateStandartDev(firstTime,nextTime);
calculateAverageAbsoluteDifferance(firstTime,nextTime);
calculateAverageResultant(firstTime,nextTime);
calculateMax(firstTime,nextTime);
calculateBinnedDist(firstTime,nextTime);
firstTime=(long) (nextTime+0.000001);
nextTime=(nextTime+3000);
if(nextTime>=lastTime){
nextTime=lastTime;
calculateAverage(firstTime,nextTime);
calculateStandartDev(firstTime,nextTime);
calculateAverageAbsoluteDifferance(firstTime,nextTime);
calculateAverageResultant(firstTime,nextTime);
calculateMax(firstTime,nextTime);
calculateBinnedDist(firstTime,nextTime);
bitti=true;
}
myContentValues.put("ortX", averageX);
myContentValues.put("ortY", averageY);
myContentValues.put("ortZ", averageZ);
myContentValues.put("stdX", stdX);
myContentValues.put("stdY", stdY);
myContentValues.put("stdZ", stdZ);
myContentValues.put("aadX", aadX);
myContentValues.put("aadY", aadY);
myContentValues.put("aadZ", aadZ);
myContentValues.put("maxX", maxX);
myContentValues.put("maxY", maxY);
myContentValues.put("maxZ", maxZ);
myContentValues.put("averageResultantAcc", averageResultantAcc);
db.insertOrThrow("Features", null, myContentValues);
}
dosyayaYaz(dosyaAdi);
}
数据库类:
public class VeriTabani extends SQLiteOpenHelper {
private final static String veriTabaniAdi="dataBase1";
private static final int veriTabaniVersiyon=5;
public VeriTabani(Context context) {
super(context, veriTabaniAdi, null, veriTabaniVersiyon);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
final String tablo1,tablo2;
tablo1="CREATE TABLE Koordinatlar (_id INTEGER primary key AUTOINCREMENT,xKoor REAL,yKoor REAL,zKoor REAL,zaman INTEGER);";
db.execSQL(tablo1);
tablo2="CREATE TABLE Features (_id INTEGER primary key AUTOINCREMENT,ortX REAL,ortY REAL,ortZ REAL,stdX REAL,stdY REAL,stdZ REAL,maxX REAL,maxY REAL,maxZ REAL,aadX REAL,aadY REAL,aadZ REAL,averageResultantAcc REAL,binX1 INTEGER,binX2 INTEGER,binX3 INTEGER,binX4 INTEGER,binX5 INTEGER,binX6 INTEGER,binX7 INTEGER,binX8 INTEGER,binX9 INTEGER,binX10 INTEGER,binY1 INTEGER,binY2 INTEGER,binY3 INTEGER,binY4 INTEGER,binY5 INTEGER,binY6 INTEGER,binY7 INTEGER,binY8 INTEGER,binY9 INTEGER,binY10 INTEGER,binZ1 INTEGER,binZ2 INTEGER,binZ3 INTEGER,binZ4 INTEGER,binZ5 INTEGER,binZ6 INTEGER,binZ7 INTEGER,binZ8 INTEGER,binZ9 INTEGER,binZ10 INTEGER);";
db.execSQL(tablo2);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS Koordinatlar");
db.execSQL("DROP TABLE IF EXISTS Features");
onCreate(db);
}
}