lundi 26 janvier 2015

Why i can't do "select" on my database?

I've been making apk for registration charging times and i've got a problem with selecting the row to calculate time of charging. I've no idea how to make it work. Are there any specific methods needed to be able to select data from database in BroadcastReceiver ?


The problem is in method "czas()" when I call method rawquery.


There is my code :



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

public class ChargingOnReceiver extends BroadcastReceiver {
private String data;
private SQLiteDatabase db;
private Context coc;
private int ida = 5;

@Override
public void onReceive(Context context, Intent intent) {

db = context.openOrCreateDatabase("dane.db",0, null);

db.execSQL("CREATE TABLE IF NOT EXISTS Ladowanie(_id INTEGER PRIMARY KEY AUTOINCREMENT, data_od DATETIME, data_do DATETIME, czas long);");
coc = context;
Calendar cal = Calendar.getInstance();
data = cal.get(Calendar.YEAR) + "-" + cal.get(Calendar.MONTH) + "-"
+ cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY)
+ ":" + cal.get(Calendar.MINUTE) ;

if(intent.getAction().equals(Intent.ACTION_POWER_CONNECTED))
{
db.execSQL("insert into ladowanie (data_od,data_do,czas) values (datetime('now'),date('now'),0);");
notyfikujLadowanie(context);

}

if(intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED))
{



db.execSQL("update ladowanie set data_do=datetime('now') where data_od like (select max(data_od) from ladowanie);");
db.execSQL("update ladowanie set czas="+ czas() +" where data_od like (select max(data_od) from ladowanie);");

notyfikujRozladuj(context);

}

}


public long czas()
{
Cursor cursor = db.rawQuery("select * from ladowanie where data_od like (select max(data_od) from ladowanie);", null);

// cursor.moveToFirst();

Date startDate = null,endDate = null;
long diffInMs =0,diffInSec=0;

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



try {
startDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("data_od")));
} catch (ParseException e1) {

e1.printStackTrace();
}
try {
endDate = (Date) outputFormat.parse(cursor.getString(cursor.getColumnIndex("data_do")));
} catch (ParseException e) {

e.printStackTrace();
}
if(startDate != null && endDate != null){
diffInMs = endDate.getTime() - startDate.getTime();
diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
}

cursor.close();
return 0;

}

Aucun commentaire:

Enregistrer un commentaire