0

I am new to Android and having a hard time to implement the following code without UI freeze. I tried to use a new thread, but it doesn't give feedback (at least I don't know how to get it) when loop is finished. My code looks like this (excerpt):

public class FilterSettingsActivity extends AppCompatActivity {
private String SMSMsgs = "";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_filter_settings);
    listSMSs(false);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_preview:

           listSMSs(true);

          //execute after loop completetion
            Intent i = new Intent(FilterSettingsActivity.this, PreviewSmsActivity.class);
            i.putExtra("SMSMsgs",SMSMsgs);
            startActivity(i);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

public void listSMSs(Boolean write){

    Cursor cur = getContentResolver().query(uriSMS, null, getSelection(fromDate,toDate,thread_id),getArgs(fromDate,toDate,thread_id),"thread_id");
    String sms =  cur.getCount()+" SMS found";

    if(write==true) {

        // this code stucks UI
        while (cur.moveToNext()) {
            Long d = Long.parseLong(cur.getString(cur.getColumnIndex("date"))); //for retrieve readable date, time
            String PhoneNumber = cur.getString(cur.getColumnIndex("address"));

            SMSMsgs += "At :"+ millisToDate(d) +" From :" + getContactName(FilterSettingsActivity.this,PhoneNumber)+" "+ cur.getString(cur.getColumnIndex("address"))+" : " + "\n"
                    + cur.getString(cur.getColumnIndex("body"))+"\n"+"\n";
        }
    }
    final TextView textView = (TextView) findViewById(R.id.tvStatus);
    textView.setText(sms);
  }

}

Can anyone help on how to implement AsyncTask or new Thread on Cursor queries? Thank you.

Edit: The problem here is that cursor has to be inside the asynctask class and has to receive several arguments (strings, arrays of strings) from outside functions and activities to do its job. These functions and activities are not presented in code example. If arrays of strings can be passed as params in doInBackground function, then quoted solution is applicable, otherwise this question is not a duplicate.

Gruiberg
  • 66
  • 8

1 Answers1

0

You can use CursorLoader to implement this which takes care of loading data asynchronously

refer this https://developer.android.com/reference/android/content/CursorLoader.html

http://www.theappguruz.com/blog/use-android-cursorloader-example

arjun
  • 3,514
  • 4
  • 27
  • 48
  • Thanks for suggestion. However, cursor is not the performance issue, it returns almost instantly with results after cur.getCount() . The loop: while (cur.moveToNext()) is :( – Gruiberg Feb 01 '17 at 18:01