[Q] app slow down when using sqlite database - Java for Android App Development

I am trying to create a circular buffer using sqlite. For some reason every time I instantiate my db access class, the os start skipping frames (I am using the emulator to run my code).
02-22 20:22:03.172: I/Choreographer(860): Skipped 628 frames! The application may be doing too much work on its main thread.
I do not understand what I am doing wrong. I am calling the database class from an intentService (I assume this should not slow down the main thread at all) as follows:
Code:
private SqliteLog mSqliteLog;
mSqliteLog = new SqliteLog(context);
mSqliteLog.writelogInformation("sleepMode", "ON");
I added my code at the end of this message
Code:
/**
* SqliteLog
*
*
* Base class for sqliteLog control
*
*
*/
public class SqliteLog {
// Debug log tag
private static final String tag = "SqliteLog";
// Version of database
private static final int DATABASE_VERSION = 1;
// Name of database
private static final String DATABASE_NAME = "log";
// Table of database
private static final String TABLE_NAME = "log";
public static final String ROWID_NAME = "id";
public static final String PREFERENCE_NAME = tag + "Pref";
public static final String COLUMN_LOGNUMBER = "logNumber";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_FUNCTION = "function";
public static final String COLUMN_DESCRIPTION = "description";
public static final int TABLE_SIZE = 20;
private static final String DATABASE_CREATE ="create table " + TABLE_NAME + " (" + ROWID_NAME + " integer primary key autoincrement, " +
COLUMN_LOGNUMBER + " INTEGER NOT NULL, " +
COLUMN_TIME + " TEXT NOT NULL, " +
COLUMN_FUNCTION + " TEXT NOT NULL, " +
COLUMN_DESCRIPTION + " TEXT NOT NULL " +
");";
//The context of the calling class;
private Context thisContext;
/**
* <p>Constructor for SqliteLog
* @param context :- Context of calling class
*
*/
public SqliteLog(Context context) {
Log.d(tag,"SqliteLog constructor called");
thisContext = context;
}
/**
* writelogInformation :- Writes a row into the log table
*
*/
public void writelogInformation(String functionName, String descriptionInfo) {
// Retrieve preferences
SharedPreferences SqliteLogPref = thisContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
int logNumber = SqliteLogPref.getInt("logNumber", 1);
// Open database for writing
DatabaseHelper databaseHelper = new DatabaseHelper(thisContext);
SQLiteDatabase sQLiteDatabase = databaseHelper.getWritableDatabase();
// Define the column name and data
ContentValues values = new ContentValues();
values.put(COLUMN_LOGNUMBER, logNumber);
values.put(COLUMN_TIME, getTime());
values.put(COLUMN_FUNCTION, functionName);
values.put(COLUMN_DESCRIPTION, descriptionInfo);
// Update database
sQLiteDatabase.update(TABLE_NAME, values, null, null);
// Close database
databaseHelper.close();
// Test if next database update will need to be wrapped around
logNumber = (logNumber % TABLE_SIZE) + 1;
// Store preferences
SharedPreferences.Editor editor = SqliteLogPref.edit();
editor.putInt("logNumber", logNumber);
editor.commit();
}
/**
* clearLog :- Erase all information from table
*
*/
public void clearLog() {
// Retrieve preferences
SharedPreferences SqliteLogPref = thisContext.getSharedPreferences(PREFERENCE_NAME, 0);
// Store preferences
SharedPreferences.Editor editor = SqliteLogPref.edit();
editor.putInt("logNumber", 1);
editor.commit();
// Delete all rows
DatabaseHelper databaseHelper = new DatabaseHelper(thisContext);
SQLiteDatabase sQLiteDatabase = databaseHelper.getReadableDatabase();
sQLiteDatabase.delete (TABLE_NAME, null, null);
}
/**
* readlogInformation :- Read the whole table
*
*/
public String[] readlogInformation() {
// Create string array of appropriate length
String[] returnArray;
// Retrieve preferences
SharedPreferences SqliteLogPref = thisContext.getSharedPreferences(PREFERENCE_NAME, 0);
int logNumber = SqliteLogPref.getInt("logNumber", 0);
// Open database for reading
DatabaseHelper databaseHelper = new DatabaseHelper(thisContext);
try {
SQLiteDatabase sQLiteDatabase = databaseHelper.getReadableDatabase();
// Get a cursor to the correct cell
Cursor cursor = sQLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
// Get number of rows in table
int lengthOfTable = 0;
// Move cursor to where it needs to be
if (cursor != null) {
lengthOfTable = cursor.getCount();
// If count is less than max, then we have not wrapped around yet
if(lengthOfTable < TABLE_SIZE) {
cursor.moveToFirst();
}
// Position cursor appropriately
else {
cursor.moveToPosition(logNumber-1);
}
// Create string array of appropriate length
returnArray = new String[lengthOfTable];
for(int i=1; i<=lengthOfTable; i++) {
returnArray[i] = cursor.getString(1) + "; " + cursor.getString(2) + "; " + cursor.getString(3);
}
}
else {
Log.e(tag,"Cursor null");
// Create string array of appropriate length
returnArray = new String[0];
}
} catch(SQLiteException e) {
Log.d(tag,"SQLiteException when using getReadableDatabase");
// Create string array of appropriate length
returnArray = new String[0];
}
// Close database
databaseHelper.close();
return returnArray;
}
/**
* readlogInformation :- Read the whole table
*
*/
public String getTime() {
// Create a new time object
Time currentTime = new Time(Time.getCurrentTimezone());
// Get current time
currentTime.setToNow();
return currentTime.toString();
}
/**
* DatabaseHelper
*
*
* Class to help control database
*
*
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
/**
* <p>Constructor for DatabaseHelper
* @param context :- Context of calling class<p>
*
*/
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(tag,"DatabaseHelper constructor called");
}
/**
* <p>onCreate
* @param db :- Pass an sqlite object
*
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(tag,"onCreate called");
// Create database
db.execSQL(DATABASE_CREATE);
// Insert a new row
ContentValues values = new ContentValues();
// Create a certain number of rows
for(int i=1; i<=TABLE_SIZE; i++) {
values.clear();
values.put(COLUMN_LOGNUMBER, i);
values.put(COLUMN_FUNCTION, "empty");
values.put(COLUMN_DESCRIPTION, "empty");
db.insert(TABLE_NAME, "null", values);
}
Log.d(tag,"database created");
}
/**
* <p>onUpgrade
* @param db :- Pass an sqlite object
* @param oldVersion :- Old version of table
* @param newVersion :- New version of table
*
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(tag,"onUpgrade called");
// Not used, but you could upgrade the database with ALTER
// Scripts
}
}
}
I have been trying to figure this out for a while now. I would appreciate any insight, Amish

Related

[Q] SQLite Force Close - first app

Hey everyone,
I'm trying to get started with SQLite. My app keeps force closing on this activity:
Code:
public class ViewActivity extends Activity {
private TextView company;
private BillMeDB dh;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all);
company = (TextView) findViewById(R.id.Company1);
BillMeDB db = new BillMeDB(this);
db.open();
long id;
id = db.insertEntry("Power", "AEP", "item", "2010.9.15", "w2", "2010.9.24", "2011.1.1", 75.77);
id = db.insertEntry("Cell Phone", "Verizon", "item", "2010.9.15", "w2", "2010.9.24", "2011.1.1", 185.45);
Cursor c = db.getEntry(1);
if (c.moveToFirst())
company.setText(c.getString(1));
db.close();
// Cursor c = BillMeLoad.database.fetchAllEntries();
company.setText(this.dh.getEntry(0).toString());
}
}
I can't figure out why though. It blows up(I think) when it starts creating a DB. Here's my DB file - I have no idea where I've gone wrong, but apparently something isn't right. Can someone give me a hand?
My DB File:
Code:
package com.caleb.billme;
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 BillMeDB {
public static final String KEY_BILLNAME = "billname";
public static final String KEY_COMPANY = "company";
public static final String KEY_ROWID = "_id";
public static final String KEY_ITEM = "item";
public static final String KEY_DUEDATE = "duedate";
public static final String KEY_REMFREQ = "remfreq";
public static final String KEY_REMDATE = "remdate";
public static final String KEY_ENDDATE = "enddate";
public static final String KEY_DUEAMNT = "dueamnt";
private static final String TAG = "BillMeDB";
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
private static final String DATABASE_CREATE =
"CREATE TABLE BillTable (_id integer primary key autoincrement, "
+ "billname text not null, company text not null, item text not null, " +
"duedate text not null, remfreq text not null, " +
"remdate text not null, enddate text not null, dueamnt double not null)";
private static final String DATABASE_NAME = "Data";
private static final String DATABASE_TABLE = "BillTable";
private static final int DATABASE_VERSION = 2;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
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 BillTable");
onCreate(db);
}
}
public BillMeDB(Context ctx) {
mCtx = ctx;
}
public BillMeDB open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public long insertEntry(String billname, String company, String item, String duedate, String remfreq, String remdate, String enddate, double dueamnt ) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_BILLNAME, billname);
initialValues.put(KEY_COMPANY, company);
initialValues.put(KEY_ITEM, item);
initialValues.put(KEY_DUEDATE, duedate);
initialValues.put(KEY_REMFREQ, remfreq);
initialValues.put(KEY_REMDATE, remdate);
initialValues.put(KEY_ENDDATE, enddate);
initialValues.put(KEY_DUEAMNT, dueamnt);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteAllEntries() {
return db.delete(DATABASE_TABLE, null, null) > 0;
}
public boolean deleteEntry(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor getAllEntries() {
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_BILLNAME,
KEY_COMPANY, KEY_ITEM,
KEY_DUEDATE, KEY_REMFREQ,
KEY_REMDATE, KEY_ENDDATE,
KEY_DUEAMNT},
null, null, null, null, null);
}
public Cursor getEntry(long rowId) throws SQLException{
Cursor c = db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_BILLNAME }, KEY_ROWID + "=" + rowId,
null, null, null, null);
if (c != null)
c.moveToFirst();
return c;
}
public boolean updateEntry(long rowId, String billname, String company, String item,
String duedate, String remfreq, String remdate, String enddate, double dueamnt) {
ContentValues args = new ContentValues();
args.put(KEY_BILLNAME, billname);
args.put(KEY_COMPANY, company);
args.put(KEY_ITEM, item);
args.put(KEY_DUEDATE, duedate);
args.put(KEY_REMFREQ, remfreq);
args.put(KEY_REMDATE, remdate);
args.put(KEY_ENDDATE, enddate);
args.put(KEY_DUEAMNT, dueamnt);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
in BillMeDB.java change
Code:
public BillMeDB(Context ctx) {
mCtx = ctx;
}
to
Code:
public BillMeDB(Context ctx) {
mCtx = ctx;
DBHelper = new DatabaseHelper(mCtx);
}
also in ViewActivity.java
Code:
company.setText(this.dh.getEntry(0).toString());
i guess you are trying to display both the KEY_ROWID and KEY_BILLNAME but i think you can't treat a cursor like that. you must first use getEntry(rowId) to get the cursor and then use getString(columnIndex) like you did with getEntry(1). maybe something like
(you must do this before closing the db)
Code:
c = db.getEntry(2);
if (c.moveToFirst())
company.setText(c.getString(0) + "\t" + c.getString(1));

[Q] My App use API of Google Maps but the map is slow

Hello Boys,
I am a new Android developer and I'm developing an app with the API of Google Maps.
Into an area of the map I place many markers.
The application works correctly, but the map scroolling and the map zoom isn't quick, everything goes slow.
The marker that I have included in the map is in the "png" format image, and his weighs is approximately 600 bytes.
it is possible that many marker object cause low map scrool?
this is the code of my APP:
Code:
plublic class IDC extends MapActivity {
private LocationManager locationManager;
private LocationListener locationListener;
private MapController mc;
private MapView mapView;
private String myPosition;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String errore="";
myPosition="";
try{
mapView = (MapView) findViewById(R.id.mapview);
mc = mapView.getController();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
//getMyLocation();
MyDBHelper myDB = new MyDBHelper(IDS.this);
Cursor cursor= myDB.query(new String[] { "x", "y", "y2", "w", "k", "latitude", "longitude"});
//Log.i("NOMI", "TOT. NOMI"+cursor.getCount());
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mm_20_blue);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable,IDS.this);
List<Address> address = new ArrayList<Address>();
Log.i("TOT TUPLE", " = "+cursor.getCount());
while(cursor.moveToNext()){
String s= cursor.getString(0);
errore=s;
String nome[]=s.split("-");
// Log.i("Pos Colonna NOME", ""+cursor.getColumnIndex("nome"));
// Log.i("Pos. in Colonna", ""+cursor.getString(0));
//address.addAll(gc.getFromLocationName(nome[1], 1));
//Address a= address.get(address.size()-1);
String la=cursor.getString(5);
String lo=cursor.getString(6);
double latitude= Double.parseDouble(la);
double longitude= Double.parseDouble(lo);
int lan= (int)(latitude*1E6);
int lon= (int)(longitude*1E6);
GeoPoint point = new GeoPoint(lan, lon);
String tel1=cursor.getString(1);
String tel2=cursor.getString(2);
String mail=cursor.getString(4);
String web=cursor.getString(3);
String info[]= {tel1,tel2,nome[1],web,mail};
MyOverlayItem overlayitem = new MyOverlayItem(point, "Hello", nome[0], info);
//mc.animateTo(point);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
mapView.setBuiltInZoomControls(true);
mc.setZoom(6);
}catch (Exception e) {
e.printStackTrace();
}
}
}
Code:
public class MyItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
private CustomizeDialog customizeDialog;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public MyItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
protected boolean onTap(int index)
MyOverlayItem item = (MyOverlayItem) mOverlays.get(index);
customizeDialog = new CustomizeDialog(mContext);
customizeDialog.setPersonalText(item.getSnippet());
String []info= item.getInfo();
customizeDialog.setT1(info[0]);
customizeDialog.setT2(info[1]);
customizeDialog.setA(info[2]);
customizeDialog.setW(info[3]);
customizeDialog.setM(info[4]);
customizeDialog.show();
return true;
}
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
}
what is the problem??....PLEASE, HELP ME!!

More secure encryption class using salt

Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Thanks for sharing, it's quite usefull ! I will include it to my project
Jonny said:
Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
Thanks
Gesendet von meinem LG-D855 mit Tapatalk

WidgetHost Activity to Fragment

I am trying to convert a WidgetHostActivity to Fragment but i get an error when i am trying to open WidgetManager. Here is the convert i have done so far (without OnStart and OnStop)...
Code:
public class FragmentBlue extends Fragment implements OnLongClickListener
{
static final String TAG = "FragmentBlue";
public static final int RESULT_OK = -1;
public static final int RESULT_CANCELED = 0;
AppWidgetManager mAppWidgetManager;
AppWidgetHost mAppWidgetHost;
ViewGroup mainlayout;
TextView text;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
mainlayout = (ViewGroup) view.findViewById(R.id.main_layout);
text = (TextView)view.findViewById(R.id.tvtext);
mainlayout.setOnLongClickListener(this);
mAppWidgetManager = AppWidgetManager.getInstance(getActivity());
mAppWidgetHost = new AppWidgetHost(getActivity(), R.id.APPWIDGET_HOST_ID);
return view;
}
/**
* Launches the menu to select the widget. The selected widget will be on
* the result of the activity.
*/
void selectWidget() {
text.setText(null);
int appWidgetId = this.mAppWidgetHost.allocateAppWidgetId();
Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
addEmptyData(pickIntent);
startActivityForResult(pickIntent, R.id.REQUEST_PICK_APPWIDGET);
}
/**
* This avoids a bug in the com.android.settings.AppWidgetPickActivity,
* which is used to select widgets. This just adds empty extras to the
* intent, avoiding the bug.
*
*
*/
void addEmptyData(Intent pickIntent) {
ArrayList<AppWidgetProviderInfo> customInfo = new ArrayList<AppWidgetProviderInfo>();
pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
}
/**
* If the user has selected an widget, the result will be in the 'data' when
* this function is called.
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == R.id.REQUEST_PICK_APPWIDGET) {
configureWidget(data);
} else if (requestCode == R.id.REQUEST_CREATE_APPWIDGET) {
createWidget(data);
}
} else if (resultCode == RESULT_CANCELED && data != null) {
int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
if (appWidgetId != -1) {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}
}
/**
* Checks if the widget needs any configuration. If it needs, launches the
* configuration activity.
*/
private void configureWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (appWidgetInfo.configure != null) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidgetInfo.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResult(intent, R.id.REQUEST_CREATE_APPWIDGET);
} else {
createWidget(data);
}
}
/**
* Creates the widget and adds to our view layout.
*/
public void createWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
AppWidgetHostView hostView = mAppWidgetHost.createView(getActivity(), appWidgetId, appWidgetInfo);
hostView.setAppWidget(appWidgetId, appWidgetInfo);
mainlayout.addView(hostView);
Log.i(TAG, "The widget size is: " + appWidgetInfo.minWidth + "*" + appWidgetInfo.minHeight);
}
I think the problem is into startActivityForResult(pickIntent, R.id.REQUEST_PICK_APPWIDGET); cause when i change R.id.REQUEST_PICK_APPWIDGET to a number (e.g. 1) WidgetManager opens and when i choose an installed widget it does nothing (just closing the window). I hope it is understandable.

