Android for loop List - android

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;
}

Related

How to sort 10 most called numbers from the list of called numbers with counter

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+"");

Expression wanted instead of ContentValues

I have this code:
private void saveBoard(){
Card tmp;
int n = cardBoard.length;
for(int i = 0; i < n/2; i++) {
for(int j = 0; j < n/2; j++) {
tmp = cardBoard[i][j];
ContentValues values = new ContentValues();
values.put(Constants.ENTRY_COLUMN_POSITIONX, i);
values.put(Constants.ENTRY_COLUMN_POSITIONY, j);
values.put(Constants.ENTRY_COLUMN_VALUE, tmp.getValue());
}
}
Uri uri = context.getContentResolver().insert(BoardContentProvider.CONTENT_URL, values);
Toast.makeText(context, "New Diary-entry Added", Toast.LENGTH_SHORT).show();
}
I'm following this example code:
public void addDiaryEntry(View v) {
String title = mTitle.getText().toString();
String content = mContent.getText().toString();
if(title.isEmpty()) {
mTitle.setError(getText(R.string.error_empty_title));
} else if(content.isEmpty()) {
mContent.setError(getText(R.string.error_empty_content));
} else {
ContentValues values = new ContentValues();
values.put(Constants.ENTRY_COLUMN_TITLE, title);
values.put(Constants.ENTRY_COLUMN_CONTENT, content);
Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //format it as per your requirement
String dateNow = formatter.format(currentDate.getTime());
values.put(Constants.ENTRY_COLUMN_RECORD_DATE, dateNow);
Uri uri = getContentResolver().insert(DiaryContentProvider.CONTENT_URL, values);
Toast.makeText(getBaseContext(), "New Diary-entry Added", Toast.LENGTH_SHORT).show();
goToShowDiaries();
}
}
The main difference is, my class extends from GridLayout, and the class from example code extends AppCompatActivity.
The problem is this line:
Uri uri = context.getContentResolver().insert(BoardContentProvider.CONTENT_URL, values);
It doesn't take values as an argument, it wants an expression. What is the proper way to do this? I want to insert something in a db.
It can't reach the values variable. U have to put this line:
ContentValues values = new ContentValues();
Outside the for-loop.
Like this:
public void saveBoard(){
Card tmp;
int n = cardBoard.length;
ContentValues values = new ContentValues();
for(int i = 0; i < n/2; i++) {
for(int j = 0; j < n/2; j++) {
tmp = cardBoard[i][j];
values.put(Constants.ENTRY_COLUMN_POSITIONX, i);
values.put(Constants.ENTRY_COLUMN_POSITIONY, j);
values.put(Constants.ENTRY_COLUMN_VALUE, tmp.getValue());
}
}
Uri uri = context.getContentResolver().insert(BoardContentProvider.CONTENT_URL, values);
Toast.makeText(context, "New Diary-entry Added", Toast.LENGTH_SHORT).show();
}

Achartengine Line Graph

