0

Here, first my application syncs data from server when the data is synchronized to local database I query one table to retrieve its data and from I get uri of picture and I use another background task to download user picture to my sd card and Since my main background thread is boolean type so I am not able to call functionality to fetch image from there itself. If I call method from postexecute then I get NetworkOnMainthread exception I am stuck in condition where I need to use safe thread below is code

protected void onPreExecute() {
    mDialog = ProgressDialog.show(viewContext, "", "Synchronizing Data",
            true);

};

/*
 * (non-Javadoc)
 * 
 * @see android.os.AsyncTask#doInBackground(Params[])
 */
@Override
protected Boolean doInBackground(Void... arg0) {
    if (type.contains("ferry")) {
        return SynchronizeRepositoryFerry(false);

    } else {
        return SynchronizeRepositories(false, initialSync);
    }
}

/*
 * (non-Javadoc)
 * 
 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
 */
@Override
protected void onPostExecute(Boolean result) {
    this.syncComplete = result;
    mDialog.dismiss();
    if (type.contains("Dash")) {
        new BackgroundTask().execute();
    }
    else{
        Intent intent = new Intent();
        intent.setClass(viewContext, classType);
        viewContext.startActivity(intent);

    }


}

class BackgroundTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog mDialog;

    protected void onPreExecute() {
        mDialog = ProgressDialog.show(viewContext, "", "Loading Images",
                true);
    };

    @Override
    protected Void doInBackground(Void... params) {
        try {
            int id = 0;
            String url = "http://i.zdnet.com/blogs/3-29-androids.jpg";
            com.jumbybay.businessobjects.User user = new com.jumbybay.businessobjects.User();
            DatabaseHelper dbHelper = new DatabaseHelper(viewContext);
            IUserRepository repository = dbHelper.getUserRepository();
            List<com.jumbybay.businessobjects.User> imageList;
            try {
                imageList = repository.Retrieve();
                for (int i = 0; i < imageList.size(); i++) {
                    user = imageList.get(i);
                    // url = user.getPicture();
                    id = user.getId();
                    savesd(id, url);

                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (final Exception e) {

        }
        return null;
    }

    public void savesd(int id, String uri) throws IOException {
        URL url;
        if (uri == null) {
            url = new URL("http://i.zdnet.com/blogs/3-29-androids.jpg");
        } else {
            url = new URL(uri);
        }
        InputStream input = url.openStream();
        try {
            File storagePath = Environment.getExternalStorageDirectory();
            OutputStream output = new FileOutputStream(new File(
                    storagePath, +id + ".jpg"));

            try {
                byte[] buffer = new byte[20000];
                int bytesRead = 0;
                while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, bytesRead);
                }
            } finally {
                output.close();
            }
        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            input.close();
        }

    }

    protected void onPostExecute(Void result) {
        mDialog.dismiss();
        Intent intent = new Intent();
        /*
         * intent.setClass(viewContext, classType);
         * viewContext.startActivity(intent);
         */

        intent.setClass(viewContext, classType);
        viewContext.startActivity(intent);

    };
}
Sourabh Saldi
  • 3,567
  • 6
  • 34
  • 57

2 Answers2

1
@Override
    protected Boolean doInBackground(Void... arg0) {
        if (type.contains("ferry")) {
            return SynchronizeRepositoryFerry(false);

        } else {
            SynchronizeRepositories(false, initialSync);
            com.jumbybay.businessobjects.User user = new com.jumbybay.businessobjects.User();
            DatabaseHelper dbHelper = new DatabaseHelper(viewContext);
            IUserRepository repository = dbHelper.getUserRepository();
            List<com.jumbybay.businessobjects.User> imageList;
            try {
                int id;
                String url = "http://i.zdnet.com/blogs/3-29-androids.jpg";
                imageList = repository.Retrieve();
                for (int i = 0; i < imageList.size(); i++) {
                    user = imageList.get(i);
                    // url = user.getPicture();
                    id = user.getId();
                    savesd(id, url);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block// url = user.getPicture();
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        return SynchronizeRepositories(false, initialSync);
    }
Sourabh Saldi
  • 3,567
  • 6
  • 34
  • 57
0

There are two Solution of this Problem but first one is great solution.

1) Don't write network call in Main UI Thread, Use Async Task for that.

2) Write below code into your MainActivity file after setContentView(R.layout.activity_main); but this is not proper way.

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

And below import statement into your java file.

import android.os.StrictMode;

And see below link for more information.

Caused by: android.os.NetworkOnMainThreadException

Community
  • 1
  • 1
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128