how to perform a query every 30 seconds in android? - android

i have a query that i want to perform it every 30 seconds and Log it to Logcat. i did this by handler and i did not get response.
here is my code:
runnable = new Runnable() {
#Override
public void run() {
Cursor cursor = null;
int i;
try {
String sql = "SELECT * FROM info";
cursor = database.rawQuery(sql, null);
} catch (SQLException sqle) {
throw sqle;
}
if (cursor != null && cursor.getCount() != 0) {
cursor.moveToFirst();
do {
i = cursor.getCount();
} while (cursor.moveToNext());
cursor.close();
if (i > count) {
count = i;
Log.i("COUNT", "" + count);
}
}
handler.postDelayed(runnable, 30000);
}
};
runnable.run();
if anyone can help me i will be appreciated.

The Best Way to Create a Timer will be to Use Timer class
Timer _Request_Trip_Timer = new Timer();
_Request_Trip_Timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//your code here
}
}, 5, 1000);// First time start after 5 mili second and repead after 1 second

Related

showing download progress in progress bar using DownloadManager

I am working on an android app in which i am using DownloadManager to download a file from a server.
Problem
While the file download is in progress, I want to show the download progress via progress bar. File is downloaded successfully but I am not able to show the download progress.
Code I use to show progress
private void startAppDownload() {
...
// code to show download progress
new Thread(new Runnable() {
#Override
public void run() {
boolean isDownloading = true;
int downloadStatus, totalBytesDownloaded, totalBytes;
DownloadManager.Query downloadQuery = new DownloadManager.Query();
downloadQuery.setFilterById(downloadID);
Cursor cursor = downloadManager.query(downloadQuery);
cursor.moveToFirst();
while (isDownloading) {
totalBytesDownloaded = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
);
totalBytes = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
);
downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
isDownloading = false;
}
final int downloadProgress = (int) ((double)totalBytesDownloaded / (double)totalBytes * 100f);
runOnUiThread(new Runnable() {
#Override
public void run() {
downloadProgressBar.setProgress(downloadProgress);
}
});
}
cursor.close();
}
}).start();
}
I logged the totalBytesDownloaded variable but it is always zero and the totalBytes variable is always -1.
This causes downloadProgress variable to always be zero, hence progress bar shows no progress.
Question
What am I doing wrong here? Why is totalBytesDownloaded variable always equal to zero and totalBytes variable always -1?
You have a Logic error, Your Query is out of the while loop where the UI is updated
private void startAppDownload() {
new Thread(new Runnable() {
#Override
public void run() {
boolean isDownloading = true;
int downloadStatus, totalBytesDownloaded, totalBytes;
while (isDownloading) {
DownloadManager.Query downloadQuery = new DownloadManager.Query();
downloadQuery.setFilterById(downloadID);
Cursor cursor = downloadManager.query(downloadQuery);
cursor.moveToFirst();
totalBytesDownloaded = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
);
totalBytes = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
);
downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
isDownloading = false;
break;;
}
final int downloadProgress = (int) ((double)totalBytesDownloaded / (double)totalBytes * 100f);
runOnUiThread(new Runnable() {
#Override
public void run() {
downloadProgressBar.setProgress(downloadProgress);
}
});
}
cursor.close();
}
}).start();
}

Cursor only returning one value / last value

