I made an app to read values from the database and send messages through the smsManager and it was perfectly fine but all of a sudden it stopped working, Anybody have any idea what could be the cause? It returns sent status but the messages are not being sent in reality. Here is the code:
package com.brs;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.telephony.SmsManager;
import android.widget.Toast;
/**
* Created by Sahil on 17-06-2015.
*/
public class Sending extends IntentService {
public static int cursor_count=0;
public Sending()
{
super("Sending");
}
SQLiteDatabase sqliteDatabase;
DatabaseHandler databasehandler;
Cursor cursor, cursor2;
protected void onHandleIntent(Intent workIntent) {
databasehandler = new DatabaseHandler(getApplicationContext());
sqliteDatabase = databasehandler.getReadableDatabase();
cursor = databasehandler.read_queue(sqliteDatabase);
cursor.moveToFirst();
System.out.println("The Vlaues for cursor : " + cursor.getCount());
//cursor_count = cursor.getCount();
cursor2 = databasehandler.read_polls(sqliteDatabase);
System.out.println("The Vlaues for cursor2 : " + cursor2.getCount());
int t = 0;
//To reach the first pending statement.
do {
String stats;
stats = cursor.getString(2);
System.out.println("The status is " + stats);
if (stats.matches("PENDING")) {
System.out.println("THE DEBUG CHECKER");
t = 1;
break;
}
} while (cursor.moveToNext());
if (t == 1)
{
do
{
String ques = "", opt1 = "", opt2 = "", opt3 = "", opt4 = "", opt5 = "", keyword = "", start_date = "", end_date = "", message = "";
int k = cursor.getInt(0);
System.out.println("The cursor index:" + k);
if (cursor2.moveToFirst())
{
do
{
int pol_id;
pol_id = cursor2.getInt(0);
if (pol_id == k)
{
ques = cursor2.getString(1);
opt1 = cursor2.getString(2);
opt2 = cursor2.getString(3);
opt3 = cursor2.getString(4);
opt4 = cursor2.getString(5);
opt5 = cursor2.getString(6);
keyword = cursor2.getString(7);
start_date = cursor2.getString(8);
end_date = cursor2.getString(9);
message = cursor2.getString(10);
break;
}
} while (cursor2.moveToNext());
}
for (int i = 0; i < 20; i++) {
int id;
String number;
String status;
id = cursor.getInt(0);
number = cursor.getString(1);
status = cursor.getString(2);
System.out.println("The id :" + id);
System.out.println("The number:" + number);
System.out.println("The status :" + status);
if (id == k) {
String sms;
if (message.matches("")) {
sms = ques + "\nA." + opt1 + "\nB." + opt2 + "\nC." + opt3 + "\nD." + opt4 + "\nE." + opt5 + "\nSTART DATE:" + start_date + "\nEND DATE:" + end_date + "\nReply in the below given format:\n" + id + " " + keyword + " (A|B|C|D|E)";
} else {
sms = message + "\nSTART DATE:" + start_date + "\nEND DATE:" + end_date + "\nReply in the below given format:\n" + id + " " + keyword + " (A|B|C|D|E)\nResponses in Invalid format would not be processed.\nSent from GOLL_POLL";
}
try {
SmsManager smsManager = SmsManager.getDefault();
PendingIntent sentPI;
String SENT = "SMS_SENT";
sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
smsManager.sendTextMessage(number, null, sms, sentPI, null);
databasehandler.update_queue(id, number, "SENT");
} catch (Exception e) {
databasehandler.update_queue(id, number, "FAIL");
System.out.println("Message sending failed");
e.printStackTrace();
}
System.out.println("The status:" + cursor.getString(2));
if (cursor.moveToNext()) {
} else {
break;
}
}
else {
break;
}
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 40000);
cursor.moveToPrevious();
} while (cursor.moveToNext());
System.out.println("The end has been reached:");
}
}
}
Related
I'm trying to loop through a string array containing numbers and parse these values into an integer collection, displaying the return value into a broadcast e.g. "A work from ---, returned value" .
I've split the string into a string array with .split(',') and attempted to loop through this array while parsing the string values to integers.
I can get a return value from the for loop if I can directly enter the index parseInt(FilterDataValues[1]) or any index indexed, but once I add i parseInt(FilterDataValues[i+1]) or parseInt(FilterDataValues[i]) I can't get a return value. The loop works fine in a simpler loop, so I'm not too sure what's going on. Please help me any help will be fine
public String sortingList(Context context)
{
String filterData = "";
StimulusDatabase td = new StimulusDatabase(context);
Cursor result = td.getAllData();
while (result.moveToNext())
{
filterData = (result.getString(23));
}
if(filterData.isEmpty())
{
return "";
}
else
{
String[] FilterDataValues = filterData.split(",");
for(int i = 0; i <= FilterDataValues.length; i++)
{
FilterOptions.add(parseInt(FilterDataValues[i+1]));
}
// for(int i = 0; i <= FilterDataValues.length; i++)
// {
// FilterOptions.add(i+1));
// }
return filterData;
}
}
Output of the entire code doesn't cause a notification to appear even after 20/30 minutes
Output when using the commented code (0,2,6 are column indexes)
A word from Martin Luther King Jr
0,2,6
The entire class is below
package com.example.MentalHealthStateManagement.Application.Notifications;
import android.app.Notification;
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.os.Build;
import android.util.Log;
import com.example.MentalHealthStateManagement.Application.Database.StimulusDatabase;
import com.example.MentalHealthStateManagement.R;
import com.example.MentalHealthStateManagement.StateHandler.CheckIn;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import androidx.core.app.NotificationManagerCompat;
import static java.lang.Integer.parseInt;
public class Trigger_Receiver extends BroadcastReceiver
{
private static final String CHANNEL_ID = "M.H.S.M daily check-in registry";
private static final String TAG = "Trigger Receiver: ";
private String[] authors;
private String sortStatement;
private List<Integer> FilterOptions = new ArrayList<>();
private int notificationID = 135;
#Override
public void onReceive(Context context, Intent intent)
{
sortStatement = sortingList(context);
authors = getAuthors(context).split("#");
String[] quotes = getQuotes(context).split("#");
int randomNum = randomPosition();
// Create an exclusive intent for the user's daily check-in
intent = new Intent(context, CheckIn.class);
// Create the TaskStack Builder and add the Main Activity, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Checks if the API Level is 26 or greater
Notification.Builder notification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notification = new Notification.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle("A word from " + authors[randomNum])
.setContentText(sortingList(context))//quotes[randomNum]
.setStyle(new Notification.BigTextStyle().bigText(sortingList(context)))
.setContentIntent(pendingIntent)
.setAutoCancel(true);
}
NotificationManagerCompat notificationManger = NotificationManagerCompat.from(context);
assert notification != null;
notificationManger.notify(notificationID, notification.build());
notificationID++;
Log.i("Trigger_Receiver", "Trigger successful");
}
//Gets the authors for the specified trigger
public String getAuthors(Context context)
{
StringBuilder authors = new StringBuilder();
StimulusDatabase td = new StimulusDatabase(context);
// List<Integer> AuthorsToBeFiltered = NumberFilterValue;
Cursor result = td.getAllData();
while (result.moveToNext())
{
authors = new StringBuilder(result.getString(2) + " " + result.getString(4) + " "
+ result.getString(6) + " " + result.getString(8) + " " +
result.getString(10) + " " + result.getString(12) + " "
+ result.getString(14) + " " + result.getString(16) + " " +
result.getString(18) + " " + result.getString(20));
}
// while (result.moveToNext())
// {
// if(!AuthorsToBeFiltered.isEmpty())
// {
// for(int i = 0; i<AuthorsToBeFiltered.size(); i++)
// {
// if(AuthorsToBeFiltered.get(i) % 2 == 0)
// {
// authors.append(result.getString(i));
// }
// }
// }
// else
// {
// authors = new StringBuilder(result.getString(2) + " " + result.getString(4) + " " + result.getString(6) + " " + result.getString(8) + " " +
// result.getString(10) + " " + result.getString(12) + " " + result.getString(14) + " " + result.getString(16) + " " +
// result.getString(18) + " " + result.getString(20));
// }
// }
return authors.toString();
}
//Gets the quotes for the specified trigger
public String getQuotes(Context context)
{
StringBuilder quotes = new StringBuilder();
StimulusDatabase td = new StimulusDatabase(context);
//List<Integer> AuthorsToBeFiltered = NumberFilterValue;
Cursor result = td.getAllData();
while (result.moveToNext())
{
quotes.append(result.getString(1)).append(" ").append(result.getString(3))
.append(" ").append(result.getString(5)).append(" ").append(result.getString(7))
.append(" ").append(result.getString(9)).append(" ").append(result.getString(11))
.append(" ").append(result.getString(13)).append(" ").append(result.getString(15))
.append(" ").append(result.getString(17)).append(" ").append(result.getString(19));
}
// while (result.moveToNext())
// {
// if(!AuthorsToBeFiltered.isEmpty())
// {
// for(int i = 0; i<AuthorsToBeFiltered.size(); i++)
// {
// if(AuthorsToBeFiltered.get(i) % 2 == 0)
// {
// quotes.append(result.getString(i-1));
// }
// }
// }
// else
// {
// quotes.append(result.getString(1)).append(" ").append(result.getString(3))
// .append(" ").append(result.getString(5)).append(" ").append(result.getString(7))
// .append(" ").append(result.getString(9)).append(" ").append(result.getString(11))
// .append(" ").append(result.getString(13)).append(" ").append(result.getString(15))
// .append(" ").append(result.getString(17)).append(" ").append(result.getString(19));
// }
// }
return quotes.toString();
}
//A random number used to gather different quotes and authors
//P.S. each quote belongs to appropriate author due to the delimiter settings preformed in the StimulusSetup class
public Integer randomPosition()
{
int randomNum = 0;
// Ensures the API level 26 or greater
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
randomNum = ThreadLocalRandom.current().nextInt(0, authors.length + 1);
}
else
{
Log.d(TAG,"Incompatible device, API lower than lollipop");
}
return randomNum;
}
public String sortingList(Context context)
{
String filterData = "";
StimulusDatabase td = new StimulusDatabase(context);
Cursor result = td.getAllData();
while (result.moveToNext())
{
filterData = (result.getString(23));
}
if(filterData.isEmpty())
{
return "";
}
else
{
String[] FilterDataValues = filterData.split(",");
for(int i = 0; i <= FilterDataValues.length; i++)
{
FilterOptions.add(parseInt(FilterDataValues[i+1]));
}
// ` Working loop
// for(int i = 0; i <= FilterDataValues.length; i++)
// {
// FilterOptions.add(i+1));
// }
return filterData;
}
}
}
Notice that in the loop, you are calling
FilterOptions.add(parseInt(FilterDataValues[i+1]));
which should fail in last interation of loop, because there will be attempt of reading value from position which does not exist in this array. I guess you could find IndexOutOfBoundException in LogCat.
This is probably the cause of why you can't get return value, as method should throw exception.
I am using android call logs in my app and I would like to determine whether the last call was an incoming or out going call. This is what I have tried so far however int type gives me an error android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 284
Cursor managedCursor = context.getContentResolver().query( CallLog.Calls.CONTENT_URI,null, null,null, android.provider.CallLog.Calls.DATE + " DESC");
int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER );
int duration1 = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
int type = Integer.parseInt(managedCursor.getString(managedCursor.getColumnIndex(CallLog.Calls.TYPE)));
Log.v("DialBroadcast Receiver", "Number is: " + type);
if( managedCursor.moveToFirst() == true ) {
String phNumber = managedCursor.getString( number );
callDuration = managedCursor.getString( duration1 );
String dir = null;
sb.append( "\nPhone Number:--- "+phNumber +" \nCall duration in sec :--- "+callDuration );
sb.append("\n----------------------------------");
Log.i("*****Call Summary******","Call Duration is:-------"+sb);
Log.v("DialBroadcast Receiver", "Number is: " + callDuration);
}
Try this
public String getLastDialledNumber() {
String[] projection = {Calls.NUMBER};
Cursor cursor = mContext.getContentResolver().query(Calls.CONTENT_URI, projection,
Calls.TYPE + "=" + Calls.OUTGOING_TYPE, null, Calls.DEFAULT_SORT_ORDER +
" LIMIT 1");
if (cursor == null) return null;
if (cursor.getCount() < 1) {
cursor.close();
return null;
}
cursor.moveToNext();
int column = cursor.getColumnIndexOrThrow(Calls.NUMBER);
String number = cursor.getString(column);
cursor.close();
return number;
}
For details
How do I access call log for android?
you are get
int type = Integer.parseInt(managedCursor.getString(managedCursor.getColumnIndex(CallLog.Calls.TYPE)));
before chek if( managedCursor.moveToFirst()){}
that's why you get exeption.
put this line inside of if or try this method
private static String getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
return stringBuffer.toString();
}
Inserting values into table using beans
public static void addGetAssessmentDetail(Context context,
GetAssessmentBean getassessmentDetail) {
DBHelper dbHelper = null;
SQLiteDatabase sqlDBRead = null;
SQLiteDatabase sqlDBWrite = null;
try {
dbHelper = new DBHelper(context, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
sqlDBRead = dbHelper.getReadableDatabase();
sqlDBWrite = dbHelper.getWritableDatabase();
ContentValues book = new ContentValues();
book.put(TB_FinalAssessmentValues.CL_1_ID, getassessmentDetail.getId());
book.put(TB_FinalAssessmentValues.CL_2_USER_ID , getassessmentDetail.getUser_id());
book.put(TB_FinalAssessmentValues.CL_3_BOOK_ID, getassessmentDetail.getBook_id());
book.put(TB_FinalAssessmentValues.CL_4_CHAPTER_ID,
getassessmentDetail.getChapter_id());
book.put(TB_FinalAssessmentValues.CL_5_QUESTION_TYPE,
getassessmentDetail.getQuestion_type());
book.put(TB_FinalAssessmentValues.CL_6_QUESTION_ID,
getassessmentDetail.getQuestion_id());
book.put(TB_FinalAssessmentValues.CL_7_OPTION_ID,
getassessmentDetail.getOption_id());
book.put(TB_FinalAssessmentValues.CL_8_MARK,
getassessmentDetail.getMark());
book.put(TB_FinalAssessmentValues.CL_9_NOTES,
getassessmentDetail.getNotes());
book.put(TB_FinalAssessmentValues.CL_10_MATCH_OPTION, getassessmentDetail.getMatchOption());
book.put(TB_FinalAssessmentValues.CL_11_DRAG_VALUES,
getassessmentDetail.getDragValues());
book.put(TB_FinalAssessmentValues.CL_12_ADDED_TIME,
getassessmentDetail.getAdded_time());
Log.i("", "assessment values insertion success" );
} catch (Exception e) {
e.printStackTrace();
}
}
And trying to retrieve those table values into JSON array
public JSONArray getFullAssessmentData(Context mContext, String bookid,
int UserId) {
DBHelper dbh = new DBHelper(mContext, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
SQLiteDatabase db = dbh.getReadableDatabase();
JSONArray resultSet = new JSONArray();
try {
Cursor c = db.rawQuery("SELECT * FROM " + TB_FinalAssessmentValues.NAME
+ " WHERE " + TB_FinalAssessmentValues.CL_3_BOOK_ID+ "='"+ bookid + "'", null);
Log.i("tag", "msg vachindi");
if (c.getCount() > 0) {
c.moveToFirst();
do {
c.moveToFirst();
while (c.isAfterLast() == false) {
int totalColumn = c.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (c.getColumnName(i) != null) {
try {
rowObject.put(c.getColumnName(i),
c.getString(i));
} catch (Exception e) {
}
}
}
resultSet.put(rowObject);
c.moveToNext();
}
c.close();
db.close();
}
while (c.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
And finally trying to store those values into JSON array
JSONArray fullassessmentjson = rdb.getFullAssessmentData( getContext(), BookId, UserId);
Log.i("Tag123456","Finalcheck"+fullassessmentjson);
DBHelper
db.execSQL("CREATE TABLE IF NOT EXISTS " + TB_FinalAssessmentValues.NAME + "("
+ TB_FinalAssessmentValues.CL_1_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_2_USER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_3_BOOK_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_4_CHAPTER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_5_QUESTION_TYPE + " TEXT, "
+ TB_FinalAssessmentValues.CL_6_QUESTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_7_OPTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_8_MARK + " TEXT, "
+ TB_FinalAssessmentValues.CL_9_NOTES + " TEXT, "
+ TB_FinalAssessmentValues.CL_10_MATCH_OPTION + " TEXT, "
+ TB_FinalAssessmentValues.CL_11_DRAG_VALUES + " TEXT, "
+ TB_FinalAssessmentValues.CL_12_ADDED_TIME + " TEXT)");
and the error is its showing nothing in the Json array
Seems like you're adding the values to your ContentValues object, but do not perform the actual insert into the database.
(because of this you're basically querying an empty table)
You should call the insert() method of SQLiteDatabase at the end of addGetAssessmentDetail() to insert the data into your table:
sqlDBWrite.insert(TABLE_TO_INSERT, null, book);
I have an android Quote application in which I have used SQLite Database for storing quotes. I have launched the first version of the application with this DatabaseHelper.
public class DataBaseHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "SuccessQuotes";
private SQLiteDatabase myDataBase;
private static int DATABASE_VERSION = 1;
private final Context myContext;
public DataBaseHandler(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
Log.e("path", DB_PATH);
}
// ==============================================================================
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// ==============================================================================
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
and my Database Activity is :
public class DAO {
// All Static variables
private SQLiteDatabase database;
private DataBaseHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
// Pages Table Columns names
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_WEB_ID = "qu_web_id";
private static final String AU_ID = "_auid";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
// ==============================================================================
public DAO(Context context) {
dbHandler = new DataBaseHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHandler.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// Log.e("path2", context.getDatabasePath("SuccessQuotes").toString());
// open();
}
// ==============================================================================
// Getting All Quotes
public Cursor getQuotes(String start) {
// Select All Query
String limit = "15";
if (start.equals("5000")) {
String query_count = "SELECT COUNT(" + QU_ID + ") AS count FROM "
+ TABLE_QUOTES;
Cursor c_count = database.rawQuery(query_count, null);
c_count.moveToFirst();
Integer count = c_count.getInt(c_count.getColumnIndex("count"));
limit = String.valueOf(count);
}
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
//Log.i("query",query);
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting All Quotes
public Cursor getFavoriteQuotes(String start) {
// Select All Query
String limit = "15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1"+" ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
//======================================================================
// Getting Fav Quote from ID
public String getFavQuotes(String strkey_id) {
// Select All Query
String fav = "";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1 AND " + QU_ID + " = " +strkey_id;
Cursor cursor = database.rawQuery(query, null);
if(cursor.getCount() != 0)
{
cursor.moveToFirst();
fav = cursor.getString(cursor.getColumnIndex(QU_FAVORITE));
}
return fav;
}
// ==============================================================================
// Getting All Author Quotes
public Cursor getAuthorQuotes(String authorID,String start) {
// Select All Query
String limit="15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_AUTHOR + " = " + authorID + " ORDER BY "+ QU_WEB_ID +" DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Selected Quote
public Cursor getOneQuote(String quoteID) {
// Select All Query
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_ID + " = '" + quoteID + "'";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public void addOrRemoveFavorites(String id, String value) {
ContentValues values = new ContentValues();
values.put(QU_FAVORITE, value);
// Update Row
// database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
}
// ==============================================================================
// Getting All Authors
public Cursor getAllAuthors() {
// Select All Query
String query = "SELECT *, COUNT(" + QU_AUTHOR + ") AS count FROM "
+ TABLE_AUTHORS + " LEFT JOIN " + TABLE_QUOTES + " ON " + AU_WEB_ID
+ " = " + QU_AUTHOR + " GROUP BY " + AU_NAME ;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Quotes Count
public Integer getQuotesCount() {
String query = "SELECT COUNT(" + QU_TEXT + ") AS count FROM "
+ TABLE_QUOTES;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer count = cursor.getInt(cursor.getColumnIndex("count"));
return count;
}
// ==============================================================================
// Getting Quote ID
public Integer getQotdId() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY RANDOM() LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer id = cursor.getInt(cursor.getColumnIndex(QU_ID));
return id;
}
// ==============================================================================
public void updateSetting(String field, String value) {
open();
ContentValues values = new ContentValues();
values.put(field, value);
// Update Row
database.update(TABLE_SETTINGS, values, null, null);
}
// ==============================================================================
public Cursor getSettings() {
open();
String query = "SELECT * FROM " + TABLE_SETTINGS;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_WEB_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(QU_WEB_ID));
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int qu_web_id) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_WEB_ID, qu_web_id);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
public void open() throws SQLException {
// database = dbHandler.getReadableDatabase();
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDatabase() {
dbHandler.close();
}
Now if I want to update application with more quotes, which changes should I make so that the new and old users don't face any issue ?
I know That Database Version Should Increased, I will it, but What should I put in onUpgrade method ?
I am not expert Android developer, so Please explain me little more if possible, I will very thankful for it.
Thanks
Thanks
Well the Java doc pretty much explains what needs to be done.
From Java doc
Called when the database needs to be upgraded. The implementation
should use this method to drop tables, add tables, or do anything else it
needs to upgrade to the new schema version.
What we do is , alter the tables whenever we have changed the table schema.
In addition you can also perform some data migration if required. Basically its a hook which you got and you can perform any kind of compatibility logic.
cheers,
Saurav
I have a sqlite database in which I store all events. I store StartTime and EndTime against each events in date format.
I have fragments for days with tabs and one activity which adds events. Events are shown in another fragments.
Now I want to check if events do overlap with each other and based on which app should display a message.
How to display message in added event activity when the user saves events.
How can I do this?
I have tried this way but still events get added with same start time and end time:
ImageButton imageButton = (ImageButton)findViewById(R.id.imgbtn_fab);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
eventTitle = title.getText().toString();
EventTableHelper db = new EventTableHelper(getApplication());
List<EventData> events;
events = db.getAllEvents();
for (EventData eventData : events) {
String datefrom = eventData.getFromDate();
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
String dateTo = eventData.getToDate();
//times = dateTo.substring(11,16).split(":");
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
if (eventTitle.length() == 0) {
Toast.makeText(getApplicationContext(), "Title can not be empty.", Toast.LENGTH_LONG).show();
}
else if(minutesFrom == minutesTo) {
Toast.makeText(getApplicationContext(),"Event with same time exists.",Toast.LENGTH_LONG).show();
}
else
{
db.addEvent(new EventData(eventTitle, startTime, endTime, dayOfWeek, location));
setResult(RESULT_OK, i);
finish();
}
}
});
I get dates like this:
c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
df = new SimpleDateFormat("HH:mm a");
datefrom = c.getTime();
startTime = String.valueOf(datefrom);
aTime = df.format(datefrom.getTime());
showFromTime.setText(aTime);
c.add(Calendar.HOUR_OF_DAY, 1);
dateto = c.getTime();
endTime = String.valueOf(dateto);
bTime = df.format(dateto.getTime());
showToTime.setText(bTime);
I have created an EventTableHelper:
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I tried to use getAll events function in an activity to get data.
Edit: Here's my current code.
#Override
public void onClick(View v) {
eventTitle = title.getText().toString();
EventTableHelper db = new EventTableHelper(getApplication());
List<EventData> events;
// events = db.getOverlappingEvents(startTime,endTime);
if (eventTitle.length() == 0) {
Toast.makeText(getApplicationContext(), "Title can not be empty.", Toast.LENGTH_LONG).show();
}
else if(db.doesEventOverlap(startTime,endTime))
{
Toast.makeText(getApplicationContext(), "Event exists", Toast.LENGTH_LONG).show();
}
else
{
db.addEvent(new EventData(eventTitle, startTime, endTime, dayOfWeek, location));
setResult(RESULT_OK, i);
finish();
}
}
minutesTo, minutesFrom will only have the value for the last line in the db.
I would try to do a new function in EventTableHelper:
List<EventData> getOverlappingEvents(Date startTime, Date endTime) {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE
+ " WHERE (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + startTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + endTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " ('" + startTime + "' < " + KEY_FROM_DATE
+ " AND " + KEY_TO_DATE + " < '" + endTime + "')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
and in onClick:
events = db.getOverlappingEvents();
...
and instead of:
else if(minutesFrom == minutesTo)
this:
else if(events.size() > 0)
Actually it could be even further optimized, because it looks like you don't need the overlapping events data, only a boolean if there's at least one overlapping event:
boolean doesEventOverlap(Date startTime, Date endTime) {
String selectQuery = "SELECT COUNT(*) FROM " + TABLE
+ " WHERE (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + startTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + endTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " ('" + startTime + "' < " + KEY_FROM_DATE
+ " AND " + KEY_TO_DATE + " < '" + endTime + "')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
return cursor.getInt(0) > 0;
} while (cursor.moveToNext());
}
return false;
}
and in onClick instead of:
else if(minutesFrom == minutesTo)
this:
else if(db.doesEventOverlap())