SQlite Method to Export Single cell value string to a variable - java

I have code that imports data with sms! And now I need one method to export this data from the database to a variable on the IncomingSMSReceiver (I will probably make one method for each field); Can I export a single cell value to a variable?
E.g I tried to do it for the onoma column but I don't know what database method I should use and what sql, and how to export it.
DatabaseHelper.java
package toulios.ptixiakh.toulios;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Toulios.db";
public static final String TABLE_NAME="Foitites_table";
public static final String Col_AM="AM";
public static final String Col_ONOMA="ONOMA";
public static final String Col_EPITHETO="EPITHETO";
public static final String Col_EXAMINO="EXAMINO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME+"(AM INTEGER PRIMARY KEY,ONOMA TEXT,EPITHETO TEXT, EXAMINO INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}
public boolean eisagoghfititi(String am,String onoma,String epitheto,String examino)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_AM,am);
contentValues.put(Col_ONOMA,onoma);
contentValues.put(Col_EPITHETO,epitheto);
contentValues.put(Col_EXAMINO,examino);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public String exagwgh_onoma(String am){
String str="";
final String SQL_SELECT_QUERY = "SELECT "+DatabaseHelper.Col_ONOMA+" FROM "+DatabaseHelper.TABLE_NAME+" WHERE "+DatabaseHelper.Col_AM+" = "+am;
DatabaseHelper queryDbHelperObj = new DatabaseHelper(this);
SQLiteDatabase sqLiteDatabase = queryDbHelperObj.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(SQL_SELECT_QUERY,null);
if (cursor.moveToFirst()) {
str = cursor.getString(cursor.getColumnIndex("content"));
}
cursor.close();
return str;
}
}
IncomingSMSReceiver.java
public class IncomingSMSReceiver extends BroadcastReceiver{
private static final String SMS_RECEIVED ="android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context _context, Intent _intent) {
if (_intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = _intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage
.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message : messages)
{
String strPhoneNo = message.getOriginatingAddress();
String msg = message.getMessageBody();
if (msg.startsWith("01"))
{
try {
final String[] temaxismeno_sms = msg.split(":");
DatabaseHelper dbHelper = new DatabaseHelper(_context.getApplicationContext());
dbHelper.eisagoghfititi(temaxismeno_sms[1],temaxismeno_sms[2],temaxismeno_sms[3],temaxismeno_sms[4]);
Toast.makeText(_context, "Egine eisagwgh fititi!!", Toast.LENGTH_LONG).show();
String message1 = "H Eisagwgh egine sthn vash.";// minima pou tha stalthei
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(strPhoneNo, null, message1, null, null);
Toast.makeText(_context, "O fititis idopiithike", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(_context, "SMS failed, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if (msg.startsWith("02"))
{
final String[] temaxismeno_sms = msg.split(":");
String apotelesma;
DatabaseHelper dbHelper = new DatabaseHelper(_context.getApplicationContext());
apotelesma = dbHelper.exagwgh_onoma(temaxismeno_sms[1]);
String message2 = "To onoma tou am pou epilexate einai "+apotelesma;
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(strPhoneNo, null, message2, null, null);
}
}
}
}
}
}

You can achieve that in the below way --
public static final String SQL_SELECT_QUERY = "SELECT COLUMN1 FROM "+AndroidOpenDbHelper.TEST_TABLE;
AndroidOpenDbHelper queryDbHelperObj = new AndroidOpenDbHelper(this);
SQLiteDatabase sqLiteDatabase = queryDbHelperObj.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(SQL_SELECT_QUERY,null);
if(cursor != null)
{
if(cursor.moveToFirst())
{
do
{
String ColumnVal = cursor.getString(cursor.getColumnIndex("Column1"));
}while(cursor.moveToNext());
}
}
EDITED:
"SELECT "+AndroidOpenDbHelper.ONOMA+" FROM "+AndroidOpenDbHelper.TEST_TABLE+" WHERE "+AndroidOpenDbHelper._ID+" = "+am;
Hope this helps!

Related

Not able to match or compare two dates

I am not able to match or compare two dates one from Database and second is current date.I have five checkboxes. When 1st user checkes a checkbox and insert its value by clicking the save button. 2nd time when he check 2 or more checkboxes Now here I want to update last record by date. I set date as primary key in that table.
NamazCounterActivity
package com.example.shakeelmughal.assanislam;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NamazCounterActivity extends AppCompatActivity {
DatabaseHelper mydb;
CheckBox cb1,cb2,cb3,cb4,cb5;
Button B1,B2,B3;
TextView tv;
int vcb1=0,vcb2=0,vcb3=0,vcb4=0,vcb5=0;
Date date = new Date();
String a="1";
public static final String SHARED_PREF = "sharedPrefs";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";
public static final String CHECK3 = "check3";
public static final String CHECK4 = "check4";
public static final String CHECK5 = "check5";
private Boolean chb1,chb2,chb3,chb4,chb5;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namaz_counter);
try {
mydb = new DatabaseHelper(this);
} catch (IOException e) {
e.printStackTrace();
}
tv = findViewById(R.id.textView24);
cb1 = findViewById(R.id.namaz1);
cb2 = findViewById(R.id.namaz2);
cb3 = findViewById(R.id.namaz3);
cb4 = findViewById(R.id.namaz4);
cb5 = findViewById(R.id.namaz5);
B1 = findViewById(R.id.result);
B2 = findViewById(R.id.dateee);
B3 = findViewById(R.id.sumr);
c_date();
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData1();
if (c.moveToFirst())
{
if(mydb.date().equals(c.getString(0)))
{
Updateingdata();
}
else
{
InsertingData();
}
}
else
{
InsertingData();
}
SaveData();
}
});
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData();
if(c.getCount() == 0)
{
Toast.makeText(NamazCounterActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
StringBuffer stringBuffer = new StringBuffer();
while (c.moveToNext())
{
stringBuffer.append("ID: " +c.getString(0 )+"\n");
stringBuffer.append("Fajar: " +c.getString(1)+"\n");
stringBuffer.append("Zohr: " +c.getString(2)+"\n");
stringBuffer.append("Asr: " +c.getString(3)+"\n");
stringBuffer.append("Magrib: " +c.getString(4)+"\n" );
stringBuffer.append("Isha: " +c.getString(5)+"\n");
}
showData("Data",stringBuffer.toString());
}
});
//home button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
//functions for save old values
loadData();
updateViews();
}
//function for going back to previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
public void InsertingData()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean result = mydb.InsertData(date().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(result == true)
{
Toast.makeText(NamazCounterActivity.this, "Prayer Saved",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(NamazCounterActivity.this, "Some Error", Toast.LENGTH_LONG).show();
}
}
public void Updateingdata()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean res = mydb.UpdateData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(res == true)
{
Toast.makeText(NamazCounterActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(NamazCounterActivity.this,"Data Not Updated",Toast.LENGTH_SHORT).show();
}
}
//for date ()
public void c_date() {
date.setTime(System.currentTimeMillis()); //set to current time
B2.setText(date.toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEEEEEE, MMM dd, yyyy");
B2.setText(dateFormat.format(date));
}
public void SaveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(CHECK1, cb1.isChecked());
editor.putBoolean(CHECK2, cb2.isChecked());
editor.putBoolean(CHECK3, cb3.isChecked());
editor.putBoolean(CHECK4, cb4.isChecked());
editor.putBoolean(CHECK5, cb5.isChecked());
editor.apply();
}
public void loadData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
chb1 = sharedPreferences.getBoolean(CHECK1, false);
chb2 = sharedPreferences.getBoolean(CHECK2, false);
chb3 = sharedPreferences.getBoolean(CHECK3, false);
chb4 = sharedPreferences.getBoolean(CHECK4, false);
chb5 = sharedPreferences.getBoolean(CHECK5, false);
}
public void updateViews()
{
cb1.setChecked(chb1);
cb2.setChecked(chb2);
cb3.setChecked(chb3);
cb4.setChecked(chb4);
cb5.setChecked(chb5);
}
public void showData(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public java.sql.Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
}
DatabaseHelper.java
package com.example.shakeelmughal.assanislam;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import static android.content.ContentValues.TAG;
import static java.time.LocalTime.now;
/**
* Created by Shakeel Mughal on 5/30/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public Context context;
private SQLiteDatabase db2;
public AssetManager mngr;
SQLiteDatabase db;
private Resources mResources;
private InputStream inputstream = null;
private final static String Dbname = "NamazCounter.db";
private final static String Tbname = "DailyWork";
private final static String Tbname2 = "items";
private final static String Col_1 = "ID";
private final static String Col_2 = "Fajar";
private final static String Col_3 = "Zohr";
private final static String Col_4 = "Asr";
private final static String Col_5 = "Magrib";
private final static String Col_6 = "Isha";
private final static String NCol_1 = "date_for";
private final static String NCol_2 = "fajr";
private final static String NCol_3 = "shurooq";
private final static String NCol_4 = "dhuhr";
private final static String NCol_5 = "asr";
private final static String NCol_6 = "maghrib";
private final static String NCol_7 = "isha";
public DatabaseHelper(Context context) throws IOException {
super(context, Dbname, null, 1);
this.context = context;
mResources = context.getResources();
mngr = context.getAssets();
db = this.getWritableDatabase();
db = this.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
//namaz counter
final String Table1 = "CREATE TABLE "+Tbname+"(ID PRIMARY KEY TEXT, Fajar TEXT, Zohr TEXT, Asr TEXT, Magrib TEXT, Isha TEXT)";
//for namaz timing
final String Table2 = "CREATE TABLE "+Tbname2+"(date_for TEXT, fajr TEXT, shurooq TEXT, dhuhr TEXT, asr TEXT, maghrib TEXT,isha TEXT)";
db.execSQL(Table1);
db.execSQL(Table2);
Log.d(TAG, "DataBase Created");
try {
readDataToDb(db);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ Tbname);
db.execSQL("DROP TABLE IF EXISTS "+ Tbname2);
onCreate(db);
}
public void openDatabase() {
String dbPath = context.getDatabasePath(Dbname).getPath();
if (db != null) {
db.isOpen();
return;
}
db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (db != null) {
db.close();
}
}
//Json fun
private String readJsonDataFromFile() throws IOException {
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputstream = mngr.open("NamazTiming.json");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputstream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputstream != null) {
inputstream.close();
}
}
return new String(builder);
}
public void readDataToDb(SQLiteDatabase db) throws IOException, JSONException {
final String date = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
String jsonDataString = readJsonDataFromFile();
JSONArray jsonfileJSONArray = new JSONArray(jsonDataString);
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String dateid;
String nmz1;
String nmz2;
String nmz3;
String nmz4;
String nmz5;
String nmz6;
JSONObject jsonfileObject = jsonfileJSONArray.getJSONObject(i);
dateid = jsonfileObject.getString(date);
nmz1 = jsonfileObject.getString(namaz1);
nmz2 = jsonfileObject.getString(namaz2);
nmz3 = jsonfileObject.getString(namaz3);
nmz4 = jsonfileObject.getString(namaz4);
nmz5 = jsonfileObject.getString(namaz5);
nmz6 = jsonfileObject.getString(namaz6);
ContentValues jsonfilevalues = new ContentValues();
jsonfilevalues.put(NCol_1, dateid);
jsonfilevalues.put(NCol_2, nmz1);
jsonfilevalues.put(NCol_3, nmz2);
jsonfilevalues.put(NCol_4, nmz3);
jsonfilevalues.put(NCol_5, nmz4);
jsonfilevalues.put(NCol_6, nmz5);
jsonfilevalues.put(NCol_7, nmz6);
long rowID= db.insert(Tbname2, null, jsonfilevalues);
if(rowID>-1){
int catid=0;
Cursor cursor = db.rawQuery("SELECT "+ NCol_1 + " FROM "+ Tbname2+" where "+ NCol_1 + "='" + now() + "'" , null);
cursor.moveToFirst();
if (cursor.moveToNext()) {
catid = (cursor.getInt(0));
}
cursor.close();
JSONArray jsonitemsarray= (JSONArray) jsonfileObject.get("itemsList");
readitem(db,jsonitemsarray);
}
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void readitem(SQLiteDatabase db,JSONArray jsonfileJSONArray) throws IOException, JSONException {
final String date1 = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String Did;
String nmzz1 ;
String nmzz2 ;
String nmzz3 ;
String nmzz4 ;
String nmzz5 ;
String nmzz6 ;
JSONObject jsonfileObject1 = jsonfileJSONArray.getJSONObject(i);
Did = jsonfileObject1.getString(date1);
nmzz1 = jsonfileObject1.getString(namaz1);
nmzz2 = jsonfileObject1.getString(namaz2);
nmzz3 = jsonfileObject1.getString(namaz3);
nmzz4 = jsonfileObject1.getString(namaz4);
nmzz5 = jsonfileObject1.getString(namaz5);
nmzz6 = jsonfileObject1.getString(namaz6);
ContentValues jsonfilevalues1 = new ContentValues();
jsonfilevalues1.put(NCol_1, Did);
jsonfilevalues1.put(NCol_2, nmzz1);
jsonfilevalues1.put(NCol_3, nmzz2);
jsonfilevalues1.put(NCol_4, nmzz3);
jsonfilevalues1.put(NCol_5, nmzz4);
jsonfilevalues1.put(NCol_6, nmzz5);
jsonfilevalues1.put(NCol_7, nmzz6);
db.insert(Tbname2, null, jsonfilevalues1);
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues1);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
//inserting for counter
public boolean InsertData(String d_date, String Fjr, String zhr, String assr, String mgrb, String isa)
{
SQLiteDatabase db = this.getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,d_date);
contentValues.put(Col_2,Fjr);
contentValues.put(Col_3,zhr);
contentValues.put(Col_4,assr);
contentValues.put(Col_5,mgrb);
contentValues.put(Col_6,isa);
long success = db.insert(Tbname,null,contentValues);
if(success == -1)
{
return false;
}
else
{
return true;
}
}
public boolean UpdateData(String id,String n1, String n2, String n3,String n4,String n5)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,id);
contentValues.put(Col_2,n1);
contentValues.put(Col_3,n2);
contentValues.put(Col_4,n3);
contentValues.put(Col_3,n4);
contentValues.put(Col_4,n5);
db.update(Tbname,contentValues,"ID = ?", new String[]{id});
return true;
}
public Cursor getAllDataForNamaz()
{
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname2 + " WHERE date_for = "+ date(),null);
closeDatabase();
return cs;
}
public Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname,null);
return cs;
}
public Cursor getAllData1()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT ID FROM "+ Tbname,null);
return cs;
}
}
I advise you to convert all your date into timestamp and use only timestamp for comparaison (you can also save date as timestamp in your database) :
System.currentTimeMillis() // Current timestamp
date.time // timestamp of the SQL Date object
if (timestamp1 > timestamp2) {
// timestamp1 after timestamp2
} else if (timestamp1 < timestamp2) {
// timestamp1 before timestamp2
} else {
// timestamp1 == timestamp2
}
Try this code first convert data into this format..."dd/mm/yyyy"
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
// define log
}

Cant Find Database file in Eclipse for Android

I have been doing an android database application project recently.When i tried to execute. I cant find the folder 'databases' in the file explorer of the DDMS. I checked the following path /data/data/packagename/databases,but there i could not find databases folder and my database file.
I have attached the code for database helper class
please help me if there is any error that is preventing me from creating the database or is it wrong with my eclipse. Because even some of my existing projects also don't show up with the databases folder inside them.
DBclass.java:
package pack.andyxdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBclass {
public static final String KEY_TIMESTAMP = "Timestamp";
public static final String KEY_UNIQUEID = "UniqueID";
public static final String KEY_DEVICETYPE = "Devicetype";
public static final String KEY_RSSI = "RSSI";
private static final String DATABASE_NAME = "DannyZ.db";
private static final String DATABASE_TABLE = "Data";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;
private static final String USER_MASTER_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
+ KEY_TIMESTAMP + " INTEGER ,"
+ KEY_UNIQUEID + " INTEGER, " + KEY_DEVICETYPE + " TEXT, " + KEY_RSSI + " INTEGER PRIMARY KEY )";
//CREATE TABLE `DannyZ` (
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_MASTER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if DATABASE VERSION changes
// Drop old tables and call super.onCreate()
}
}
public DBclass(Context c) {
ourContext = c;
dbh = new DbHelper(ourContext);
}
public DBclass open() throws SQLException {
odb = dbh.getWritableDatabase();
return this;
}
public void close() {
dbh.close();
}
public long insertrecord(int timestamp, int uniqueID,String Device, int RSSI) throws SQLException{
// Log.d("", col1);
// Log.d("", col2);
ContentValues IV = new ContentValues();
IV.put(KEY_TIMESTAMP, timestamp);
IV.put(KEY_UNIQUEID, uniqueID );
IV.put(KEY_DEVICETYPE, Device != "");
IV.put(KEY_RSSI, RSSI );
return odb.insert(DATABASE_TABLE, null, IV);
// returns a number >0 if inserting data is successful
}
public void updateRow(long rowID, String col1, String col2,String col3,String col4) {
ContentValues values = new ContentValues();
values.put(KEY_TIMESTAMP, col1);
values.put(KEY_UNIQUEID, col2);
values.put(KEY_DEVICETYPE, col3);
values.put(KEY_RSSI, col4);
try {
odb.update(DATABASE_TABLE, values, KEY_RSSI + "=" + rowID, null);
} catch (Exception e) {
}
}
public boolean delete() {
return odb.delete(DATABASE_TABLE, null, null) > 0;
}
public Cursor getAllTitles() {
// using simple SQL query
return odb.rawQuery("select * from " + DATABASE_TABLE + "ORDER BY "+KEY_RSSI, null);
}
public Cursor getallCols(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID, KEY_DEVICETYPE, KEY_RSSI }, null, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
public Cursor getColsById(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID,KEY_DEVICETYPE }, KEY_RSSI + " = " + id, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
}
also my MainActivity.java code is here. Here i try to insert the data into database by making use of submit button. When i hit submit button the app does not stay for long time and says unfortunately myapp has stopped.my curious concern has been is my database being created or not?
please do help me thanks
MainActivity:
public class MainActivity extends Activity {
private ListView list_lv;
private EditText txt1;
private EditText txt2;
private EditText txt3;
private EditText txt4;
private Button btn1;
private Button btn2;
private DBclass db;
private ArrayList<String> collist_1;
private ArrayList<String> collist_2;
private ArrayList<String> collist_3;
private ArrayList<String> collist_4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collist_1 = new ArrayList<String>();
collist_2 = new ArrayList<String>();
collist_3 = new ArrayList<String>();
collist_4 = new ArrayList<String>();
items();
// getData();
}
private void items() {
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
txt1 = (EditText) findViewById(R.id.editText1);
txt2 = (EditText) findViewById(R.id.editText2);
txt3 = (EditText) findViewById(R.id.editText3);
txt4 = (EditText) findViewById(R.id.editText4);
// list_lv = (ListView) findViewById(R.id.dblist);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//getData();
viewData();
}
private void viewData() {
Intent i = new Intent(MainActivity.this, viewActivity.class);
startActivity(i);
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitData();
}
});
}
protected void submitData() {
int a = Integer.parseInt( txt1.getText().toString());
int b = Integer.parseInt( txt2.getText().toString());
String c = txt3.getText().toString();
int d = Integer.parseInt( txt4.getText().toString());
db = new DBclass(this);
long num = 0;
try {
db.open();
num = db.insertrecord(a, b,c,d);
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Error Duplicate value"+e,2000).show();
} finally {
//getData();
}
if (num > 0)
Toast.makeText(this, "Row number: " + num, 2000).show();
else if (num == -1)
Toast.makeText(this, "Error Duplicate value", 4000).show();
else
Toast.makeText(this, "Error while inserting", 2000).show();
}
}
Create object of helper class in your activity onCreate method for creating the database file in android app
DBclass db=new DBclass(context);
Hope this will help.

filtering data from the database using setFilterQueryProvider?

I have here my code. Data on the database are filtered by the title, how can i filter data by title or author? I think it is on these lines of codes on Catalogue.java:
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
Here are my codes:
Catalogue.java
package com.cvsu.catalogue.db;
import com.cvsu.catalogue.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
#SuppressLint("NewApi")
public class Catalogue extends Activity {
private CollectionsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
public final static String TITLE_EXTRA = "com.cvsu.catalogue.db._TITLE";
public final static String AUTHOR_EXTRA = "com.cvsu.catalogue.db._AUTHOR";
public final static String LOCATION_EXTRA = "com.cvsu.catalogue.db._LOCATION";
public final static String CALLNUMBER_EXTRA = "com.cvsu.catalogue.db._CALLNUMBER";
public final static String PUBLISHER_EXTRA = "com.cvsu.catalogue.db._PUBLISHER";
public final static String DATEPUBLISHED_EXTRA = "com.cvsu.catalogue.db._DATEPUBLISHED";
public final static String DESCRIPTION_EXTRA = "com.cvsu.catalogue.db._DESCRIPTION";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalogue_title);
dbHelper = new CollectionsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCollections();
// The desired columns to be bound
String[] columns = new String[] {
CollectionsDbAdapter.KEY_TITLE,
CollectionsDbAdapter.KEY_AUTHOR,
CollectionsDbAdapter.KEY_LOCATION,
CollectionsDbAdapter.KEY_CALLNUMBER,
CollectionsDbAdapter.KEY_PUBLISHER,
CollectionsDbAdapter.KEY_DATEPUBLISHED,
CollectionsDbAdapter.KEY_DESCRIPTION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.txtTitle,
R.id.txtAuthor,
//R.id.location,
//R.id.callnumber,
//R.id.publisher,
//R.id.datepublished,
//R.id.description,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.book_info_title,
cursor,
columns,
to,
0);
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view,
int position, long id ) {
// Get the cursor, positioned to the corresponding row in the result set
/*Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String bookTitle =
cursor.getString(cursor.getColumnIndexOrThrow("title"));
Toast.makeText(getApplicationContext(),
bookTitle, Toast.LENGTH_SHORT).show();*/
Intent i = new Intent (CatalogueTitle.this, BookInfoPage.class);
i.putExtra(TITLE_EXTRA, String.valueOf(id));
i.putExtra(AUTHOR_EXTRA, String.valueOf(id));
i.putExtra(LOCATION_EXTRA, String.valueOf(id));
i.putExtra(CALLNUMBER_EXTRA, String.valueOf(id));
i.putExtra(PUBLISHER_EXTRA, String.valueOf(id));
i.putExtra(DATEPUBLISHED_EXTRA, String.valueOf(id));
i.putExtra(DESCRIPTION_EXTRA, String.valueOf(id));
startActivity(i);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
}
});
}
public static void main(String[] args) {
}
}
Collections.Java
package com.cvsu.catalogue.db;
public class Collections {
String title = null;
String author = null;
String location = null;
String callnumber = null;
String publisher = null;
String datepublished = null;
String description = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCallNumber() {
return callnumber;
}
public void setCallNumber(String callnumber) {
this.callnumber = callnumber;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDatePublished() {
return datepublished;
}
public void setDatePublished(String datepublished) {
this.datepublished = datepublished;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CollectionsDbAdapter.java
package com.cvsu.catalogue.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class CollectionsDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_LOCATION = "location";
public static final String KEY_CALLNUMBER = "callnumber";
public static final String KEY_PUBLISHER = "publisher";
public static final String KEY_DATEPUBLISHED = "datepublished";
public static final String KEY_DESCRIPTION = "description";
private static final String TAG = "CollectionsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryCollections";
private static final String SQLITE_TABLE = "Collections";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_TITLE + "," +
KEY_AUTHOR + "," +
KEY_LOCATION + "," +
KEY_CALLNUMBER + "," +
KEY_PUBLISHER + "," +
KEY_DATEPUBLISHED + "," +
KEY_DESCRIPTION + "," +
" UNIQUE (" + KEY_CALLNUMBER +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CollectionsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CollectionsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCollections(String title, String author,
String location, String callnumber, String publisher, String datepublished, String description) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_CALLNUMBER, callnumber);
initialValues.put(KEY_PUBLISHER, publisher);
initialValues.put(KEY_DATEPUBLISHED, datepublished);
initialValues.put(KEY_DESCRIPTION, description);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public Cursor fetchCollectionsByTitle(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_TITLE + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchCollectionsByAuthor(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_AUTHOR + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCollections() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = null;
database.openDataBase();
if(constraint!=null){
cur = database.selectDataWithConstrain(constraint.toString());
}
return cur;
}
using this constarint write a query in your Database Class and get the data required either title or author
public Cursor selectDataWithConstrain(String c) {
// TODO Auto-generated method stub
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tbl_xxx WHERE title LIKE '%"+c+"%'", null);
return cursor;
}
public Cursor fetchdatabyfilter(String inputText, String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM " + dbTable;
if (inputText == null || inputText.length() == 0 ) {
row = sqlDb.rawQuery(query, null);
} else {
query = "SELECT * FROM " + dbTable + " WHERE " + filtercolumn + " like '%" + inputText + "%' ";
row = sqlDb.rawQuery(query, null);
}
if (row != null)
{
row.moveToFirst();
}
return row;
}
mainactivity:
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchdatabyfilter(constraint.toString(),"title" );
}
});

