Set message sending start datetime - android

I have chat application in which I am sending message to numbers which are being sent successfully. Now I want that I should set start date time of message sending. for this purpose I have stored datetime in sqlite database. that is my code:
while (true) {
cursor = databaseHelperClass.getMessageNotSent();
if (cursor != null && cursor.moveToFirst()) {
do {
Id = cursor.getInt(cursor.getColumnIndex("ID"));
jobMessageNotSent = cursor.getString(cursor.getColumnIndex("Message"));
startDatetime = cursor.getString(cursor.getColumnIndex("StartDatetime"));
isComplete = cursor.getInt(cursor.getColumnIndex("isComplete"));
} while (cursor.moveToNext());
new SendJobMessages().execute(Id);
}
and this is my asyncTask code:
private class SendJobMessages extends AsyncTask<Integer , Integer, Integer> {
private String jobNumbers = null;
#Override
protected Integer doInBackground(Integer... jobMessageIds) {
totalNumbers = jobMessageIds.length;
jobNumbersArray = new ArrayList<String>();
databaseHelperClass = new DatabaseHelperClass(getApplicationContext());
cursor = databaseHelperClass.getMessagesNumber(Id);
if (cursor != null && cursor.moveToFirst()) {
do {
JobMessagesId = cursor.getInt(cursor.getColumnIndex("ID"));
laterJobsNumbers = cursor.getString(cursor.getColumnIndex("Numbers"));
JobId = cursor.getInt(cursor.getColumnIndex("JobId"));
jobNumbersArray.add(laterJobsNumbers);
} while (cursor.moveToNext());
// sendJobsMessages();
for (int i = 0; i < jobNumbersArray.size(); i++) {
jobNumbers = jobNumbersArray.get(i);
if (countMessagePerDay() >= Integer.parseInt(MaxNoOfMessagePerDay)) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
sendSMSLater(String.valueOf(jobNumbers));
} catch (ParseException e) {
e.printStackTrace();
}
this.publishProgress(1);
}
}
}
return jobMessageIds.length;
}
}
and this is my sqlite query:
public Cursor getJMessagesNotSent() {
db = this.getReadableDatabase();
String query = "select * from Jobs where iscomplete = 0 and datetime('now') > startdatetime";
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
and for numbers:
public Cursor getJobsNumber(int jobId) {
db = this.getReadableDatabase();
String query = "SELECT * From JobMessages where issent = 0 and JobId = " + jobId + "";
Cursor cursor = db.rawQuery(query, null);
return cursor;
}

Related

Contacts Update to DB Not working with ContentObserver

I am working with an Android application which shows the list of contacts in the phone like Whats-app. I am successful with getting the contacts to the Application database. When I try to update my DB when a contact is newly added/edited/deleted using Content Observer, I mainly face two problems
1. When Calls ,
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
I am getting wrong name. eg:- I edited Samuel's Contact no but checking the above code getting David's name.
when I try to get contact number by using the code,
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
I am getting error
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 402 rows, 41 columns.
03-01 17:16:56.546 3660-3660/com.xxxxxxxxx.xxxxx W/System.err: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Please Anybody help me to find the solution.
Here is my Code
public class ContactObserver extends ContentObserver {
Intent i;
private static final String TAG = "ObserverReceiver";
private Context context;
BaseActivity mBaseActivity;
public ContactObserver(Handler handler, BaseActivity context) {
super(handler);
this.mBaseActivity = context;
this.context = context;
}
public ContactObserver() {
super(null);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
if (!selfChange) {
try {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Log.d(TAG, "Observer has been started..");
// Contacts Cursor
final Cursor cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Check which contact is added or updated
if (cur != null) {
while (cur.moveToNext()) {
// Get contact added/updated timestamp but CONTACT_LAST_UPDATED_TIMESTAMP
// Get new/updated contact detail here
final String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
final String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactNumber = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} catch (Exception e) {
e.printStackTrace();
}
}
String finalContactNumber = contactNumber;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
List<Contacts> sContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getBySystemid(id);
Log.i("Contacts1+", new Gson().toJson(sContacts));
if (sContacts.size() > 0) {
for (Contacts mContacts : sContacts) {
String phone = finalContactNumber;
if (phone == null) {
phone = mContacts.getPhone();
}
Log.i("Contacts1+", contactName + " : " + phone);
if (phone != null && phone.length() > 0) {
phone = phone.replace(" ", "");
}
while (String.valueOf(phone.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < phone.length(); i++) {
num = num + phone.charAt(i);
}
phone = num;
}
if (phone.length() == 10) {
phone = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + phone;
}
if ((mContacts.getName() != contactName || mContacts.getPhone() != phone)) {
mContacts.setName(contactName);
if (!mContacts.getPhone().equalsIgnoreCase(phone)) {
mContacts.setPhone(phone);
mContacts.setIslisted("false");
}
if (mContacts.getPhone().equalsIgnoreCase(phone) || mContacts.getName().equalsIgnoreCase(contactName)) {
ContactDatabase.getDatabase(context)
.contactsDao()
.update(mContacts);
cur.close();
}
}
}
} else {
Contacts mContacts = new Contacts();
String contactNumber = null;
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactNumber != null && contactNumber.length() > 0) {
contactNumber = contactNumber.replace(" ", "");
contactNumber = contactNumber.replace("-", "");
}
while (String.valueOf(contactNumber.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < contactNumber.length(); i++) {
num = num + contactNumber.charAt(i);
}
contactNumber = num;
}
if (contactNumber.length() == 10) {
contactNumber = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + contactNumber;
}
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
mContacts.setPhone(contactNumber);
mContacts.setName(contactName);
mContacts.setSystemid(id);
mContacts.setIslisted("false");
List<Contacts> cContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getbyPhone(contactNumber);
if (cContacts.size() == 0) {
ContactDatabase.getDatabase(context)
.contactsDao()
.insert(mContacts);
}
} catch (Exception e) {
e.printStackTrace();
}
}
i = new Intent(context, ContactSynchService.class);
context.startService(i);
cur.close();
}
});
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getSharedPreference(String key) {
SharedPreferences prefs = mBaseActivity.getSharedPreferences(AppConstants.SHARED_KEY, MODE_PRIVATE);
return prefs.getString(key, "DEFAULT");
}
}
I tried these links, but none of them could give a solution.
ContentObserver for contact update manually
ContentObserver not working in android
Android: ContentObserver not working in android 4.3
Any help will be appreciated. Thanks in Advance

