I have over 3000 sms on my device. I'm trying to read all messages in the database. I am using this query:
Cursor cur1 = c.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, null);
cur1.getCount() returns all 3000 sms, but when I parse it through a loop it only runs through 400 to 500.
Cursor cur1 = c.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, null);
int size = cur1.getCount();
if(size > 0)
{
sms = new SMS[size];
//int i = 0;
for(int i = 0 ; i < size ; i++)
{
cur1.moveToNext();
ContactInfo p = new ContactInfo();
String content = cur1.getString(cur1.getColumnIndex("body"));
String number = cur1.getString(cur1.getColumnIndex("address"));
long date = cur1.getLong(cur1.getColumnIndex("date"));
String person = cur1.getString(cur1.getColumnIndex("person"));
String protocol = cur1.getString(cur1.getColumnIndex("protocol"));
String name = p.getName(number, c);
String type = null;
Calendar cal=Calendar.getInstance();
cal.clear();
cal.setTimeInMillis(date);
String date_time=String.format("%1$te %1$tB %1$tY,%1$tI:%1$tM:%1$tS %1$Tp",cal);
Log.i("INFO", content+" "+i);
sms[i] = new SMS(type , name , number , date_time , content );
}
}
After 400-500 iterations logcat prints
09-19 20:28:31.148: E/liblog(3153): failed to call dumpstate
09-19 20:28:31.179: I/ActivityManager(3153): Process com.arslan (pid 1766) has died.
Many other processes are running on device and due to this long process of reading 3000 messages it takes a lot of continuous CPU time that's why process killed. When I tried to read it through thread it works fine.
final Cursor cur1 = c.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, "date ASC");
final int size = cur1.getCount();
final int sleeptimer = size;
final SMS [] sms = new SMS[size];
Thread myThread = new Thread()
{
public void run()
{
try
{
int currentwait = 0;
int j=0;
while(currentwait < sleeptimer)
{
sleep(200);
currentwait+=200;
for(int i = 0 ; i < 200 ; i++)
{
if(!cur1.moveToNext())
{
break;
}
ContactInfo p = new ContactInfo();
String content = cur1.getString(cur1.getColumnIndex("body"));
String number = cur1.getString(cur1.getColumnIndex("address"));
long date = cur1.getLong(cur1.getColumnIndex("date"));
String protocol = cur1.getString(cur1.getColumnIndex("protocol"));
String name = p.getName(number, c);
String type = null;
Calendar cal=Calendar.getInstance();
cal.clear();
cal.setTimeInMillis(date);
String date_time=String.format("%1$te %1$tB %1$tY,%1$tI:%1$tM:%1$tS %1$Tp",cal);
Log.i("INFO", content+" "+j);
sms[j] = new SMS(type , name , number , date_time , content );
j++;
}
}
}
catch(Exception e)
{
}
finally{
}
}
};
myThread.start();
Related
I am working on phonebook app in android which contains frequently called numbers activity too.I have got the list of numbers with the counter that how many times its have been called.But now i want only 10 most called numbers from that list.
Here is the working code:
I have sorted data using map.
Basically i wanted to sort the data by value which is counter of called numbers.
ListView list_view2;
String[] PERMISSIONS = {Manifest.permission.READ_CALL_LOG};
ArrayList<Integer> listdata2;
ArrayList<Integer> key;
ArrayList<Integer> value;
int maxIndex = 0;
Integer val;
HashMap<String, Integer> map = new HashMap<String, Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frequently_called);
list_view2 = findViewById(R.id.list_view2);
listdata2 = new ArrayList<Integer>();
getCallDetails();
}
#SuppressLint("LongLogTag")
private String getCallDetails() {
StringBuffer sb = new StringBuffer();
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED) {
requestContactsPermissions();
return requestContactsPermissions();
}
Cursor managedCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
Integer number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
Integer callType = managedCursor.getInt(type);
Integer callDate = managedCursor.getInt(date);
Date callDayTime = new Date(Long.valueOf(callDate));
Integer callDuration = managedCursor.getInt(duration);
Log.e("Phone number", phNumber + "");
Log.e("call type", callType + "");
Log.e("call duration", callDuration + "");
// Log.e("call date", callDate + "");
Log.e("call day time", callDayTime + "");
String dir = null;
int dircode = new Integer(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;
}
if (map.get(phNumber) == null) {
map.put(phNumber+"", 1);
} else {
Integer scount = map.get(phNumber).intValue();
scount++;
map.put(phNumber+"", scount);
//Log.e("map values", map + "");
}
}
managedCursor.close();
//Log.e("map.keySet()",map.keySet().toString());
HashSet<String> numbersset=new HashSet<String>(map.keySet());
ArrayList<String> numbers= new ArrayList<String>();
ArrayList<Integer> counts= new ArrayList<Integer>();
Iterator iterator=numbersset.iterator();
while(iterator.hasNext()) {
String no = iterator.next().toString();
numbers.add(no);
counts.add(map.get(no));
}
Log.e("number count ",numbers.size()+"|");
Log.e("count count ",counts.size()+"|");
for (int i=0;i<counts.size();i++){
for(int j=0;j<counts.size();j++){
int t1=counts.get(i);
int t2=counts.get(j);
if(t1 > t2){
for(t1=0;t1>=10;t1++) {
for(t2=0;t2>=10;t2++) {
int temp = counts.get(j);
counts.set(j, counts.get(i));
counts.set(i, temp);
String temps = numbers.get(j);
numbers.set(j, numbers.get(i));
numbers.set(i, temps);
}
}
}
}
}
//Sorting data in reverse
for (int i=0;i<counts.size();i++){
Log.e("sort-"+numbers.get(i),counts.get(i)+"");
}
return sb.toString();
}
private String requestContactsPermissions () {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CALL_LOG)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
} else {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
}
return null;
}
}
For your count array.This will sort your counts array in descendingorder.
Comparator mycomparator = Collections.reverseOrder();
Collections.sort(counts,mycomparator);
now if you want to get 10 elements from your ArrayList.
ArrayList<Integer> popular_counts= new ArrayList<Integer>();
for(int i = 0; i< 9; i++){
popular_counts.add(counts.get(i));
}
popular_counts is your final ArrayList.
You can create loop that will be 10 times and another one which will search every time for the biggest counter and add the coresponding number to the new list.
#Override
protected void onCreate(Bundle savedInstanceState) { // Exaple to show result
ArrayList<String> number = new ArrayList<>();
number.add("0521392");
number.add("0521396");
number.add("0521397");
number.add("0521398");
number.add("0521391");
ArrayList<Integer> counts = new ArrayList<>();
counts.add(10);
counts.add(5);
counts.add(6);
counts.add(10);
counts.add(7);
for (String n : mostCalled(number, counts, 8)){ // Calling the function and printing the output
Log.i("go", "phone number: " + n);
}
}
private ArrayList<String> mostCalled(ArrayList<String> number, ArrayList<Integer> counts, int howMuchNumbersToShow){ // function that get list of phone numbers and list of how meany times each number called and return the howMuchNumbersToShow most called numbers (who called the most times)
if (number.size() != counts.size()){
return new ArrayList<>();
}
int biggerNumber = -1; // will store the current biggest number
int lastBiggerNumber = 10000000; // will store the last bigger number
int biggerNumberPlace = -1; // will store the place of the biggest number in the array
ArrayList<Integer> biggerNumberLocationList = new ArrayList<>(); // will store all the places of the biggest numbers in the array
if (howMuchNumbersToShow > number.size())
howMuchNumbersToShow = number.size();
for (int l=0; l<howMuchNumbersToShow; l++){
for (int x=0; x<counts.size(); x++){
if (!biggerNumberLocationList.contains(x)) // to get each number one time (help in case more then one phone number called the same amount)
if (counts.get(x) >= biggerNumber && counts.get(x)<= lastBiggerNumber){
biggerNumber = counts.get(x);
biggerNumberPlace = x;
}
}
lastBiggerNumber = biggerNumber;
biggerNumber = -1;
biggerNumberLocationList.add(biggerNumberPlace);
}
ArrayList<String> mostCalledPhoneNumbers = new ArrayList();
int place_in_array;
String phoneNumber;
for (int f=0; f<biggerNumberLocationList.size() ; f++) {
place_in_array = biggerNumberLocationList.get(f);
phoneNumber = number.get(place_in_array);
mostCalledPhoneNumbers.add(phoneNumber);
// Log.i("go", "place in array " + biggerNumberLocationList.get(f) + ", the phone number " + number.get(biggerNumberLocationList.get(f)) + " called " + counts.get(biggerNumberLocationList.get(f)) + " times ");
}
return mostCalledPhoneNumbers;
}
It would be easier to use HashMap for this job or even ArrayList<> of type object that stores string and int.
after studying a lot i made this custom code .which worked perfect.i guess its lengthy.but still.again thanks to #Tejas Pandya and #guy.
//putting above data into hashmap
HashMap<String,Integer> hm = new HashMap<String,Integer>();
for(int i = 0; i < counts.size(); i++) {
hm.put(numbers.get(i),counts.get(i));
}
//create list from elements of hashmaps
List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());
//sort the list
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Map.Entry<String, Integer> stringIntegerEntry,
Map.Entry<String, Integer> t1) {
return (t1.getValue()).compareTo(stringIntegerEntry.getValue());
}
});
HashMap<String,Integer> temp = new LinkedHashMap<String,Integer>();
for(Map.Entry<String,Integer> aa : list){
temp.put(aa.getKey() , aa.getValue());
Log.e("descending",aa.getValue()+"");
Log.e("descending",aa.getKey()+"");
}
String temp2 = String.valueOf((list.subList(0, 10)));
Log.e("final",temp2+"");
I have a list that is populated with data taken from database.
The data of the list are passed to the view to display them. For each id taken from the database, I want to add a day to the calendar, then, I added the id what I need in an array, in order to have them sorted.
The problem is the loop in the list, instead of iterating based on the number of id in the array, the cycle continues without stopping ... I hope I explained, this is all the code
private Integer[] id_nome_op;
public void checkOperatori() {
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String OPERATORI = "SELECT _id, ...... ORDER BY _id ASC";
Cursor cur = db.rawQuery(OPERATORI, null);
int count = cur.getCount();
id_nome_op = new Integer[count];
nome_op = new String[count];
cognome_op = new String[count];
for (int i = 0; i < count; i++) {
cur.moveToNext();
id_nome_op[i] = cur.getInt(0);
nome_op[i] = cur.getString(1);
cognome_op[i] = cur.getString(2);
mWeekView.setData(nome_op, cognome_op);
}
cur.close();
db.close();
}
#Override
public List<WeekViewEvent>onMonthChange(int newYear, int newMonth) {
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
final String strDate = simpleFormat.format(calendarioFooter.getTime());
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String tabella_op = "SELECT m._id, m.id_operatore, ...........";
Cursor cur = db.rawQuery(tabella_op, null);
while (cur.moveToNext()) {
startTime = (Calendar) calendarioFooter.clone();
id_appuntamento = cur.getString(0);
id_operator = cur.getInt(1);
dat = cur.getString(2);
ora_iniz = cur.getString(3);
ora_fin = cur.getString(4);
id_servizio = cur.getString(5);
id_client = cur.getString(6);
nome_cliente = cur.getString(7);
cognome_cliente = cur.getString(8);
nome_operatore = cur.getString(9);
colore_serv = cur.getInt(10);
tipo_serv = cur.getString(11);
int giorno_ok = Integer.parseInt(dat.substring(8, 10));
int ora_inizio = Integer.parseInt(ora_iniz.substring(0, 2));
int minuto_inizio = Integer.parseInt(ora_iniz.substring(3, 5));
int ora_fine = Integer.parseInt(ora_fin.substring(0, 2));
int minuto_fine = Integer.parseInt(ora_fin.substring(3, 5));
int size = id_nome_op.length;//array id
for(int i = 1; i< size; i++){
if (i == 1) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
} else if (i == 2) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
startTime.add(Calendar.DATE, 1);
} else if (i == 3) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
startTime.add(Calendar.DATE, 2);
}
startTime.set(Calendar.HOUR_OF_DAY, ora_inizio);
startTime.set(Calendar.MINUTE, minuto_inizio);
startTime.set(Calendar.MONTH, newMonth - 1);
startTime.set(Calendar.YEAR, newYear);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.HOUR_OF_DAY, ora_fine);
endTime.set(Calendar.MINUTE, minuto_fine);
WeekViewEvent event = new WeekViewEvent(id_appuntamento, getEventTitle(startTime), startTime, endTime);
event.setColor(colore_serv);
events.add(event);
}
}
cur.close();
db.close();
return events;
}
Hi i have Thumbnail of image and video file using cursor by implementing in Asyntask, now i have to wait for loading thumbnails if have more than 500 files in mobile.
so i used universal-image-loader-1.6.1-with-src.jar for asynchronous loading in which got problem to display bitmap,
how to load all thumbnails (Image and video file) using universal-image-loader? i have referred this http://www.technotalkative.com/android-select-multiple-photos-from-gallery/ to using Asynchronous image loader but already i have Bitmap - bitList Arraylist (Thumbnail for Image and video) then i how to display these bitmap using that library in gridview?
My Code part is
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID }; // Images getting
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
imagecursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
bitList = new ArrayList<Bitmap>();
arrPathList = new ArrayList<String>();
selectedPath = new ArrayList<String>();
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
bitList.add( MediaStore.Images.Thumbnails.getThumbnail(
mContext.getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null));
arrPathList.add(imagecursor.getString(dataColumnIndex));
}
final String[] parameters = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID, MediaStore.Video.Media.DURATION , MediaStore.Video.Media.MIME_TYPE}; // Videos getting
final String orderBy_v = MediaStore.Video.Media._ID;
videocursor = mContext.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, parameters, null,
null, orderBy_v);
int video_column_index = videocursor.getColumnIndex(MediaStore.Video.Media._ID);
for(int ii = 0; ii < videocursor.getCount(); ii ++){
videocursor.moveToPosition(ii);
int id_v = videocursor.getInt(video_column_index);
int datacolumn_v = videocursor.getColumnIndex(MediaStore.Video.Media.DATA);
long duration = videocursor.getInt(video_column_duration);
bitList.add(MediaStore.Video.Thumbnails.getThumbnail(mContext.getContentResolver(), id_v,
MediaStore.Video.Thumbnails.MICRO_KIND, null));
arrPathList.add(videocursor.getString(datacolumn_v));
}
Thanks in Advance.
Problem solved by using of Lazy loading concept that means i will show first 15 images from we have retrieved by image cursor and stored bitmap into the bitlist Arraylist and will be retrieved at each time by scrolling at the end of the view.
My Code part is :
protected Integer doInBackground(Integer... params){ // here we passes first 15 and will pass next 15 for every scrolling at the end of the view
// TODO Auto-generated method stub
if(params[0] != null)
count = params[0];
if(count == 15) // this is for will show only 15 images in first attempt in the view
j = 0; // Maintain this variable as static
for(int i = j; i < count; i ++){
imgcursor.moveToPosition(i);
String mime_Type = imgcursor.getString(imgcursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE));
String fMime_type = mime_Type.substring(0,5);
if(fMime_type.equals("image")){
id = imgcursor.getInt(imgcursor.getColumnIndex(MediaStore.Images.Media._ID));
dataColumnIndex = imgcursor.getColumnIndex(MediaStore.Images.Media.DATA);
String date = imgcursor.getString((imgcursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN)));
if(Constants.DEBUG)Log.e(TAG, "Date of this file" +date);
if(bitList != null)
bitList.add( MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null));
durationcount.add(null);
mimeType.add(fMime_type);
arrPathList.add(imgcursor.getString(dataColumnIndex));
}
else
{
id = imgcursor.getInt(imgcursor.getColumnIndex(MediaStore.Video.Media._ID));
dataColumnIndex = imgcursor.getColumnIndex(MediaStore.Video.Media.DATA);
if(Constants.DEBUG)Log.e("Duration", "Duration of video :"+imgcursor.getString(dataColumnIndex));
String path = imgcursor.getString(dataColumnIndex);
File f = new File(path);
try {
FileInputStream in = new FileInputStream(f);
mRetriever.setDataSource(in.getFD());
String durations = mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // getting duration of the every videos
long duration = Long.parseLong(durations);
if(Constants.DEBUG)Log.e(TAG, "Duration of file: "+duration);
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(duration),
TimeUnit.MILLISECONDS.toMinutes(duration) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration)),
TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
if(Constants.DEBUG)Log.e(TAG, "Duration of file Hms: "+hms);
durationcount.add(hms);
if(bitList != null)
bitList.add( MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(), id,
MediaStore.Video.Thumbnails.MICRO_KIND, null));
mimeType.add(fMime_type);
arrPathList.add(imgcursor.getString(dataColumnIndex));
in.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
j = count;
return null;
}
Actually I have written a method for updatiing server database using webservice from my application installed in the device using two IP Address.If one IP failed then it usess the second IP for upadting the data at server.
If Both the IP address failed i am saving the data to one of my sqllite database table tblTransaction.The code for that is given below.
private void Delay15Minute() throws IOException {
String server1IPAddress = "";
String server2IPAddress = "";
String deviceId = "";
Cursor cursorAdmin;
Cursor cursorTransaction;
adminhelper = new admin_helper(this);
cursorAdmin = adminhelper.GetAdminDetails();
if (cursorAdmin.moveToFirst())
server1IPAddress = cursorAdmin.getString(cursorAdmin
.getColumnIndex("RemoteServer1IPAddress"));
server2IPAddress = cursorAdmin.getString(cursorAdmin
.getColumnIndex("RemoteServer2IPAddress"));
deviceId = cursorAdmin.getString(cursorAdmin
.getColumnIndex("DeviceID"));
cursorAdmin.close();
ContentValues initialDelay15 = new ContentValues();
ContentValues initialTransaction = new ContentValues();
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String RevisedEstimatedDate = sdf.format(date);
manifest_helper = new manifest_helper(this);
cursor = manifest_helper.GetDeliveries(pkManifest);
cursor.moveToFirst();
dbAdapter = new DatabaseAdapter(this);
dbAdapter.open();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.getString(cursor.getColumnIndex("PKDelivery"));
String RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String dateRevisedEstimatedDeliveryTime = addTime(val[0], val[1], 15);
initialDelay15.put("RevisedEstimatedDeliveryTime",
dateRevisedEstimatedDeliveryTime);
dbAdapter.UpdateRecord("tblDelivery", initialDelay15, "PKDelivery"
+ "=" + cursor.getString(cursor.getColumnIndex("PKDelivery")), null);
}
dbAdapter.close();
dataXmlExporter=new DataXmlExporter(this);
dataXmlExporter.StartDataSet();
cursor = manifest_helper.GetDeliveries(pkManifest);
dataXmlExporter.AddRowandColumns(cursor,"tblDelivery");
String sqlTransaction = "Select 6 as TransactionType,'Update Revised Estimated Delivery Time' as Description,"
+ " deviceId as DeviceID ,date() as TransactionUploadDate,time() as TransactionUploadTime from tblAdmin where PKAdmin > ?";
dbAdapter = new DatabaseAdapter(this);
dbAdapter.open();
cursorTransaction = dbAdapter.ExecuteRawQuery(sqlTransaction, "-1");
dataXmlExporter.AddRowandColumns(cursorTransaction, "Transaction");
String XMLTransactionData=dataXmlExporter.EndDataSet();
try {
if ((server1IPAddress != "") && (server2IPAddress != "")) {
try {
if (server1IPAddress != "") {
InsertUploadedTrancasctionDetails(server1IPAddress,
deviceId, XMLTransactionData);
}
} catch (Exception exception) {
if ((server1IPAddress != server2IPAddress)
&& (server2IPAddress != "")) {
InsertUploadedTrancasctionDetails(server2IPAddress,
deviceId, XMLTransactionData);
}
}
}
} catch (Exception exception) {
initialTransaction.put("ReceivedDate",
RevisedEstimatedDate);
initialTransaction.put("TransactionData",
XMLTransactionData);
dbAdapter.InsertRecord("tblTransaction", "",
initialTransaction);
}
dbAdapter.close();
LoadDeliveries(pkManifest);
}
The Problem is that i need to update the data to the server that stored in the tbltransaction automatically when we get connection to the serverIP along with my running application.I think it is possible by means of establishing backround running process along with my application that will check whethere data is there in the tbltransaction and connection with server is there.
So will any one have an idea for this ...if so please help meee...........
Here are a couple of methods that together will do just this. This is all within a Service, you could use a Handler instead and do this within an activity, but a Service is a wiser choice.
First, we need to be able to tell if we're online, this requires Network State and Wifi State Permissions:
public boolean isOnline() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
return false;
}
}
Next we need to be able to set an alarm to retry. Add these variables:
private static AlarmManager am;
private static PendingIntent pIntent;
public static final int MSG_UPDATE = 0;
public static final String PENDING_REQ_KEY = "request";
And a set alarm method:
private synchronized void setAlarm() {
if (am == null) am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
if (Constants.LOG_DEBUG) Log.d(TAG,"Setting Alarm for 5 mins");
long delay = 300000L; //5 Mins
Intent i = new Intent(this,Service.class); //Reference the Service this method is in
i.putExtra(PENDING_REQ_KEY, MSG_UPDATE);
pIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC,System.currentTimeMillis()+delay,pIntent);
}
Next, Override the onStartCommand method, to capture the update request:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getExtras() != null && intent.getExtras().containsKey(PENDING_REQ_KEY)) {
int request = intent.getExtras().getInt(PENDING_REQ_KEY);
if (request == MSG_UPDATE) update();
}
return START_STICKY;
}
finally, your update method:
public void update() {
if (isOnline()) {
/** Push data to server here */
}
else {
setAlarm();
}
}
I want to join two cursors so that the contents of the second Cursor shall also appear in first Cursor after joining.
Precisely here is my code,
public final Uri AllImage_URI_Int = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
public final Uri AllAudio_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cContentList = managedQuery(AllImage_URI_Int, null, null, null, MediaStore.Images.ImageColumns.TITLE);
cList_Int = managedQuery(AllImage_URI, null, null, null, MediaStore.Images.ImageColumns.TITLE);
Should i use the CursorJoiner in this case?
I want to pass this Cursor to SimpleListAdapter? How can i join those two cursors?
Maybe you can use a MergeCursor wrapper to merge your two Cursors into a new one, and pass it to your Adapter.
well, i solved it myself and working, extendeb by AbstractCursor, heres the code,
private final int ROWCACHESIZE = 64;
private int mRowNumCache[] = new int[ROWCACHESIZE];
private int mCursorCache[] = new int[ROWCACHESIZE];
private int mCurRowNumCache[][];
private int mLastCacheHit = -1;
public SortCursor(Cursor[] cursors, String sortcolumn)
{
mCursors = cursors;
int length = mCursors.length;
mSortColumns = new int[length];
for (int i = 0 ; i < length ; i++) {
if (mCursors[i] == null) continue;
mCursors[i].moveToFirst();
// We don't catch the exception
mSortColumns[i] = mCursors[i].getColumnIndexOrThrow(sortcolumn);
}
mCursor = null;
String smallest = "";
for (int j = 0 ; j < length; j++) {
if (mCursors[j] == null || mCursors[j].isAfterLast())
continue;
String current = mCursors[j].getString(mSortColumns[j]);
if (mCursor == null || current.compareToIgnoreCase(smallest) < 0) {
smallest = current;
mCursor = mCursors[j];
}
}
for (int i = mRowNumCache.length - 1; i >= 0; i--) {
mRowNumCache[i] = -2;
}
mCurRowNumCache = new int[ROWCACHESIZE][length];
}