cursor.moveToFirst seems to be skipped

I'm new to Java and just tried to make a database. I managed to make a DB and all but when I want to read the values it seems to get an error.
This is my code for my settings activity (which asks for setting values and add them in the DB on a specific ID)
public class Settings extends Activity{
Button Save;
static Switch SwitchCalculations;
public static String bool;
public static List<Integer> list_id = new ArrayList<Integer>();
public static List<String> list_idname = new ArrayList<String>();
public static List<String> list_kind = new ArrayList<String>();
public static List<String> list_value = new ArrayList<String>();
static Integer[] arr_id;
static String[] arr_idname;
static String[] arr_kind;
static String[] arr_value;
public static final String TAG = "Settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Save = (Button) findViewById(R.id.btnSave);
SwitchCalculations = (Switch) findViewById(R.id.switchCalcOnOff);
readData();
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
writeData();
//Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT).show();
readData();
Save.setText("Opgeslagen");
}
});
}
public void writeData() {
int id = 1;
String idname = "switchCalcOnOff";
String kind = "switch";
boolean val = SwitchCalculations.isChecked();
String value = new Boolean(val).toString();
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dbh.C_ID, id);
cv.put(dbh.C_IDNAME, idname);
cv.put(dbh.C_KIND, kind);
cv.put(dbh.C_VALUE, value);
if (dbh.C_ID.isEmpty() == true) {
db.insert(dbh.TABLE, null, cv);
Log.d(TAG, "Insert: Data has been saved.");
} else if (dbh.C_ID.isEmpty() == false) {
db.update(dbh.TABLE, cv, "n_id='1'", null);
Log.d(TAG, "Update: Data has been saved.");
} else {
Log.d(TAG, "gefaald");
}
db.close();
}
public void readData() {
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
List<String> list_value = new ArrayList<String>();
String[] arr_value;
list_value.clear();
Cursor cursor = db.rawQuery("SELECT " + dbh.C_VALUE + " FROM " + dbh.TABLE + ";", null);
if (cursor.moveToFirst()) {
do {
list_value.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()){
cursor.close();
}
db.close();
arr_value = new String[list_value.size()];
for (int i = 0; i < list_value.size(); i++){
arr_value[i] = list_value.get(i);
}
}
}
Then I have my dbHelper activity see below:
package com.amd.nutrixilium;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbHelper_Settings extends SQLiteOpenHelper{
private static final String TAG="dbHelper_Settings";
public static final String DB_NAME = "settings.db";
public static final int DB_VERSION = 10;
public final String TABLE = "settings";
public final String C_ID = "n_id"; // Special for id
public final String C_IDNAME = "n_idname";
public final String C_KIND = "n_kind";
public final String C_VALUE = "n_value";
Context context;
public dbHelper_Settings(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
// oncreate wordt maar 1malig uitgevoerd per user voor aanmaken van database
#Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format("create table %s (%s int primary key, %s TEXT, %s TEXT, %s TEXT)", TABLE, C_ID, C_IDNAME, C_KIND, C_VALUE);
Log.d(TAG, "onCreate sql: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE); // wist een oudere database versie
Log.d(TAG, "onUpgrate dropped table " + TABLE);
this.onCreate(db);
}
}
And the weird thing is I don't get any error messages here.
But I used Log.d(TAG, text) to check where the script is being skipped and that is at cursor.moveToFirst().
So can anyone help me with this problem?
Here, contrary to what you seem to expect, you actually check that a text constant is not empty:
if (dbh.C_ID.isEmpty() == true) {
It isn't : it always contains "n_id"
I think your intent was to find a record with that id and, depending on the result, either insert or update.
You should do just that: attempt a select via the helper, then insert or update as in the code above.
Edit:
Add to your helper something like this:
public boolean someRowsExist(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("select EXISTS ( select 1 from " + TABLE + " )", new String[] {});
cursor.moveToFirst();
boolean exists = (cursor.getInt(0) == 1);
cursor.close();
return exists;
}
And use it to check if you have any rows in the DB:
if (dbh.someRowsExist(db)) { // instead of (dbh.C_ID.isEmpty() == true) {
Looks like you're having trouble debugging your query. Android provides a handy method DatabaseUtils.dumpCursorToString() that formats the entire Cursor into a String. You can then output the dump to LogCat and see if any rows were actually skipped.

Error database not open

Hey I'm trying to insert data in the SQLite database, but everytime I try to insert the logcat shows the error. THe error ir shown on a service that gets the calllog data and insert in the DB.
Error:
02-15 17:07:51.658: ERROR/AndroidRuntime(25392): java.lang.IllegalStateException: database not open
And the error is in this line of the Service class:
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
Here is the service:
public class TheService extends Service {
private static final String TAG = "TheService";
private static final String LOG_TAG = "TheService";
private Handler handler = new Handler();
private SQLiteDatabase db;
class TheContentObserver extends ContentObserver {
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
searchInsert();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
db = DataHandlerDB.createDB(this);
registerContentObservers();
}
#Override
public void onDestroy(){
db.close();
}
#Override
public void onStart(Intent intent, int startid) {
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
int numberColumnId = cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int durationId = cursor
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int contactNameId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
int callTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/d/yyyy");
Date date = new Date();
cursor.moveToFirst();
String contactNumber = cursor.getString(numberColumnId);
String contactName = (null == cursor.getString(contactNameId) ? ""
: cursor.getString(contactNameId));
String duration = cursor.getString(durationId);
String numType = cursor.getString(numTypeId);
String callType = cursor.getString(callTypeId);
ContentValues values = new ContentValues();
values.put("contact_id", 1);
values.put("contact_name", contactName);
values.put("number_type", numType);
values.put("contact_number", contactNumber);
values.put("duration", duration);
values.put("date", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
values.put("type", callType);
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
cursor.close();
}
public void registerContentObservers() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, true,
new TheContentObserver(handler));
}
}
And here is the DataHandlerDB Class:
public class DataHandlerDB {
private static final String DATABASE_NAME = "mydb.db";
private static final int DATABASE_VERSION = 1;
protected static final String TABLE_NAME = "table1";
protected static final String TABLE_NAME_2 = "table2";
protected String TAG = "DataHandlerDB";
//create the DB
public static SQLiteDatabase createDB(Context ctx) {
OpenHelper helper = new OpenHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
helper.onOpen(db);
db.close();
return db;
}
public static class OpenHelper extends SQLiteOpenHelper {
private final Context mContext;
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String[] sql = mContext.getString(R.string.ApplicationDatabase_OnCreate).split("\n");
db.beginTransaction();
try{
execMultipleSQL(db, sql);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e("Error creating tables and debug data", e.toString());
throw e;
} finally {
db.endTransaction();
}
}
private void execMultipleSQL(SQLiteDatabase db, String[] sql) {
for(String s : sql){
if(s.trim().length() > 0){
db.execSQL(s);
}
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*Log.w("Application Database",
"Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);*/
}
#Override
public void onOpen(SQLiteDatabase db){
super.onOpen(db);
}
}
}
Don't you want this code
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
to be:
if (!db.isOpen()) {
db = getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
?
Also, in the function
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
helper and db are local variables, not class members. This means that the database that you open here is not used for anything, anywhere.

Categories

Resources