简体   繁体   中英

Updating One ListView From Two Different AsyncTask

I have an activity (MainActivity) that has an inner AsyncTask class. This class gets local wireless configurations like: ip address, subnet, gateway etc. I have an external Asynctask that gets external ip configuration. like ip address, hostname, location etc. the second class uses a json rest api for this. But when I post to the listview from second class I'm not able to. I don't know if this is possible. I pass the current context to second class and use WeakReferences in case the main activity terminates. Also, I'm using a custom array adapter for the listview. from what I understand doinbackground() method run in different threads so how synchronization happens between these two classes. An alternate solution I was thinking instead of posting directly into the listview from second class is to store in a variable on mainclass and then output to listview from 1st asynctask. but that gives unexpected results. How is this done. has any one done something similar before? thanks Note: I remmoved some import from mainactivity otherwise class was going to take too space here. Main Activity

package org.techgeorge.netxcan;
import org.apache.commons.net.util.SubnetUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import utils.IpUtils;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private ArrayList<String> wifiIface;
    private WifiAdapter wifiAdapter;
    private String TAG = this.getClass().getName();
    private String extIpv6;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        wifiIface = new ArrayList<>();

        listView = (ListView) findViewById(R.id.output_list);
        wifiAdapter = new WifiAdapter(this, R.layout.list_item, wifiIface);
        listView.setAdapter(wifiAdapter);

        WifiAsyncTask wifiTask = new WifiAsyncTask(this);
        wifiTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        getWanIpInfo();

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void setExtIpv6(String ipv6) {
        this.extIpv6 = ipv6;
    }

    public ArrayList<String> getWifiIface() {
        return wifiIface;
    }

    public ArrayAdapter<String> getArrayAdapter() {
        return wifiAdapter;
    }

    public void getWanIpInfo() {
        WanIpTask wanIpTask = new WanIpTask(this);
        wanIpTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    public class WifiAsyncTask extends AsyncTask<Void, Void, Void> {
        WeakReference<MainActivity> weakReference;
        private static final String WEB_IP_SERVICE = "https://ipinfo.io/json";
        String error = "Couldn't get external IP";
        int subnet;
        Wireless wifi;

        public WifiAsyncTask(MainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        protected void onPreExecute() {
            wifi = new Wireless(getApplicationContext());
            wifi.getInternalMobileIpAddress();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                if ( wifi.getNetworkInfo() != null && wifi.getNetworkInfo().isConnected()) {
                    adding Lan stuff
                    subnet = wifi.getInternalWifiSubnet();
                    wifiIface.add("LAN Information");
                    wifiIface.add("Ipv6 "+wifi.getIpv6());
                    wifiIface.add("Mac "+wifi.getMacAddress());
                    wifiIface.add("Ipv4 "+wifi.getWifiInetAddress().getHostAddress()+"/"+subnet);
                    wifiIface.add("Host "+wifi.getWifiInetAddress().getHostName());
                    wifiIface.add("Dns1 "+IpUtils.getIpToString(wifi.getDhcpInfo().dns1));
                    wifiIface.add("Dns2 "+IpUtils.getIpToString(wifi.getDhcpInfo().dns2));
                    wifiIface.add("Gateway "+IpUtils.getIpToString(wifi.getDhcpInfo().gateway));

                    //adding wireless stuff
                    wifiIface.add("WIFI Information");
                    wifiIface.add("SSID "+wifi.getSSID());
                    wifiIface.add("Speed "+wifi.getLinkSpeed()+ "Mbs");
                    wifiIface.add("Signal "+wifi.getWifiInfo().getRssi() + "db");
                    wifiIface.add("Channel "+wifi.getWifiInfo().getNetworkId() + "");

                    }
                }
            } catch (Wireless.NoConnectivityManagerException e) {
                e.printStackTrace();
            } catch (Wireless.NoWifiManagerException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (Wireless.NoWifiInterface noWifiInterface) {
                noWifiInterface.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            wifiAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onPostExecute(Void... values) {
            MainActivity activity = weakReference.get();
            if(activity != null || !activity.isFinishing()) {
                wifiAdapter.notifyDataSetChanged();
            }
        }

    }
}

WanAsynTask

package org.techgeorge.netxcan;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WanIpTask extends AsyncTask<Void, Void, String> {

    // IP service is 100% open source https://github.com/aaronjwood/public-ip-api
//    private static final String EXTERNAL_IP_SERVICE = "https://public-ip-api.appspot.com/";
    private static final String EXTERNAL_IP_SERVICE = "https://ipinfo.io/json";
    private final WeakReference<MainActivity> delegate;

    /**
     * Constructor to set the delegate
     *
     * @param delegate Called when the external IP has been fetched
     */
    public WanIpTask(MainActivity delegate) {
        this.delegate = new WeakReference<>(delegate);
    }

    /**
     * Fetch the external IP address
     *
     * @param params
     * @return External IP address
     */
    @Override
    @SuppressLint("NewApi")
    protected String doInBackground(Void... params) {
        String error = "Couldn't get external IP";
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder().url(EXTERNAL_IP_SERVICE).build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                return error;
            }
            return response.body().string().trim();
        } catch (IOException e) {
            return error;
        }
    }

    /**
     * Calls the delegate when the external IP has been fetched
     *
     * @param result External IP address
     */
    @Override
    protected void onPostExecute(String result) {
        MainActivity activity = delegate.get();
        if (activity != null) {
            activity.getWifiIface().add(result);
            String[] wanResult = result.split("\n");
            for(int i = 0; i < wanResult.length; i++) {
                activity.getWifiIface.add()
            }            
        }
    }
}

In WanAsynTask you are not not updating adapter

@Override
protected void onPostExecute(String result) {
    MainActivity activity = delegate.get();
    if (activity != null) {
        activity.getWifiIface().add(result);
        String[] wanResult = result.split("\n");
        for(int i = 0; i < wanResult.length; i++) {
            activity.getWifiIface.add()
        }  
        // notify adapter    
        activity.wifiAdapter.notifyDataSetChanged();

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM