0

I am using onNewIntent when I am scanning NFC tags. I want to show ProgressDialog while tag is scanned. I tried use a thread but it crashed my app. Is there some way how I can show progressDialog when onNewIntent starts?

public void onNewIntent(Intent intent) {
        setIntent(intent);
        Thread scanning = new Thread(new Runnable() {
            public void run() {
                ScanDialog = ProgressDialog.show(BorrowActivity.this,
                        "Scanning...", "scanning");
            }
        });
        scanning.start();
              .
              . //next code doing something
              .
}
Matwosk
  • 459
  • 1
  • 9
  • 25
  • "When the tag is scanned", basically the tag is already scanned when your application receives the intent, so I assume you're talking about parsing ? – Daneo Apr 25 '14 at 08:51
  • Yes actually I am talking about parsing but my app also communicate with server and then write some data to tag. This process takes a few seconds. Thats why I need to show progressDialog. – Matwosk Apr 25 '14 at 11:41

2 Answers2

0

You cannot update or use a UI on another thread:

solution:

Call the Main thread and update the UI inside there

    Thread scanning = new Thread(new Runnable() {
        public void run() {
            runOnUiThread(new Runnable() 
            {
               public void run() 
               {
                    ScanDialog = ProgressDialog.show(BorrowActivity.this,
                        "Scanning...", "scanning");
               }
            });

        }
 });
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
  • I tried also this way and it is still crasing my app. However if I don't use thread it will just freeze screen for few seconds but finally doesn't crash and works correctly. – Matwosk Apr 25 '14 at 00:56
0

Finally I fixed it with asyncTask.

public void onNewIntent(Intent intent) {
    setIntent(intent);
        ScanDialog = ProgressDialog.show(BorrowActivity.this,
                "Scanning...", "Scanning");

        try {
        new DoBackgroundTask().execute();
        } catch (Exception e) {
             //error catch here
        }
        ScanDialog.dismiss();

And AsyncTask:

private class DoBackgroundTask extends AsyncTask<Integer, String, Integer> {

    protected Integer doInBackground(Integer... status) {
     //do something
    }
    protected void onProgressUpdate(String... message) {
    }
    protected void onPostExecute(Integer status) {
    }
}
Matwosk
  • 459
  • 1
  • 9
  • 25