I'm trying to create a custom dialog using onCreateContextMenu
and onContextItemSelected
. so when a user select the context menu it creates a dialog.
I'm using this code when a user select the first element:
if(item.getItemId() == 0) {
try {
imageUrl = new URL(UrlSprite);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
final Dialog d = new Dialog(ctx);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setCancelable(true);
d.setContentView(R.layout.popupsprite);
TextView titulo = (TextView)d.findViewById(R.id.pkmnNombre);
titulo.setText(Constantes.Pokemon[numero-1]);
ImageView image = (ImageView)d.findViewById(R.id.spritePopup);
image.setImageBitmap(loadedImage);
d.show();
} catch (IOException e) {
e.printStackTrace();
}
}
But when I click the application closes. It only happens in Android 3.0+, in earlier versions, like 2.1, 2.2, 2.3, the popup shows correctly.
Any ideas?
Thanks.
final Dialog d = new Dialog(ctx);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setCancelable(true);
d.setContentView(R.layout.popupsprite);
TextView titulo = (TextView)d.findViewById(R.id.pkmnNombre);
titulo.setText(Constantes.Pokemon[numero-1]);
ImagenSprite = (ImageView)d.findViewById(R.id.spritePopup);
attachImage(UrlSprite, ImagenSprite);
d.show();
And
public void attachImage(final String fileUrl, final ImageView view) {
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
final Bitmap image = downloadImg(fileUrl);
if (image != null) {
view.post(new Runnable() {
@Override
public void run() {
view.setImageBitmap(image);
}
});
}
}
Bitmap downloadImg(String imgUrl) {
try {
URL imageUrl = new URL(imgUrl);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return loadedImage;
}
});
}
You are running network related operation on the ui thread
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.connect();
You should use a Thread
or AsyncTask
. You will get NetworkOnMainThreadException
post honeycomb
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html .
So create your own thread and do network related operation there or use Asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
In addition to Raghunandan use DialogFragment
instead, I think its deprecated for Android 4.0+ ( As a side note ).
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.