0

I have two processes running in parallel and the same read and write operations on the same database. So I want to take them to a asynctask, so they sync with each other .But in the process of implementation, has generated an error that I do not know how fix expect people to help. when you run the application to the new sync (). execute (); error

 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.invoice);
 doTimerTask();
}

public void workoffline()
{
    clearArray();
    try {
        mDb.openDB();
        Cursor mCursor = mDb.getAllInvoice(IDDelivery);
        if (mCursor.moveToFirst()) {
            do {
                codeInvoiceArray.add(mCursor.getString(1));
                nameArray.add(mCursor.getString(2));
                phonenumberArray.add(mCursor.getString(3));
                addressArray.add(mCursor.getString(4));
                urlArray.add(mCursor.getString(5));

            } while (mCursor.moveToNext());
            loaddatalistview();
        }
        mDb.closeDB();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

// lấy dữ liệu từ server về thiết bị
public void loaddata()
{

    String sampleURL = SERVICE_URL + "/monthlytarget.php";
    CallUrl wst = new CallUrl(CallUrl.GET_TASK, this, "Lấy thông tin hóa đơn...", 1, IDDelivery);
    wst.execute(new String[] {
            sampleURL
    });

    // Hiển thị thông tin nhận được lên listview

}

private class sync extends AsyncTask<Void, Void, Void>
{

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        loaddata();
        return null;
    }

    @Override
    protected void onPostExecute(final Void unused) {
        // TODO Auto-generated method stub
        workoffline();
    }

}

// kiểm tra thiết bị có kết nối mạng hay không?
// nếu có thiết bị sẽ làm việc online
// nếu không thiết bị sẽ chuyển sang hoạt động offline
public void testNetwork()
{
    // Kiểm tra kết nối đến server
    TestConnectionNew test = new TestConnectionNew();
    try {
        String recieve = test.execute("http://longvansolution.tk/monthlytarget.php").get();
        if (recieve.equalsIgnoreCase("true") && isNetworkAvailable() == true)
        {

           //loaddata();
           // workoffline();
            new sync().execute();
        }
        else if (recieve.equalsIgnoreCase("false") || isNetworkAvailable() == false)
        {
            String mess = "Không thể kết nối đến server hoặc thiết bị chưa có kết nối mạng!";
            Toast.makeText(Invoice.this, mess, Toast.LENGTH_SHORT).show();
            workoffline();
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

// thực hiện load data từ server về theo thời gian định sẵn
public void doTimerTask() {
    TimerTask mTimerTask;
    Timer t = new Timer();
    final Handler handler = new Handler();
    mTimerTask = new TimerTask() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    testNetwork();
                    Log.d("TIMER", "TimerTask run");
                }
            });
        }
    };
    // public void schedule (TimerTask task, long delay, long period)
    t.schedule(mTimerTask, 500, 300000); //
}

error

12-21 14:43:54.750: E/AndroidRuntime(11093): FATAL EXCEPTION: AsyncTask #4
12-21 14:43:54.750: E/AndroidRuntime(11093): java.lang.RuntimeException: An error occured while    executing doInBackground()
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at      java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at java.lang.Thread.run(Thread.java:856)
12-21 14:43:54.750: E/AndroidRuntime(11093): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.os.Handler.<init>(Handler.java:121)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.app.Dialog.<init>(Dialog.java:107)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.app.AlertDialog.<init>(AlertDialog.java:114)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.app.AlertDialog.<init>(AlertDialog.java:98)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at Url.CallUrl.showProgressDialog(CallUrl.java:289)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at Url.CallUrl.onPreExecute(CallUrl.java:300)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.os.AsyncTask.execute(AsyncTask.java:511)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at com.longvan.saigonfleamarket.Invoice.loaddata(Invoice.java:240)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at com.longvan.saigonfleamarket.Invoice$sync.doInBackground(Invoice.java:254)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at com.longvan.saigonfleamarket.Invoice$sync.doInBackground(Invoice.java:1)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-21 14:43:54.750: E/AndroidRuntime(11093):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
Takeshi Pham
  • 61
  • 1
  • 7

4 Answers4

0

Is CallUrl trying to show a ProgressDialog? If so, you cannot do that from AsyncTask's doInBackground method. Have a look at the publishProgress method instead.

Docs here.

Adrián Rodríguez
  • 1,836
  • 15
  • 16
  • That won't work. He is executing an `AsyncTask` from another `AsyncTask` `doInBackground(...)` method. This means the second `AsyncTask`methods which normally run on the UI thread are actually running on the first `AsyncTask` worker thread which does the work for its `doInBackGround` method. The exception is caused because the second `AsyncTask` is trying to show a progress dialog in its `onPreExecute` method. – Squonk Dec 21 '12 at 08:14
0

Create a PorgressDialog before calling the Async task and after you finish executing the Async task dismiss the PorgressDialog. This will solve your problem. Check here here , here and here here

kumar
  • 691
  • 1
  • 7
  • 16
  • the problem here is in the class CallUrl required used PorgressDialog, because there is much activity and use this class. – Takeshi Pham Dec 21 '12 at 08:19
0

You'll have to run the UI interactions in the UI thread. Try doing

runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    //your UI interaction code here

                }
            });

This will execute the code in the UI thread.

Tharaka Devinda
  • 1,952
  • 21
  • 23
0

From your UI thread (default) you are creating a TimerTask thread, and from within that you are creating a Runnable (thread), and from within that you are creating an AsyncTask thread. In the midst of this, you have a Toast call:

Toast.makeText(Invoice.this, mess, Toast.LENGTH_SHORT).show();

(You can't access the UI thread directly from another thread like this; try a handler.)

I believe some simplification is in order; here are some excellent examples that should help:

AsyncTask and Looper.prepare() error

Can't create handler inside thread that has not called Looper.prepare() - AsyncTask inside a dialog

Java Can't create handler inside thread that has not called Looper.prepare()

Timer & TimerTask versus Thread + sleep in Java

Community
  • 1
  • 1
CodeShane
  • 6,480
  • 1
  • 18
  • 24