Display each row from Database on a new line in a TextView

I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}

when Perform to "this.getReadableDatabase",skip the following code and throws Exception

public List<MedicalCase> getPersonalCase(int personid) {
Cursor c = null;
MedicalCase mMedicalCase = new MedicalCase();
List<MedicalCase> myList = new ArrayList<MedicalCase>();
try {
synchronized (DBLOCK) {
SQLiteDatabase db = this.getReadableDatabase();
String str_personid = String.valueOf(personid);
c = db.query(true, TABLE_Case, new String[]{MedicalCase_CaseId, MedicalCase_CaseCoverImageFileName,
MedicalCase_CaseColor, MedicalCase_CaseName,
MedicalCase_StartDate, MedicalCase_EndDate},
Person_PersonId + " = ?", new String[]{str_personid}, null, null, null, null);
if (c != null && c.moveToFirst()) {
do {
mMedicalCase.setCaseId(c.getColumnIndex(MedicalCase_CaseId));
mMedicalCase.setCaseCoverImageFileName(c.getString(c.getColumnIndex(MedicalCase_CaseCoverImageFileName)));
mMedicalCase.setCaseColor(c.getString(c.getColumnIndex(MedicalCase_CaseColor)));
mMedicalCase.setCaseName(c.getString(c.getColumnIndex(MedicalCase_CaseName)));
mMedicalCase.setStartDate(c.getLong(c.getColumnIndex(MedicalCase_StartDate)));
mMedicalCase.setEndDate(c.getLong(c.getColumnIndex(MedicalCase_EndDate)));
myList.add(mMedicalCase);
} while (c.moveToNext());
}
}
c.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return myList;
}
This is my code ,when Perform to this.getReadableDatabase,skip the following code and throws Exception,but not go to String str_personid = String.valueOf(personid);
I think that it is maybe the SQLiteDatabase db = this.getReadableDatabase() is NullPointer,but i dont sure if it is wrong.

Select query in android?

public Cursor getsomething()
{
this.open();
Cursor c = database.rawQuery("SELECT content_id FROM " +
DatabaseHandler.Table_Name2 +
" where playlist_id==100813", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String path = c.getString(c.getColumnIndex("content_id"));
MainActivity.t1.append("\n");
MainActivity.t1.append(path);
}while (c.moveToNext());
}
}
this.close();
return null;
}
I am using the above code to get the values but it is showing all the values from he content_id column. What am I doing wrong?
this.open();
ContentValues values2 = new ContentValues();
String csvFilename = "/mnt/sdcard/playlist.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String Rowst[] = null;
while((Rowst = csvReader.readNext()) != null) {
st1 = Rowst[0];
st2= Rowst[1];
st3= Rowst[2];
st4= Rowst[3];
st5= Rowst[4];
st6 = Rowst[5];
st7 = Rowst[6];
st8 = Rowst[7];
st9 = Rowst[8];
st10 = Rowst[9];
st11 = Rowst[10];
st12 = Rowst[11];
st13 = Rowst[12];
st14 = Rowst[13];
st15 = Rowst[14];
st16 = Rowst[15];
st17 = Rowst[16];
st18 = Rowst[17];
st19 = Rowst[18];
values2.put(DatabaseHandler.play1,st1);
values2.put(DatabaseHandler.play2,st2);
values2.put(DatabaseHandler.play3,st3);
values2.put(DatabaseHandler.play4,st4);
values2.put(DatabaseHandler.play5,st5);
values2.put(DatabaseHandler.play6,st6);
values2.put(DatabaseHandler.play7,st7);
values2.put(DatabaseHandler.play8,st8);
values2.put(DatabaseHandler.play9,st9);
values2.put(DatabaseHandler.play10,st10);
values2.put(DatabaseHandler.play11,st11);
values2.put(DatabaseHandler.play12,st12);
values2.put(DatabaseHandler.play13,st13);
values2.put(DatabaseHandler.play14,st14);
values2.put(DatabaseHandler.play15,st15);
values2.put(DatabaseHandler.play16,st16);
values2.put(DatabaseHandler.play17,st17);
values2.put(DatabaseHandler.play18,st18);
values2.put(DatabaseHandler.play19,st19);
database.insert(DatabaseHandler.Table_Name2, null, values2);
}
csvReader.close();
this.close();
this is my code to insert data in the this table,i am trying to read a csvfile on the sdcard and entering its data into table am i doing something wrong i have posted this also if it helps
public Cursor getsomething()
{
this.open();
Cursor c = db.query(DatabaseHandler.Table_Name2, null, "playlist_id=100813", null, null, null, null);
if (c.getCount() > 0)
{
if (c.moveToFirst())
{
do {
String path = c.getString(c.getColumnIndex("content_id"));
MainActivity.t1.append("\n");
MainActivity.t1.append(path);
}while (c.moveToNext());
}
}
this.close();
return null;
}

