Wrote an application for obtaining exchange rates from the RBC website. Everything works except for updating data through the adapter in the listView. When I launch an application with Wi-Fi turned on, the actual data is displayed on the screen. If WiFi is turned off, start the application, accordingly the ListView will be empty, but when WiFi is connected, the list is not updated. I will be glad to any help. Thank you in advance. I will give a partial code:

Manifesto:

<?xml version="1.0" encoding="utf-8"?> 

 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Adapter:

 public class CustomAdapter extends BaseAdapter { private Context ctx; private ArrayList<CurrencyRateModel> arrayList; private LayoutInflater inflater; public CustomAdapter(Context ctx, ArrayList<CurrencyRateModel> arrayList) { this.ctx = ctx; this.arrayList = arrayList; inflater = ((Activity)ctx).getLayoutInflater(); } @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //TextView tv = (TextView)convertView; // For debug /* if(convertView == null) { tv = new TextView(ctx); } tv.setText("позиция =" + position);*/ ViewHolder vh; if(convertView == null) { vh = new ViewHolder(); convertView = inflater.inflate(R.layout.activity_get_currency_rates, null); vh.tvTitle = (TextView)convertView.findViewById(R.id.title); vh.tvDescription = (TextView)convertView.findViewById(R.id.description); vh.tvConvertedData = (TextView)convertView.findViewById(R.id.converted); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } CurrencyRateModel item = arrayList.get(position); vh.tvTitle.setText(item.getName()+" - "+item.getCharCode()); vh.tvDescription.setText("Курс сегодня: "+ String.format("%.2f Р", item.getValue()) + " Предыдущий: " + String.format("%.2f Р",item.getPrevious())); vh.tvConvertedData.setText("Конвертированные данные: " + String.format("%.2f Р", item.getRate())); return convertView; } static class ViewHolder { TextView tvTitle, tvDescription, tvConvertedData; }} 

Maine:

 public class MainActivity extends AppCompatActivity { // Get data from RBC https://www.cbr-xml-daily.ru/daily_json.js // Currency data private ArrayList<CurrencyRateModel> listOfCurrency; private CustomAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // async TASK Run registerReceiver(new WifiReceiver(), new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); GetRbcExchangeRates async = new GetRbcExchangeRates(); async.execute(); } ICustomCallback myCallback = new ICustomCallback() { @Override public void resultValue(double value) { Toast.makeText(MainActivity.this, "value: " + value, Toast.LENGTH_LONG).show(); for(int i = 0, size = listOfCurrency.size(); i < size; i++) { CurrencyRateModel item = listOfCurrency.get(i); item.setRate(item.getValue() * value / item.getNominal()); } myAdapter.notifyDataSetChanged(); //myAdapter.notifyDataSetInvalidated(); Мгновенное обновление; } }; private class GetRbcExchangeRates extends AsyncTask<String, String, String> { // private ArrayList<CurrencyRateModel> listOfCurrency = new ArrayList<>(); @Override protected String doInBackground(String... params) { HttpURLConnection connection = null; BufferedReader bufferedReader = null; StringBuilder jSonResult = new StringBuilder(); try { URL url = new URL("https://www.cbr-xml-daily.ru/daily_json.js"); connection = (HttpURLConnection)url.openConnection(); connection.connect(); bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = ""; while((line = bufferedReader.readLine()) != null) { jSonResult.append(line); } } catch(Exception e) { e.printStackTrace(); publishProgress("MESSAGE", "Отсутствует подключение к интернет!"); } finally { if(connection != null) connection.disconnect(); try { if(bufferedReader !=null) bufferedReader.close(); } catch(IOException e) { e.printStackTrace(); } } listOfCurrency = new ArrayList<>(); try { JSONObject rbcGETRates = new JSONObject(jSonResult.toString()); JSONObject jSonValute = rbcGETRates.getJSONObject("Valute"); Iterator<String> arrayKey = jSonValute.keys(); while(arrayKey.hasNext()) { String key = arrayKey.next(); JSONObject jSonItem = jSonValute.getJSONObject(key); CurrencyRateModel currencyitems = new CurrencyRateModel(); currencyitems.setId(jSonItem.getString("ID")); currencyitems.setNameCode(jSonItem.getString("NumCode")); currencyitems.setCharCode(jSonItem.getString("CharCode")); currencyitems.setNominal(jSonItem.getInt("Nominal")); currencyitems.setName(jSonItem.getString("Name")); currencyitems.setValue(jSonItem.getDouble("Value")); currencyitems.setPrevious(jSonItem.getDouble("Previous")); listOfCurrency.add(currencyitems); } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); if(values[0].equals("MESSAGE")) { Toast.makeText(MainActivity.this, values[1], Toast.LENGTH_LONG).show(); } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); ListView lsView = (ListView)findViewById(R.id.currencyView); myAdapter = new CustomAdapter(MainActivity.this, listOfCurrency); lsView.setAdapter(myAdapter); lsView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { FragmentManager fgManager = getSupportFragmentManager(); ValueInputDialog dialog = new ValueInputDialog(); dialog.inputValueDialogInit(myCallback); dialog.show(fgManager, ""); } }); } } public class WifiReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (netInfo != null && netInfo.isConnected()) Log.d("WifiReceiver", "Have Wifi Connection"); if(listOfCurrency == null && listOfCurrency.size() == 0) { GetRbcExchangeRates getRbcExchangeRates = new GetRbcExchangeRates(); getRbcExchangeRates.execute(); } else Log.d("WifiReceiver", "Don't have Wifi Connection"); } }} 

    1 answer 1

    In general, managed to implement it. To begin with, I changed the manifest:

     <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> 

    BroadcastReceiver:

      public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isConnected = wifi != null && wifi.isConnectedOrConnecting() || mobile != null && mobile.isConnectedOrConnecting(); if (isConnected) { // Тут и запускаю Async c обновлением списка GetRbcExchangeRates async = new GetRbcExchangeRates(); async.execute(); Toast.makeText(context, "YES", Toast.LENGTH_SHORT).show(); Log.d(TAG, "YES"); } else { Toast.makeText(context, "NO", Toast.LENGTH_SHORT).show(); Log.d(TAG, "NO"); } } } 

    I register event in MainActivity:

     @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerReceiver(new NetworkChangeReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } 

    Now, if you start the application with WiFi turned off, and then turn it on. The list is updated automatically.