Exception android.view.WindowManager$BadTokenException: Unable to add window - java

I get this error every once in a while and not sure how to fix it. I read that the context could be destroyed but no REAL answers on how to solve it, especially for my situation.
The error happens below on Utility.showDialog in the onPostExecute on my BaseLoadOperation. What is the correct way to handle this?
DataTask.java
public class DataTask extends BaseLoadOperation {
public DataTask(Context context) {
super(context);
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
Utility.showDialog(this.context.getString(R.string.connectionerror), "OK", this.context);
}
Utility.java
public static void showDialog(String message, String buttonText, Context context, final IDialogCallback callback) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(buttonText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(callback != null)
{
callback.buttonPress();
}
}
});
AlertDialog alert = builder.show();
TextView messageText = (TextView)alert.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
alert.show();
}
Exception android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#49fff91 is not valid; is your activity running?
android.view.ViewRootImpl.setView (ViewRootImpl.java:900)
android.view.WindowManagerGlobal.addView (WindowManagerGlobal.java:342)
android.view.WindowManagerImpl.addView (WindowManagerImpl.java:97)
android.app.Dialog.show (Dialog.java:419)
android.support.v7.app.AlertDialog$Builder.show (AlertDialog.java:956)
com.exposure.utilities.Utility.showDialog (Utility.java:196)
com.exposure.utilities.Utility.showDialog (Utility.java:181)
com.exposure.utilities.DataTask.onPostExecute (DataTask.java:44)

Related

Cusum exit dialog in android

I want to create a custom exit dialog box with three images that images are fetching from server. Dialog is show if i click back button. Dialog is showed to me but images that are fetched from server are not shown, default images are showing. Image url is successfully getting from server. If i place that url in my imageView an exception is generated:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.madnanijaz.labassignment1, PID: 2967
java.lang.NullPointerException: Argument must not be null
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:27)
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:22)
at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:383)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:181)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:170)
My code of Back Pressed button is:
#Override
public void onBackPressed() {
//Fetching Images(Adds from server)
fetchingAddsFromServer();
//CustomAlertDialog
final AlertDialog.Builder builder=new
AlertDialog.Builder(MainActivity.this);
View view=
LayoutInflater.from(MainActivity.this).inflate(R.layout.row_layout,null);
builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setView(view);
builder.show();
// AlertDialog alertDialog=builder.create();
//alertDialog.show();
}
private void fetchingAddsFromServer() {
StringRequest request= new StringRequest(URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object= new JSONObject(response);
JSONArray jsonArray=object.getJSONArray("slots");
JSONObject jsonObject=jsonArray.getJSONObject(1);
Toast.makeText(MainActivity.this, "Image Url
is:"+jsonObject.getString("imgurl"), Toast.LENGTH_LONG).show();
// String ImgURI=jsonObject.getString("imgurl");
Glide.with(getApplicationContext()).load(jsonObject.getString("imgurl")).into(c
losingDialogImageTwo);
//}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue= Volley.newRequestQueue(MainActivity.this);
queue.add(request);
I think its an error of custom layout.I have one ImageView in main screen. if i use Glide with that it is working fine but if a use Glide with custom layout of dialog it gives me this error that is mentioned.
The following error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.madnanijaz.labassignment1, PID: 2967
java.lang.NullPointerException: Argument must not be null
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:27)
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:22)
at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:383)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:181)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:170)
happens because you're trying to loading the image to closingDialogImageTwo with this:
Glide.with(getApplicationContext()).load(jsonObject.getString("imgurl")).into(c losingDialogImageTwo);
but you haven't initialize the View yet. Because the image is inside the custom view for the dialog, you need to initialize it after you inflating the view. Which is after the following code:
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.row_layout,null);
with this:
ImageView closingDialogImageTwo = view.findViewById(R.id.your_image_id);
You need to load the image only after your fetchingAddsFromServer() method finished fetching the image because its asynchronous behaviour.
To summarize, you need to move your AlertDialog creation inside the fetchingAddsFromServer like this:
private void fetchingAddsFromServer() {
StringRequest request= new StringRequest(URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
...
// assuming you got the image.
String imageUrl = jsonObject.getString("imgurl");
showDialogWithImage(imageUrl);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue= Volley.newRequestQueue(MainActivity.this);
queue.add(request);
}
private void showDialogWithImage(String imageUrl) {
final AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.row_layout,null);
ImageView closingDialogImageTwo = view.findViewById(R.id.your_image_id);
Glide.with(getApplicationContext())
.load(imageUrl).into(closingDialogImageTwo);
builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setView(view);
builder.show();
}

AlertDialog is shown before methods insde thread finished Android Java

The first activity in the app checks if tables and data are loaded correctly before launching the main activity.
If not, it connects to server using volley and loads the data and images and then asks user to restart app.
The problem is: AlertDialog is shown with "message loading complete" directly before the methods finished loading.
I created a thread inside the onCreate method and put all methods inside it but the same problem persists.
My question is: How can I show the alertDialog after methods complete data loading?
Here is my code:
if(! (checkTables()&&checkData())){
progressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
fillSamples();
fillExams();
fillQuestions();
fillSubQuestions();
}
}).start();
progressDialog.dismiss();
AlertDialog.Builder builder=new AlertDialog.Builder(SplashScreen.this);
builder.setMessage("Loading Data Complete Please restart your App");
builder.setCancelable(false);
builder.setPositiveButton("Restart", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(1);
}
});
AlertDialog dialog=builder.create();
dialog.show();
}
Try to use AsyncTask instead of Thread. For more info Threads and AsyncTask
if(! (checkTables()&&checkData())){
GetData.execute();
}
class GetData extends AsyncTask<Void, Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Add your progress dialog.
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
AlertDialog.Builder builder=new AlertDialog.Builder(SplashScreen.this);
builder.setMessage("Loading Data Complete Please restart your App");
builder.setCancelable(false);
builder.setPositiveButton("Restart", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(1);
}
});
AlertDialog dialog=builder.create();
dialog.show();
}
}
#Override
protected Void doInBackground(Void... voids) {
fillSamples();
fillExams();
fillQuestions();
fillSubQuestions();
return null;
}
}

Getting user input from a dialog using Mortar + Flow

I'm build my app with Mortar + Flow. I'm trying to figure out the correct way to show a popup that requests some text from the user. I've created this popup class:
public class SavedPageTitleInputPopup implements Popup<SavedPageTitleInput, Optional<String>> {
private final Context context;
private AlertDialog dialog;
public SavedPageTitleInputPopup(Context context) {
this.context = context;
}
#Override public Context getContext() {
return context;
}
#Override
public void show(final SavedPageTitleInput info, boolean withFlourish,
final PopupPresenter<SavedPageTitleInput, Optional<String>> presenter) {
if (dialog != null) throw new IllegalStateException("Already showing, can't show " + info);
final EditText input = new EditText(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setText(info.savedPage.getName());
dialog = new AlertDialog.Builder(context).setTitle(info.title)
.setView(input)
.setMessage(info.body)
.setPositiveButton(info.confirm, new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface d, int which) {
dialog = null;
final String newTitle = Strings.emptyToNull(String.valueOf(input.getText()));
presenter.onDismissed(Optional.fromNullable(newTitle));
}
})
.setNegativeButton(info.cancel, new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface d, int which) {
dialog = null;
presenter.onDismissed(Optional.<String>absent());
}
})
.setCancelable(true)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override public void onCancel(DialogInterface d) {
dialog = null;
presenter.onDismissed(Optional.<String>absent());
}
})
.show();
}
#Override public boolean isShowing() {
return dialog != null;
}
#Override public void dismiss(boolean withFlourish) {
dialog.dismiss();
dialog = null;
}
}
This class works as expected. It uses the SavedPage to figure out what to display in the dialog and it returns the users input to the PopupPresenter using PopupPresenter#onDismissed when the correct button is pressed.
My problem is writing the PopupPresenter subclass used to present the dialog and process the input. This is what I have right now:
new PopupPresenter<SavedPage, Optional<String>>() {
#Override protected void onPopupResult(Optional<String> result) {
if (result.isPresent()) {
// The user entered something, so update the API
// Oh wait, I don't have a reference to the SavedPage
// that was displayed in the dialog!
}
}
}
As the comments say, I don't have a reference to the SavedPage that was displayed in the dialog. It was stored in the whatToShow field in PopupPresenter, but this field is nulled out right before onPopupResult is called. It seems like I would be unnecessarily repeating myself to keep an additional copy of the SavedPage.
There isn't a lot of documentation yet on PopupPresenter and Popup. The only thing I have seen is a basic example in the sample project. They create a ConfirmerPopup based on data within the Confirmation object. The purpose of the ConfirmerPopup is to capture a boolean decision from the user based on the title/body given to the Confirmation object as seen by the class declaration.
public class ConfirmerPopup implements Popup<Confirmation, Boolean> {
In your case you want to capture additional user inputted text from the user. When PopupPresenter#onPopupResult is called the result object should contain all of the data needed from SavedPageTitleInputPopup. Modify your SavedPageTitleInputPopup as follows
public class SavedPageTitleInputPopup implements Popup<SavedPage, SavedPageResults> {
private final Context context;
private AlertDialog dialog;
public SavedPageTitleInputPopup(Context context) {
this.context = context;
}
#Override public Context getContext() {
return context;
}
#Override
public void show(SavedPage info, boolean withFlourish, final PopupPresenter<SavedPage, SavedPageResults> presenter) {
if (dialog != null) throw new IllegalStateException("Already showing, can't show " + info);
// Create your Dialog but scrape all user data within OnClickListeners
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
//Anything else you need to do... .setView() or .setTitle() for example
builder.setPositiveButton(info.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog = null;
//Save data to SavedPageResults
final SavedPageResults results = new SavedPageResults():
presenter.onDismissed(results);
}
});
builder.setNegativeButton(info.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog = null;
final SavedPageResults results = new SavedPageResults();
presenter.onDismissed(results);
}
});
dialog = builder.show();
}
#Override public boolean isShowing() {
return dialog != null;
}
#Override public void dismiss(boolean withFlourish) {
dialog.dismiss();
dialog = null;
}
}
Your PopupPresenter doesn't need to know anything about the Dialog's implementation now.
new PopupPresenter<SavedPage, SavedPageResults>() {
#Override protected void onPopupResult(SavedPageResults result) {
if (result.isPresent()) {
updateUi(result.getSavedText());
}
}
}

