I have a ListActivity
. Each time it starts, a AsyncTask
runs to scan my IP address and displays the result in ListActivity
. Everything works fine. But if I create a options menu (android 2.3) then my IP address doesn't be displayed in ListActivity
. The AsyncTask
still works ok and the options menu display correctly when I click on the menu button. No error occurs, the ListActivity
just don't display the IP. Here's my code:
public class MyIP extends ListActivity
{
ArrayList <Device> devicesList = new ArrayList<Device>();
AdapterListDevices adapter;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(android.R.id.list);
registerForContextMenu(listView);
adapter = new AdapterListDevices(MyIP.this, R.layout.row_list_devices, devicesList);
setListAdapter(adapter);
scanMyDevice();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo)
{
// Some code
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
// Some code
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.myip_options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Some code
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// Some code
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
// Some code
}
public void updateListAdapter(Device myDevice)
{
devicesList.add(myDevice);
adapter.notifyDataSetChanged();
}
public void scanMyDevice()
{
ScanMyDeviceTask smd = new ScanMyDeviceTask(MyIP.this);
smd.execute();
}
}
Here my ScanMyDeviceTask:
public class ScanMyDeviceTask extends AsyncTask <Void, Void, Void>
{
Context context;
ProgressDialog progDialog;
Device myDevice;
InetAddress myAddress;
public ScanMyDeviceTask(Context context)
{
this.context = context;
progDialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute()
{
progDialog.setTitle("Searching...");
progDialog.setProgressStyle(progDialog.STYLE_SPINNER);
progDialog.show();
}
@Override
protected Void doInBackground(Void... params)
{
//Scan the ip address here
}
@Override
protected void onPostExecute(Void params)
{
MyIP act = (MyIP) context;
act.updateListAdapter(myDevice);
PublicData pd = (PublicData) act.getApplication();
pd.setMyIp(myAddress.getAddress());
progDialog.dismiss();
}
}
Put a
try-catch
block around your code inscanMyDevice()
like this:If an exception is thrown in your
AsyncTask
your activity might not crash. Then you will see the behavior you described - everything seems to be working normally.So adding the code above will help you see if there is an exception that happens there or not.