I am really stuck as I have a cursor that retrieves values from the database but the cursor only returns the last value. I need the cursor to retrieve all values so I can display them all later on. Is there any way as I can return all the data stored through the cursor?
An Example as to whats happening. Eg Click on Button 1 and stores 1 perfectly but once I click on Button 2 and add 1. Button 1 data is not return or retrieved.
Any help would be greatly appreciated.
Execute
The first Cursor is goes through to check all the stored items.
public void exectute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
//if (details != null) mWorkoutDetailsList.add(details);
do {
//if (details != null) mWorkoutDetailsList.add(details);
WorkoutDetails temp = getWorkoutFromCursor(c);
//if (details != null) mWorkoutDetailsList.add(details);
if (details == null) {
details = temp;
continue;
}
//if (details != null) mWorkoutDetailsList.add(details);
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
//if (details != null) mWorkoutDetailsList.add(details);
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
//details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
// if (details != null) mWorkoutDetailsList.add(details);
} 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);
}
});
}
c.close();
}
}
});
}
Get Stored Items Code
This is the code which the excute class calls and where the cursor only returns one value.
public static Cursor getStoredItems(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE, DURATION, DATE, POINT};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, null, null, null, null, orderBy);
return cursor;
}
Array
This is the array code where i want the cursor to store its values based on type.
private WorkoutDetails getWorkoutFromCursor(Cursor c) {
long time = c.getLong(c.getColumnIndex(TrackerDb.TIME));
int type = c.getInt(c.getColumnIndex(TrackerDb.TYPE));
int duration = c.getInt(c.getColumnIndex(TrackerDb.DURATION));
int point = c.getInt(c.getColumnIndex(TrackerDb.POINT));
int totalMoney = MoneyActivity.Money.values().length;
int[] points = new int[totalMoney];
int totalActivities = MeditationTrackerActivity.ACTIVITIES.values().length;
int[] durations = new int[totalActivities];
if (type < totalActivities) {
durations[type] = duration;
}
if( type == 0) {
for (int i = 0; i < totalMoney; i++) {
points[type] = point;
}
}
else if ( type == 1) {
for ( int ii = 0; ii < totalMoney; ii++) {
points[type] = point;
}
}
else if ( type == 2) {
for ( int iii = 0; iii < totalMoney; iii++) {
points[type] = point;
}
}
return new WorkoutDetails(time, durations, points);
}
Get Workout From Cursor Code
private static WorkoutDetails getWorkoutFromCursor(Cursor c) {
long time = c.getLong(c.getColumnIndex(TrackerDb.TIME));
int type = c.getInt(c.getColumnIndex(TrackerDb.TYPE));
int duration = c.getInt(c.getColumnIndex(TrackerDb.DURATION));
String date = c.getString(c.getColumnIndex(TrackerDb.DATE));
int point = c.getInt(c.getColumnIndex(TrackerDb.POINT));
int[] durations = new int[MeditationTrackerActivity.ACTIVITIES.values().length];
durations[type] = duration;
int[] points = new int[MoneyActivity.Money.values().length];
points[type] = point;
return new WorkoutDetails(time, durations, date, points);
}

Android How to play audio for 2 times before moving to the next one

I want to play the audio two times before playing the next item.
This is my class where I want to display the items.
public void startSlides() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Intent intent = getIntent();
int setId = intent.getIntExtra("SelectedSetId",0);
databaseAccess.open();
setId = setId + 1;
List<byte[]> audio = databaseAccess.getAudioA(setId);
if (i > audio.size()){
i = 0;
}else{
playAudio(audio.get(i));
playAudio(audio.get(i));
i++;}
List<String> vocab = databaseAccess.getVocabNameA(setId);
textView2.setText(vocab.get(k));
k++;
textView.setText(+j + "/" + vocab.size());
j++;
databaseAccess.close();
if (j == vocab.size() + 1) {
timer.cancel();
}
}
});
}
}, 0, DURATION);
}
I think I have to add something at the playAudio(audio.get(i)), but I have no idea how should I do. If I do this, it plays the audio at the same time. Thanks.
if (i > audio.size()){
i = 0;
}else{
playAudio(audio.get(i));
playAudio(audio.get(i));
i++; }

How to stop Executors.newSingleThreadScheduledExecutor(); in between the thread execution?