How to force user to deal with dialog before allowing access to activity? AND What's wrong with my licensing code?

Ok so I recently completed an android app - my first one :D! - and because it is a paid app Google tells me I have to add the licensing stuff. That's fine and dandy, except I've been getting mind f*cked by it for the past five hours. Finally think I understand it a little and got it going, but in testing it in my emulator I come up with two issues:
I'm using the google API for 4.1, as instructed by their handy how-to on the developer console, but nomatter what I always end up coming up with my Connection Error dialog. Code here:
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
And cooresponding dialog being called:
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
My first question: How come it isn't connecting to the server as it should be? I've constructed my testing apratus as instructed by their tutorial. I've gone over it three times!
Second question: When I do launch the app on the emulator, the Connection Error dialog shows up fine. I hit retry, and it works. I hit Cancel, and it kills the app. However, if I simply click anywhere else in the window, outside the dialog, it closes the dialog and the app works normally. That kindof defeats the whole purpose, eh? How do I make that... not so?
Just in case I'm an idiot and the error lies elsewhere, here's the whole class:
private static final int DIALOG_RETRY = 10;
private static final int DIALOG_ERROR=20;
private static final byte[] SALT = {1,2,3,4,5,6,72,88,-37,-55,-23,34,22,14,15,16,17,18,19,-20};
private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqvh1xrNmvio909T06vAUxW3rtc98E3xNLA6qR/zdq2zHNW tQUJkDmJGukrkWj4Vd38NiD+nW92MX3HY2/dfw4AIcwS2oyeYceYc3hi4y2KeVL84y3DrOO0fCKNqBr6/Ve0cefN9HVyy57Psl4B0y8OaG9500xuEUeguO+PyIAMqFrtHVyi/seimnrcYLTYJo9IfGTRhcwi6QqQE8OlplidaT+uYwR4hNfcNLbnWnr7xDeG5gL2usibFPg+cvhFVhIGKO/aFuAVUIH2Yoarudc888X3/ZjTbmYAGuGhS8GRxiHhTVknCznX3BcxBJNeMA+xPTZ4OnaryRkHVvoJx5WQIDAQAB";
private LicenseCheckerCallback checkerCB;
private LicenseChecker checker;
TextView title, description, cure;
ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//LICENSING
checkerCB = new CallBack();
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
checker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(),tm.getDeviceId())),
BASE64_PUBLIC_KEY);
checker.checkAccess(checkerCB);
//END LICENSING
setContentView(R.layout.activity_main);
title = (TextView)findViewById(R.id.title);
description = (TextView)findViewById(R.id.description);
image = (ImageView)findViewById(R.id.image);
cure =(TextView)findViewById(R.id.cure);
Spinner dropdown = (Spinner)findViewById(R.id.mainMenu);
//List Menu Items
final String options[] = {
//TURF DISEASES
"-Turf Diseases-", "Dollar Spot","Red Thread","Pythium Blight", "Necrotic Ring","Summer Patch","Brown Patch","Fairy Ring"
,"White Patch","Rust"
//TURF INSECTS
,"-Turf Insects-","Chinch Bug","Army Worm","Hunting Billbug","Aphid","Black Cutworm","Leaf Hopper","White Grub"
//ORNAMENTAL DISEASES
,"-Ornamental Diseases-","Powdery Mildew","Leaf Spot"
//ORNAMENTAL INSECTS
,"-Ornamental Insects-","Aphid","Leaf Miner","Japanese Beatle","Spider Mites","White Fly","Euonymus Scale","Web Worm"
};
//End List Menu Items
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,options);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
newSelection(options[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void newSelection(String selection){
if(!selection.contains("-")){
title.setText(selection);
selection=selection.replace(" ", "_");
selection=selection.toUpperCase();
description.setText(getResourceID("DESC_"+selection, R.string.class));
image.setImageResource(getResourceID(selection.toLowerCase(), R.drawable.class));
}else{
title.setText("Select a disease or insect.");
description.setText("");
cure.setText("");
image.setImageResource(getResourceID("logo", R.drawable.class));
}
}
#SuppressWarnings("rawtypes")
public int getResourceID(String name, Class resType){
try{
Class res = null;
if(resType == R.drawable.class)
res=R.drawable.class;
if(resType==R.id.class)
res=R.id.class;
if(resType==R.string.class)
res=R.string.class;
java.lang.reflect.Field field = res.getField(name);
int retID = field.getInt(null);
return retID;
}catch(Exception e){
}return 0;
}
protected void onResume() {
newSelection("-");
super.onPause();
}
protected void onDestroy(){
super.onDestroy();
checker.onDestroy();
}
//LICENSING CALLBACK CLASS
private class CallBack implements LicenseCheckerCallback{
public void allow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Granted");
}
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
}
//DIALOG CLASS AND ACTION LISTENERS
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
}
For your second question, I would set setCanceledOnTouchOutside to false like so:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
//Add this
dialog.setCanceledOnTouchOutside(false);
dialog.show();

