This question has already been answered:
- Exception NetworkOnMainThreadException 1 response
First attempts to use AsyncTask . It seems everything should work, but for some reason - no.
I decided to create an inner extends AsyncTask class in the class I extends AsyncTask , and from it I can call the class I need with the method using the connection.
But something went wrong approx.
public class Converter { private SQLiteDatabase database; private Strategy strategy; private Map<String, Currency> currencies; public Converter(SQLiteDatabase database) { this.database = database; strategy = new Strategy(); } public void process() { } public void prepareDB() { // ContentValues contentValues = new ContentValues(); currencies = new DBConnection().doInBackground(); } private class DBConnection extends AsyncTask<Void, Void, Map<String, Currency>> { @Override protected Map<String, Currency> doInBackground(Void... voids) { return new Strategy().getCurrencies(); } } } Strategy class:
public class Strategy { private Map<String, Currency> currencies = new HashMap<>(); private final String URL_FORMAT = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=%s"; private static final String USER_AGENT = "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"; private static final String REFERRER = "none"; protected Document getDocument() throws Exception { return Jsoup.connect(String.format(URL_FORMAT, getDate())).userAgent(USER_AGENT).referrer(REFERRER).get(); } public static String getDate() { return "11/11/2011"; // return new SimpleDateFormat("dd/MM/yyyy").format(new Date()); } public Map<String, Currency> getCurrencies() { Map<String, Currency> map = new HashMap<>(); Document document = null; try { document = getDocument(); Log.d("process", "document created"); String e = document.getElementsByAttributeValue("class", "data").get(0).getElementsByTag("td").text(); // System.out.println(e); StringTokenizer stringTokenizer = new StringTokenizer(e, " "); while (stringTokenizer.hasMoreTokens()) { String validToken = stringTokenizer.nextToken(); if (validToken.length() == 3 && areDigits(validToken)) { Currency currency = new Currency(); currency.setdCode(validToken); currency.setCode(stringTokenizer.nextToken()); currency.setForAmount(Integer.parseInt(stringTokenizer.nextToken())); String s = null; while (true) { if ((s = stringTokenizer.nextToken()).matches("^[0-9,]+$")) break; } currency.setRate(Double.parseDouble(s.replace(",", "."))); currency.setDate(getDate()); map.put(currency.getdCode(), currency); Log.d("adding to array", currency.toString()); } } } catch (Exception e) { Log.d("exception", "catched"); e.printStackTrace(); } return map; } private boolean areDigits(String validToken) { char[] ch = validToken.toCharArray(); for (char c : ch) if (!Character.isDigit(c)) return false; return true; } } The method that throws NetworkOnMainThreadException:
protected Document getDocument() throws Exception { return Jsoup.connect(String.format(URL_FORMAT, getDate())).userAgent(USER_AGENT).referrer(REFERRER).get(); } StackTrace:
04-23 08:07:34.443 30209-30209/? E/libprocessgroup: failed to make and chown /acct/uid_10062: Read-only file system 04-23 08:07:34.443 30209-30209/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT? 04-23 08:07:34.443 30209-30209/? I/art: Not late-enabling -Xcheck:jni (already on) 04-23 08:07:34.532 30209-30209/? I/InstantRun: Starting Instant Run Server for com.xpendence.development.currencyconvarter 04-23 08:07:34.866 30209-30209/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable 04-23 08:07:35.061 30209-30209/? D/exception: catched 04-23 08:07:35.061 30209-30209/? W/System.err: android.os.NetworkOnMainThreadException 04-23 08:07:35.061 30209-30209/? W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) 04-23 08:07:35.061 30209-30209/? W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:418) 04-23 08:07:35.061 30209-30209/? W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) 04-23 08:07:35.061 30209-30209/? W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215) 04-23 08:07:35.061 30209-30209/? W/System.err: at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106) 04-23 08:07:35.062 30209-30209/? W/System.err: at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:651) 04-23 08:07:35.062 30209-30209/? W/System.err: at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:628) 04-23 08:07:35.062 30209-30209/? W/System.err: at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:260) 04-23 08:07:35.062 30209-30209/? W/System.err: at org.jsoup.helper.HttpConnection.get(HttpConnection.java:249) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.xpendence.development.currencyconverter.operations.Strategy.getDocument(Strategy.java:22) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.xpendence.development.currencyconverter.operations.Strategy.getCurrencies(Strategy.java:34) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.xpendence.development.currencyconverter.operations.Converter$DBConnection.doInBackground(Converter.java:38) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.xpendence.development.currencyconverter.operations.Converter.prepareDB(Converter.java:30) 04-23 08:07:35.062 30209-30209/? W/System.err: at com.xpendence.development.currencyconverter.MainActivity.onCreate(MainActivity.java:28) 04-23 08:07:35.062 30209-30209/? W/System.err: at android.app.Activity.performCreate(Activity.java:5990) 04-23 08:07:35.062 30209-30209/? W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 04-23 08:07:35.063 30209-30209/? W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) 04-23 08:07:35.063 30209-30209/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 04-23 08:07:35.063 30209-30209/? W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151) 04-23 08:07:35.063 30209-30209/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 04-23 08:07:35.063 30209-30209/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102) 04-23 08:07:35.063 30209-30209/? W/System.err: at android.os.Looper.loop(Looper.java:135) 04-23 08:07:35.063 30209-30209/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254) 04-23 08:07:35.063 30209-30209/? W/System.err: at java.lang.reflect.Method.invoke(Native Method) 04-23 08:07:35.063 30209-30209/? W/System.err: at java.lang.reflect.Method.invoke(Method.java:372) 04-23 08:07:35.063 30209-30209/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 04-23 08:07:35.063 30209-30209/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 04-23 08:07:35.072 30209-30244/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true [ 04-23 08:07:35.075 30209:30209 D/ ] HostConnection::get() New Host Connection established 0xb434c370, tid 30209 04-23 08:07:35.085 30209-30209/? D/Atlas: Validating map... 04-23 08:07:35.132 30209-30244/? I/OpenGLRenderer: Initialized EGL, version 1.4 04-23 08:07:35.132 30209-30244/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... 04-23 08:07:35.139 30209-30244/? D/OpenGLRenderer: Enabling debug mode 0 It is interesting not only to understand what I am doing wrong, but also to see the implementation in order to build on it later and not distract the respected Connoisseurs.