Below I am posting my code for the thread I am running to animate text in a RelativeLayout on top of the Page Curl activity by harism.
public void startProgress(final int index)
{
runnable = new Runnable()
{
#Override
public void run()
{
mArrWords.removeAll(mArrWords);
mStart.removeAll(mStart);
mEnd.removeAll(mEnd);
words = sentence.split(" ");
for(int i = 0; i < words.length; i++)
{
mArrWords.add(words[i]);
if(i == 0)
{
mStart.add(0);
mEnd.add(words[0].length());
}
else
{
mStart.add(mEnd.get(i-1)+1);
mEnd.add(mStart.get(i)+words[i].length());
}
/*Log.e("words", "" + "" + words[i]);
Log.e("mArrWords", "" + mArrWords);
Log.e("mStart", "" + mStart);
Log.e("mEnd", "" + mEnd);*/
}
for (int i = 0; i < mArrWords.size(); i++)
{
final int value = i;
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mHandler.post(new Runnable()
{
#Override
public void run()
{
currIndex = index;
try
{
if(CurlView.ANIMATE)
tv1.setVisibility(View.VISIBLE);
else
tv1.setVisibility(View.GONE);
final Pattern p = Pattern.compile(mArrWords.get(value));
final Matcher matcher = p.matcher(sentence);
SpannableString spannableTxt = new SpannableString(sentence);
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
while(matcher.find())
spannableTxt.setSpan(span, mStart.get(value), mEnd.get(value), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv1.setText(spannableTxt);
mHandler.sendEmptyMessage(0);
}
catch (Exception e)
{
e.printStackTrace();
mHandler.sendEmptyMessage(0);
}
}
});
}
}
};
final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(runnable, CurlView.ANIMTIME+50, TimeUnit.MILLISECONDS);
}
Here, I am animating the text over images. I need to change the text for each page I am changing. I am able to change the text, however, when I turn the page, the index values I store in ArrayLists are not getting cleared. I am storing a sentence in an ArrayList named mArrWords and the indexes to refer to each word of sentence are stored in mStart and mEnd.
The problem I am facing is when the text changes, the animation starts with the previous indexes stored in mStart and mEnd ArrayLists I use to store index of a particular word. What I need to know is how do I stop my thread when the page is turned or the index of the page changes. I am calling this function inside the updatePage(final CurlPage page, final int width, final int height, final int index) method of Curl activity. I hope I was able to explain my problem. Thanks!
EDIT: I would like to specify my question more clearly. How do I check if the thread is already running before starting another thread and stop the execution of the previous thread?
removeCallbacks(..) only stops pending messages (Runnables).If runnable is started then u can not stop it in this way. See the following :
removecallbacks-not-stopping-runnable

Count down timer in android

I am new to android.I am having an app which can be used for exam management.Users can insert the date of every subjects and the app will provide time(in hours) for each subject.There is countdown timer which will start from the time allocated for each subject(for eg,48 hours) and should go to zero.when it hits zero an alarm should be played showing that time allocated for that subject has got over.this is my code.
public class Alarmpage extends Activity{
TextView hourshow,minshow,secshow;
SQLiteDatabase database_read;
sampleDatabase samp;
Cursor cur;
Handler handler;
int initStart;
Runnable updater;
int t;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
hourshow=(TextView)findViewById(R.id.hr);
samp=new sampleDatabase(getApplicationContext());
database_read=samp.getReadableDatabase();
minshow=(TextView)findViewById(R.id.min);
secshow=(TextView)findViewById(R.id.sec);
cur=database_read.query(sampleDatabase.TABLE_SEC, null, null, null, null, null, null);
}
public void onResume() {
super.onResume();
if(cur.moveToFirst())
{
t=cur.getInt(3);
Log.e("time", String.valueOf(t));
}
handler=new Handler();
initStart = (int) SystemClock.elapsedRealtime();
Log.e("init", String.valueOf(initStart));
updater = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
int sec,minute,hour;
int diff = t*60*60;
Log.e("time in sec", String.valueOf(diff));
System.out.println(diff);
/*if(diff>=1)
{
hour= diff/3600;
}
else {hour = 00; }
hourshow.setText(String.valueOf(hour));
Log.e("diff after hour", String.valueOf(diff));
Log.e("hour", String.valueOf(hour));
minute = (diff % 3600) / 60;
minshow.setText(":"+String.valueOf(minute));
sec= (diff % 60);
secshow.setText(":"+String.valueOf(sec));*/
if (diff >= 1) {
sec = (int) (diff%60);
} else {
sec=00;
}
secshow.setText(":"+String.valueOf(sec));
diff = diff/60;
if (diff >= 1) {
minute = (int) (diff%60);
} else {
minute=00;
}
minshow.setText(":"+String.valueOf(minute));
diff = diff/60;
if (diff >= 1) {
hour = (int) (diff%24);
} else {hour = 00; }
hourshow.setText(String.valueOf(hour));
t=(t*60*60)-1;
handler.postDelayed(this, 1000);
}
};
handler.post(updater);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
handler.removeCallbacks(updater);
}
}
but its showing some values.but they are not correct.kindly help me.I dont understand error in this code.Thanks in advance

Categories

Resources