[Q] How to set multiple alarm with sqlite

Hey devs I am working on a project for which I need to set multiple alarms on different days I am really confused on how to set the values of those alarms in sqlite and then retrieve them and make the alarm fire . Please help me on this ...... i cant think it logically also :crying:
my mainActivity contains a simple switch button when the user turns it on it fires the alarm
here is my code....
// Setting values to database!
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
I need idea on this part how to save the time for the alarms
Code:
// Setting values to database!
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
DatabaseHandler alarms = new DatabaseHandler(MainActivity.this);
alarms.open();
alarms.createAlarm(month, day, hour, minute);
alarms.close();
// Getting values from database!
DatabaseHandler alarmsGet = new DatabaseHandler(this);
alarmsGet.open();
String monthData = alarmsGet.getData();
alarmsGet.close();
// setting Time!
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 5);
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_MONTH, 28);
cal.set(Calendar.HOUR_OF_DAY, 15);
cal.set(Calendar.MINUTE, 55);
cal.set(Calendar.SECOND, 0);
context = MainActivity.this;
Intent intentAlarm = new Intent(context, AlarmReciver.class);
pendingIntent = PendingIntent.getBroadcast(context, 111, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pendingIntent);
DatabaseHandler
Code:
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler {
private static final String DATABASE_NAME = "alarmDatabase";
private static final String DATABASE_TABLE = "alarms";
private static final int DATABASE_VERSION = 1;
public static final String KEY_ROWID = "_id";
public static final String KEY_MONTH = "_month";
public static final String KEY_DAY = "_day";
public static final String KEY_HOUR = "_hour";
public static final String KEY_MINUTE = "_minute";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
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("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTO INCREMENT, " + KEY_MONTH
+ " INTEGER, " + KEY_DAY + " INTEGER, " + KEY_HOUR
+ " INTEGER, " + KEY_MINUTE + " INTEGER);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseHandler(Context c) {
ourContext = c;
}
public DatabaseHandler open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createAlarm(int month, int day, int hour, int minute) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
values.put(KEY_MONTH, month);
values.put(KEY_DAY, day);
values.put(KEY_HOUR, hour);
values.put(KEY_MINUTE, minute);
return ourDatabase.insert(DATABASE_TABLE, null, values);
}
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_MONTH, KEY_DAY,
KEY_HOUR, KEY_MINUTE };
return null;
}
}

Categories

Resources