Unable to add window error in Android [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application"
I've tried different things, but I still keep the same error:
android.view.WindowManager$BadTokenException: Unable to add window
At this line:
alertDialog.show();
Can you look at the code?
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
Context mContext = this;
alertDialog = new AlertDialog.Builder(mContext).create();
LoadData();
}
public void LoadData()
{
Thread t1 = new Thread(this);
t1.start();
}
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(!rssItems.isEmpty())
{
switch (msg.what) {
case STOPSPLASH:
//remove SplashScreen from view
//splash.setVisibility(View.GONE);
Intent intent = new Intent(
"news.displayNews");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
NewsDisplayer.rssItems.clear();
NewsDisplayer.rssItems.addAll(rssItems);
startActivity(intent);
Close();
break;
}
}
else
{
alertDialog.setCancelable(false); // This blocks the 'BACK' button
alertDialog.setMessage("No connection.");
alertDialog.setTitle("Error...");
alertDialog.setButton("Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
LoadData();
}
});
alertDialog.setButton2("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
System.exit(0);
}
});
alertDialog.show();
}
}
};
This is because the context you are using to create the alertDialog doesn't support it. So instead of mContext, try getParent() or getApplicationContext(). That might work.
I think that's because you're running this in a thread. alertDialog.show(); has to be executed on the UI thread. Try using an AsyncTask instead.
EDIT: my bad, I didn't read carefully the code.

Categories