null pointer exception at db insert

package com.omkarsoft.ImagePortofolio;
import java.util.ArrayList;
import com.omkarsoft.ImagePortofolio.dataBaseHelper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class sqlQueries {
dataBaseHelper database;
SQLiteDatabase db ;
UrlList urllist ;
public sqlQueries( dataBaseHelper dbh , SQLiteDatabase db )
{
database = dbh;
this.db = db;
}
public sqlQueries() {
System.out.println("no are sqlqueries constructor");
}
public void insertIntoCompanyTable( String companyname ) {
db = database.getWritableDatabase(); // this works fine here
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_NAME, companyname);
System.out.println(values);
db.insert(dataBaseHelper.COMPANY_LIST, null, values);
}
public int getCompanyID( String companyName)
{
int id = 0 ;
Cursor c = null;
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT company_id FROM company_list WHERE company_name = '"+ companyName +"'";
c = db.rawQuery(query,null);
} catch (Exception e) {
System.out.println("In getCompanyID : " +e);
}
if (c != null ) {
if (c.moveToFirst()) {
id = c.getInt(c.getColumnIndex("company_id"));
}
}
return id;
}
public int getCompanies( String comp) {
int id = 0;
Cursor c = null;
ArrayList<String> names = new ArrayList<String>();
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT * FROM company_list ";
c = db.rawQuery(query, null);
} catch (Exception e) {
System.out.println(e);
}
if (c != null) {
if (c.getCount() == 0)
id = 1;
else {
if (c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex("company_name"));
names.add(name);
} while (c.moveToNext());
}
if( names.contains(comp))
id = 0;
else
id = 1 ;
}
}
return id;
}
public void insertIntoImageTable( int companyid , String productname , String productdesc , byte[] bmp )
{
try
{
db = database.getWritableDatabase(); // blows here i get a NPE
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_ID, companyid);
values.put(dataBaseHelper.PRODUCT_NAME, productname);
values.put(dataBaseHelper.PRODUCT_DESCRIPTION, productdesc);
values.put(dataBaseHelper.PRODUCT_IMAGE, bmp);
System.out.println(values);
db.insertOrThrow(dataBaseHelper.IMAGE_DATA, null, values);
System.out.println(values);
}
catch( Exception e)
{
e.printStackTrace();
}
}
}
You need to open the DB for writing first like e.g.
SQLiteDatabase db = tdHelper.getWritableDatabase();
and tdHelper being an instance of
private static class TweetDBOpenHelper extends SQLiteOpenHelper
Just try to logcat every parameter you put in db.insert with String.valueOf(); You'll then see which parameter is null.

Categories

Resources