I'm using Achartengine to create a Line Graph. My current month is showing however the second line, last month, isn't showing it. Here's the lass and logcat: So as you can see from the logcat my dates are correct and so is the count from the previous month. So why its not showing is beyond me.
Log Cat:
08-07 16:13:43.969: I/PROJECTCARUSO(11734): DEBUG startdate: 2013-07-01 enddate: 2013-07-31
08-07 16:13:43.969: I/PROJECTCARUSO(11734): count: 9
08-07 16:13:43.979: I/PROJECTCARUSO(11734): DEBUG startdate: 2013-08-01 enddate: 2013-08-31
Class:
public class TempHistoryFragment extends Fragment{
private GraphicalView mChartView;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String month_name = month_date.format(cal.getTime());
ArrayList<Integer> xArray = new ArrayList<Integer>();
ArrayList<Integer> yArray = new ArrayList<Integer>();
ArrayList<Integer> xArray2 = new ArrayList<Integer>();
ArrayList<Integer> yArray2 = new ArrayList<Integer>();
cal.add(Calendar.MONTH ,-1);
String prev_month_name = month_date.format(cal.getTime());
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//***********************************************//
// Our first data Last MONTH
//***********************************************//
//start date for cursor
//cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE, 1);
String startdate = df.format(cal.getTime());
//end date
cal.set(Calendar.DATE, daysInMonth);
String enddate = df.format(cal.getTime());
Log.i("PROJECTCARUSO","DEBUG startdate: " + startdate + " enddate: " + enddate);
Cursor c = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, "? < " + StatusData.KEY_CHARTING_DATE + " AND ? > " + StatusData.KEY_CHARTING_DATE , new String[] {startdate, enddate}, null); //
c.moveToFirst();
Log.i("PROJECTCARUSO","count: " + c.getCount());
if (c.getCount()>0 && c!=null) {
while (c.isAfterLast() == false) {
if ((isNumeric(c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE))))) {
java.util.Date date = null;
int day = 0;
//get date from database
String datetest = c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_DATE));
//try to reformat to date.
try {
date = format.parse(datetest);
day = date.getDate();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xArray.add(day);
}
c.moveToNext();
}
}
int[] x = new int[xArray.size()];
for (int i = 0; i < xArray.size(); i++) {
x[i] = xArray.get(i);
}
int[] y = new int[yArray.size()];
for (int i = 0; i < yArray.size(); i++) {
y[i] = yArray.get(i);
}
TimeSeries series = new TimeSeries(prev_month_name);
for( int i = 0; i < y.length; i++)
{
series.add(x[i], y[i]);
}
//***********************************************//
// Our second data THIS MONTH
//***********************************************//
//start date for cursor
cal2.set(Calendar.DATE, 1);
String startdate2 = df.format(cal2.getTime());
//end date
cal2.set(Calendar.DATE, daysInMonth);
String enddate2 = df.format(cal2.getTime());
Log.i("PROJECTCARUSO","DEBUG startdate: " + startdate2 + " enddate: " + enddate2);
Cursor c2 = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, "? < " + StatusData.KEY_CHARTING_DATE + " AND ? > " + StatusData.KEY_CHARTING_DATE , new String[] {startdate2, enddate2}, null); //
c2.moveToFirst();
if (c2.getCount()>0 && c2!=null) {
while (c2.isAfterLast() == false) {
if (isNumeric(c2.getString(c2.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE)))){
yArray2.add(c2.getInt(c2.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE)));
java.util.Date date = null;
int day = 0;
//get date from database
String datetest = c2.getString(c2.getColumnIndex(StatusData.KEY_CHARTING_DATE));
//try to reformat to date.
try {
date = format.parse(datetest);
day = date.getDate();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xArray2.add(day);
}
c2.moveToNext();
}
}
int[] x2 = new int[xArray2.size()];
for (int i = 0; i < xArray2.size(); i++) {
x2[i] = xArray2.get(i);
}
int[] y2 = new int[yArray2.size()];
for (int i = 0; i < yArray2.size(); i++) {
y2[i] = yArray2.get(i);
}
TimeSeries series2 = new TimeSeries(month_name);
for( int i = 0; i < x2.length; i++)
{
series2.add(x2[i], y2[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(series2);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
XYSeriesRenderer renderer2 = new XYSeriesRenderer(); // This will be used to customize line 2
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(renderer2);
// Customization time for line 1!
renderer.setColor(getResources().getColor(R.color.complementary));
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
// Customization time for line 2!
renderer2.setColor(getResources().getColor(R.color.base));
renderer2.setPointStyle(PointStyle.DIAMOND);
renderer2.setFillPoints(true);
mChartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);
//Set Chart Title and labels
mRenderer.setChartTitle("Temperature Tracking");
mRenderer.setChartTitleTextSize(getResources().getDimension(R.dimen.largeText));
mRenderer.setLabelsColor(getResources().getColor(R.color.primaryTextDark));
//YAxis of Temp
mRenderer.setYTitle("Temperature", 0);
mRenderer.setYAxisMin(80, 0);
mRenderer.setYAxisMax(110, 0);
mRenderer.setYLabelsAlign(Align.CENTER);
mRenderer.setYLabelsColor(0, getResources().getColor(R.color.primaryTextDark));
//XAxis of month
mRenderer.setXLabels(20);
mRenderer.setXTitle(month_name);
mRenderer.setXAxisMin(1);
mRenderer.setXAxisMax(daysInMonth);
mRenderer.setXLabelsColor(getResources().getColor(R.color.primaryTextDark));
//Set the display
mRenderer.setMarginsColor(getResources().getColor(R.color.transparent));
mRenderer.setShowCustomTextGrid(true);
mRenderer.setAxisTitleTextSize(getResources().getDimension(R.dimen.mediumText));
mRenderer.setLabelsTextSize(getResources().getDimension(R.dimen.smallMediumText));
mRenderer.setPanEnabled(false, false);
mRenderer.setClickEnabled(false);
mRenderer.setZoomEnabled(false, false);
return mChartView;
}
#SuppressWarnings("unused")
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
Oh and here are those colors:
<color name ="base">#51bbc2</color>
<color name ="complementary">#C25951</color>
Thanks #Dan you lead me to the solution. I went and logged all the points to make sure all the right values were getting placed in the right array and come to find out yArray.add(c.getInt(c.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE))); somehow got deleted. So now it works! Yay!

reading sms records from database android

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();

Add the contents of one Cursor to another Cursor

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];
}

Categories

Resources