Example usage for android.app AlertDialog.Builder setInverseBackgroundForced

List of usage examples for android.app AlertDialog.Builder setInverseBackgroundForced

Introduction

In this page you can find the example usage for android.app AlertDialog.Builder setInverseBackgroundForced.

Prototype

public void setInverseBackgroundForced(boolean forceInverseBackground) 

Source Link

Usage

From source file:com.abc.driver.MainActivity.java

public void chooseTruckType(View v) {
    mTTtv = (TextView) this.findViewById(R.id.truck_type_tv);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    GridView gridView1 = new GridView(this);
    gridView1.setNumColumns(3);//  ww  w .  j  a  v  a2s . com
    // (GridView)findViewById(R.id.gridView1);
    SimpleAdapter adapter = new SimpleAdapter(this, mTruckTypeList, R.layout.truck_type_griditem,
            new String[] { "PIC", "TITLE", "TTYPE" },
            new int[] { R.id.griditem_pic, R.id.griditem_title, R.id.griditem_type, });

    gridView1.setAdapter(adapter);
    builder.setTitle("Please Choose");
    builder.setInverseBackgroundForced(true);
    builder.setView(gridView1);
    final Dialog dialog = builder.create();

    gridView1.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
            mTTtv.setText(((TextView) view.findViewById(R.id.griditem_title)).getText());
            mTruckType = ((TextView) view.findViewById(R.id.griditem_type)).getText().toString();
            dialog.dismiss();
        }
    });
    dialog.show();
}

From source file:com.abc.driver.MainActivity.java

public void chooseCargoType(View v) {
    mCTtv = (TextView) this.findViewById(R.id.cargo_type_tv);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    GridView gridView1 = new GridView(this);
    gridView1.setNumColumns(3);/*w w w .j  ava 2  s .c  om*/
    // (GridView)findViewById(R.id.gridView1);
    SimpleAdapter adapter = new SimpleAdapter(this, mCargoTypeList, R.layout.cargo_type_griditem,
            new String[] { "PIC", "TITLE", "CTYPE" },
            new int[] { R.id.griditem_pic, R.id.griditem_title, R.id.griditem_type, });

    gridView1.setAdapter(adapter);
    builder.setTitle("Please Choose");
    builder.setInverseBackgroundForced(true);
    builder.setView(gridView1);
    final Dialog dialog = builder.create();

    gridView1.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
            // doing something in here and then close
            mCTtv.setText(((TextView) view.findViewById(R.id.griditem_title)).getText());
            mCargoType = ((TextView) view.findViewById(R.id.griditem_type)).getText().toString();
            dialog.dismiss();
        }
    });
    dialog.show();
}

From source file:com.morlunk.mumbleclient.servers.ServerEditFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
    Settings settings = Settings.getInstance(getActivity());

    String actionName;//from   w w  w . java 2  s.  com
    switch (getAction()) {
    case ADD_ACTION:
        actionName = getString(R.string.add);
        break;
    case EDIT_ACTION:
        actionName = getString(R.string.edit);
        break;
    case CONNECT_ACTION:
        actionName = getString(R.string.connect);
        break;
    default:
        throw new RuntimeException("Unknown action " + getAction());
    }
    adb.setPositiveButton(actionName, null);
    adb.setNegativeButton(android.R.string.cancel, null);

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    View view = inflater.inflate(R.layout.dialog_server_edit, null, false);

    TextView titleLabel = (TextView) view.findViewById(R.id.server_edit_name_title);
    mNameEdit = (EditText) view.findViewById(R.id.server_edit_name);
    mHostEdit = (EditText) view.findViewById(R.id.server_edit_host);
    mPortEdit = (EditText) view.findViewById(R.id.server_edit_port);
    mUsernameEdit = (EditText) view.findViewById(R.id.server_edit_username);
    mUsernameEdit.setHint(settings.getDefaultUsername());
    mPasswordEdit = (EditText) view.findViewById(R.id.server_edit_password);

    Server oldServer = getServer();
    if (oldServer != null) {
        mNameEdit.setText(oldServer.getName());
        mHostEdit.setText(oldServer.getHost());
        mPortEdit.setText(String.valueOf(oldServer.getPort()));
        mUsernameEdit.setText(oldServer.getUsername());
        mPasswordEdit.setText(oldServer.getPassword());
    }

    if (shouldIgnoreTitle()) {
        titleLabel.setVisibility(View.GONE);
        mNameEdit.setVisibility(View.GONE);
    }

    // Fixes issues with text colour on light themes with pre-honeycomb devices.
    adb.setInverseBackgroundForced(true);

    adb.setView(view);

    return adb.create();
}

From source file:com.irccloud.android.activity.MainActivity.java

void editTopic() {
    ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(buffer.bid);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
    View view = getDialogTextPrompt();
    TextView prompt = (TextView) view.findViewById(R.id.prompt);
    final EditText input = (EditText) view.findViewById(R.id.textInput);
    input.setText(c.topic_text);/*from   w  w w . ja  va 2s. c om*/
    prompt.setVisibility(View.GONE);
    builder.setTitle("Channel Topic");
    builder.setView(view);
    builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            conn.topic(buffer.cid, buffer.name, input.getText().toString());
            dialog.dismiss();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog dialog = builder.create();
    dialog.setOwnerActivity(this);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    dialog.show();
}

From source file:com.irccloud.android.activity.MainActivity.java

@Override
public void onFailedMessageClicked(EventsDataSource.Event event) {
    final EventsDataSource.Event e = event;
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
    builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
    builder.setMessage("This message could not be sent");
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override//from  w  ww . java2  s.com
        public void onClick(DialogInterface dialog, int which) {
            try {
                dialog.dismiss();
            } catch (IllegalArgumentException e) {
            }
        }
    });
    builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                pendingEvents.remove(e.reqid);
                e.pending = true;
                e.failed = false;
                e.bg_color = R.color.self;
                e.reqid = NetworkConnection.getInstance().say(e.cid, e.chan, e.command);
                if (e.reqid >= 0) {
                    pendingEvents.put(e.reqid, e);
                    e.expiration_timer = new TimerTask() {
                        @Override
                        public void run() {
                            if (pendingEvents.containsKey(e.reqid)) {
                                pendingEvents.remove(e.reqid);
                                e.failed = true;
                                e.bg_color = R.color.error;
                                e.expiration_timer = null;
                                NetworkConnection.getInstance().notifyHandlers(
                                        NetworkConnection.EVENT_BUFFERMSG, e, MainActivity.this);
                            }
                        }
                    };
                    if (countdownTimer != null)
                        countdownTimer.schedule(e.expiration_timer, 30000);
                }
                dialog.dismiss();
            } catch (IllegalArgumentException e) {
            }
        }
    });
    AlertDialog dialog = builder.create();
    dialog.setOwnerActivity(this);
    dialog.show();
}

From source file:com.irccloud.android.activity.MainActivity.java

private void show_topic_popup() {
    if (buffer == null)
        return;//  w  w w .j  a  va 2 s  .c o m
    ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(buffer.bid);
    if (c != null) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
        View v = getLayoutInflater().inflate(R.layout.dialog_topic, null);
        if (c.topic_text.length() > 0) {
            String author = "";
            if (c.topic_author != null && c.topic_author.length() > 0) {
                author = " Set by " + c.topic_author;
                if (c.topic_time > 0) {
                    author += " on " + DateFormat.getDateTimeInstance().format(new Date(c.topic_time * 1000));
                }
                v.findViewById(R.id.setBy).setVisibility(View.VISIBLE);
                ((TextView) v.findViewById(R.id.setBy)).setText(author);
            }
            ((TextView) v.findViewById(R.id.topic)).setText(ColorFormatter.html_to_spanned(
                    ColorFormatter.emojify(ColorFormatter.irc_to_html(TextUtils.htmlEncode(c.topic_text))),
                    true, server));
        } else {
            ((TextView) v.findViewById(R.id.topic)).setText("No topic set.");
        }
        if (c.mode.length() > 0) {
            v.findViewById(R.id.mode).setVisibility(View.VISIBLE);
            ((TextView) v.findViewById(R.id.mode)).setText("Mode: +" + c.mode);

            for (ChannelsDataSource.Mode m : c.modes) {
                switch (m.mode) {
                case "i":
                    v.findViewById(R.id.mode_i).setVisibility(View.VISIBLE);
                    break;
                case "k":
                    v.findViewById(R.id.mode_k).setVisibility(View.VISIBLE);
                    ((TextView) v.findViewById(R.id.key)).setText(m.param);
                    break;
                case "m":
                    v.findViewById(R.id.mode_m).setVisibility(View.VISIBLE);
                    break;
                case "n":
                    v.findViewById(R.id.mode_n).setVisibility(View.VISIBLE);
                    break;
                case "p":
                    v.findViewById(R.id.mode_p).setVisibility(View.VISIBLE);
                    break;
                case "s":
                    v.findViewById(R.id.mode_s).setVisibility(View.VISIBLE);
                    break;
                case "t":
                    v.findViewById(R.id.mode_t).setVisibility(View.VISIBLE);
                    break;
                }
            }
        }
        builder.setView(v);
        builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        boolean canEditTopic;
        if (c.hasMode("t")) {
            UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(buffer.bid, server.nick);
            canEditTopic = (self_user != null
                    && (self_user.mode.contains(server != null ? server.MODE_OPER : "Y")
                            || self_user.mode.contains(server != null ? server.MODE_OWNER : "q")
                            || self_user.mode.contains(server != null ? server.MODE_ADMIN : "a")
                            || self_user.mode.contains(server != null ? server.MODE_OP : "o")
                            || self_user.mode.contains(server != null ? server.MODE_HALFOP : "h")));
        } else {
            canEditTopic = true;
        }

        if (canEditTopic) {
            builder.setPositiveButton("Edit Topic", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    editTopic();
                }
            });
        }
        final AlertDialog dialog = builder.create();
        dialog.setOwnerActivity(MainActivity.this);
        dialog.show();

        ((TextView) v.findViewById(R.id.topic)).setMovementMethod(new LinkMovementMethod() {
            @Override
            public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
                if (super.onTouchEvent(widget, buffer, event) && event.getAction() == MotionEvent.ACTION_UP) {
                    dialog.dismiss();
                    return true;
                }
                return false;
            }
        });
    }
}

From source file:com.irccloud.android.activity.MainActivity.java

private void insertPhoto() {
    if (buffer == null)
        return;//  w  ww.jav  a2 s .co m

    AlertDialog.Builder builder;
    AlertDialog dialog;
    builder = new AlertDialog.Builder(this);
    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
    String[] items = (Build.VERSION.SDK_INT < 19 || !NetworkConnection.getInstance().uploadsAvailable())
            ? new String[] { "Take a Photo", "Choose Existing", "Start a Pastebin", "Pastebins" }
            : new String[] { "Take a Photo", "Choose Existing Photo", "Choose Existing Document",
                    "Start a Pastebin", "Pastebins" };
    if (NetworkConnection.getInstance().uploadsAvailable()) {
        items = Arrays.copyOf(items, items.length + 1);
        items[items.length - 1] = "File Uploads";
    }

    final String[] dialogItems = items;

    builder.setItems(dialogItems, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent i;
            if (buffer != null) {
                switch (dialogItems[which]) {
                case "Take a Photo":
                    try {
                        File imageDir = new File(Environment.getExternalStorageDirectory(), "IRCCloud");
                        imageDir.mkdirs();
                        new File(imageDir, ".nomedia").createNewFile();
                        imageCaptureURI = Uri
                                .fromFile(File.createTempFile("irccloudcapture", ".jpg", imageDir));
                        i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageCaptureURI);
                        startActivityForResult(i, REQUEST_CAMERA);
                    } catch (IOException e) {
                    }
                    break;
                case "Choose Existing":
                case "Choose Existing Photo":
                    i = new Intent(Intent.ACTION_GET_CONTENT,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("image/*");
                    startActivityForResult(Intent.createChooser(i, "Select Picture"), REQUEST_PHOTO);
                    break;
                case "Choose Existing Document":
                    i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("*/*");
                    startActivityForResult(Intent.createChooser(i, "Select A Document"), REQUEST_DOCUMENT);
                    break;
                case "Start a Pastebin":
                    show_pastebin_prompt();
                    break;
                case "Pastebins":
                    i = new Intent(MainActivity.this, PastebinsActivity.class);
                    startActivity(i);
                    break;
                case "File Uploads":
                    i = new Intent(MainActivity.this, UploadsActivity.class);
                    i.putExtra("cid", buffer.cid);
                    i.putExtra("to", buffer.name);
                    i.putExtra("msg", messageTxt.getText().toString());
                    startActivityForResult(i, REQUEST_UPLOADS);
                    break;
                }
            }
            dialog.dismiss();
        }
    });
    dialog = builder.create();
    dialog.setOwnerActivity(MainActivity.this);
    dialog.show();
}

From source file:com.irccloud.android.activity.MainActivity.java

@Override
public boolean onBufferLongClicked(final BuffersDataSource.Buffer b) {
    if (b == null)
        return false;

    ArrayList<String> itemList = new ArrayList<String>();
    final String[] items;
    ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid);

    if (buffer == null || b.bid != buffer.bid)
        itemList.add("Open");

    if (ChannelsDataSource.getInstance().getChannelForBuffer(b.bid) != null) {
        itemList.add("Leave");
        itemList.add("Display Options");
    } else {//  w  w w  . j a v a 2s .c o m
        if (b.type.equalsIgnoreCase("channel"))
            itemList.add("Join");
        else if (b.type.equalsIgnoreCase("console")) {
            if (s.status.equalsIgnoreCase("waiting_to_retry")
                    || (s.status.contains("connected") && !s.status.startsWith("dis"))) {
                itemList.add("Disconnect");
            } else {
                itemList.add("Connect");
                itemList.add("Delete");
            }
            itemList.add("Edit Connection");
        }
        if (!b.type.equalsIgnoreCase("console")) {
            if (b.archived == 0)
                itemList.add("Archive");
            else
                itemList.add("Unarchive");
            itemList.add("Delete");
        }
        if (!b.type.equalsIgnoreCase("channel")) {
            itemList.add("Display Options");
        }
    }
    itemList.add("Mark All As Read");

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
    if (b.type.equalsIgnoreCase("console"))
        builder.setTitle(s.name);
    else
        builder.setTitle(b.name);
    items = itemList.toArray(new String[itemList.size()]);
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int item) {
            AlertDialog.Builder builder;
            AlertDialog dialog;

            if (conn == null || b == null)
                return;

            if (items[item].equals("Open")) {
                onBufferSelected(b.bid);
            } else if (items[item].equals("Join")) {
                conn.join(b.cid, b.name, null);
            } else if (items[item].equals("Leave")) {
                conn.part(b.cid, b.name, null);
            } else if (items[item].equals("Archive")) {
                conn.archiveBuffer(b.cid, b.bid);
            } else if (items[item].equals("Unarchive")) {
                conn.unarchiveBuffer(b.cid, b.bid);
            } else if (items[item].equals("Connect")) {
                conn.reconnect(b.cid);
            } else if (items[item].equals("Disconnect")) {
                conn.disconnect(b.cid, null);
            } else if (items[item].equals("Display Options")) {
                if (b.type.equals("channel")) {
                    ChannelOptionsFragment newFragment = new ChannelOptionsFragment(b.cid, b.bid);
                    newFragment.show(getSupportFragmentManager(), "channeloptions");
                } else {
                    BufferOptionsFragment newFragment = new BufferOptionsFragment(b.cid, b.bid, b.type);
                    newFragment.show(getSupportFragmentManager(), "bufferoptions");
                }
            } else if (items[item].equals("Edit Connection")) {
                if (!getResources().getBoolean(R.bool.isTablet)) {
                    Intent i = new Intent(MainActivity.this, EditConnectionActivity.class);
                    i.putExtra("cid", b.cid);
                    startActivity(i);
                } else {
                    EditConnectionFragment editFragment = new EditConnectionFragment();
                    editFragment.setCid(b.cid);
                    editFragment.show(getSupportFragmentManager(), "editconnection");
                }
            } else if (items[item].equals("Mark All As Read")) {
                ArrayList<Integer> cids = new ArrayList<Integer>();
                ArrayList<Integer> bids = new ArrayList<Integer>();
                ArrayList<Long> eids = new ArrayList<Long>();

                for (BuffersDataSource.Buffer b : BuffersDataSource.getInstance().getBuffers()) {
                    if (b.unread == 1 && EventsDataSource.getInstance().lastEidForBuffer(b.bid) > 0) {
                        b.unread = 0;
                        b.highlights = 0;
                        b.last_seen_eid = EventsDataSource.getInstance().lastEidForBuffer(b.bid);
                        cids.add(b.cid);
                        bids.add(b.bid);
                        eids.add(b.last_seen_eid);
                    }
                }
                BuffersListFragment blf = (BuffersListFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.BuffersList);
                if (blf != null)
                    blf.refresh();
                conn.heartbeat(buffer.bid, cids.toArray(new Integer[cids.size()]),
                        bids.toArray(new Integer[bids.size()]), eids.toArray(new Long[eids.size()]));
            } else if (items[item].equals("Delete")) {
                builder = new AlertDialog.Builder(MainActivity.this);
                builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);

                if (b.type.equalsIgnoreCase("console"))
                    builder.setTitle("Delete Connection");
                else
                    builder.setTitle("Delete History");

                if (b.type.equalsIgnoreCase("console"))
                    builder.setMessage("Are you sure you want to remove this connection?");
                else if (b.type.equalsIgnoreCase("channel"))
                    builder.setMessage("Are you sure you want to clear your history in " + b.name + "?");
                else
                    builder.setMessage("Are you sure you want to clear your history with " + b.name + "?");

                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (b.type.equalsIgnoreCase("console")) {
                            conn.deleteServer(b.cid);
                        } else {
                            conn.deleteBuffer(b.cid, b.bid);
                        }
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.show();
            }
        }
    });

    AlertDialog dialog = builder.create();
    dialog.setOwnerActivity(this);
    dialog.show();
    return true;
}

From source file:com.irccloud.android.activity.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void showUserPopup(UsersDataSource.User user, Spanned message) {
    ArrayList<String> itemList = new ArrayList<String>();
    final String[] items;
    final Spanned text_to_copy = message;

    selected_user = user;/*from w ww .  j  a  va 2 s  . com*/

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);

    if (message != null) {
        if (message.getSpans(0, message.length(), URLSpan.class).length > 0)
            itemList.add("Copy URL");
        itemList.add("Copy Message");
    }

    if (selected_user != null) {
        itemList.add("Whois");
        itemList.add("Send a message");
        itemList.add("Mention");
        itemList.add("Invite to a channel");
        itemList.add("Ignore");
        if (buffer.type.equalsIgnoreCase("channel")) {
            UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(buffer.bid, server.nick);
            if (self_user != null && self_user.mode != null) {
                if (self_user.mode.contains(server != null ? server.MODE_OPER : "Y")
                        || self_user.mode.contains(server != null ? server.MODE_OWNER : "q")
                        || self_user.mode.contains(server != null ? server.MODE_ADMIN : "a")
                        || self_user.mode.contains(server != null ? server.MODE_OP : "o")) {
                    if (selected_user.mode.contains(server != null ? server.MODE_OP : "o"))
                        itemList.add("Deop");
                    else
                        itemList.add("Op");
                }
                if (self_user.mode.contains(server != null ? server.MODE_OPER : "Y")
                        || self_user.mode.contains(server != null ? server.MODE_OWNER : "q")
                        || self_user.mode.contains(server != null ? server.MODE_ADMIN : "a")
                        || self_user.mode.contains(server != null ? server.MODE_OP : "o")
                        || self_user.mode.contains(server != null ? server.MODE_HALFOP : "h")) {
                    itemList.add("Kick");
                    itemList.add("Ban");
                }
            }
        }
        itemList.add("Copy Hostmask");
    }

    items = itemList.toArray(new String[itemList.size()]);

    if (selected_user != null)
        if (selected_user.hostmask != null && selected_user.hostmask.length() > 0)
            builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")");
        else
            builder.setTitle(selected_user.nick);
    else
        builder.setTitle("Message");

    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int item) {
            if (conn == null || buffer == null)
                return;

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
            View view;
            final TextView prompt;
            final EditText input;
            AlertDialog dialog;

            if (items[item].equals("Copy Message")) {
                if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    clipboard.setText(text_to_copy);
                } else {
                    @SuppressLint("ServiceCast")
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    if (clipboard != null) {
                        android.content.ClipData clip = android.content.ClipData
                                .newPlainText("IRCCloud Message", text_to_copy);
                        clipboard.setPrimaryClip(clip);
                    } else {
                        Toast.makeText(MainActivity.this, "Unable to copy message. Please try again.",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                Toast.makeText(MainActivity.this, "Message copied to clipboard", Toast.LENGTH_SHORT).show();
            } else if (items[item].equals("Copy Hostmask")) {
                if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    clipboard.setText(selected_user.nick + "!" + selected_user.hostmask);
                } else {
                    @SuppressLint("ServiceCast")
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    android.content.ClipData clip = android.content.ClipData.newPlainText("Hostmask",
                            selected_user.nick + "!" + selected_user.hostmask);
                    clipboard.setPrimaryClip(clip);
                }
                Toast.makeText(MainActivity.this, "Hostmask copied to clipboard", Toast.LENGTH_SHORT).show();
            } else if (items[item].equals("Copy URL") && text_to_copy != null) {
                final ArrayList<String> urlListItems = new ArrayList<String>();

                for (URLSpan o : text_to_copy.getSpans(0, text_to_copy.length(), URLSpan.class)) {
                    String url = o.getURL();
                    url = url.replace(getResources().getString(R.string.IMAGE_SCHEME) + "://", "http://");
                    url = url.replace(getResources().getString(R.string.IMAGE_SCHEME_SECURE) + "://",
                            "https://");
                    if (server != null) {
                        url = url.replace(
                                getResources().getString(R.string.IRCCLOUD_SCHEME) + "://cid/" + server.cid
                                        + "/",
                                ((server.ssl > 0) ? "ircs://" : "irc://") + server.hostname + ":" + server.port
                                        + "/");
                    }
                    urlListItems.add(url);
                }
                if (urlListItems.size() == 1) {
                    if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                CLIPBOARD_SERVICE);
                        clipboard.setText(urlListItems.get(0));
                    } else {
                        @SuppressLint("ServiceCast")
                        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                                CLIPBOARD_SERVICE);
                        android.content.ClipData clip = android.content.ClipData
                                .newPlainText(urlListItems.get(0), urlListItems.get(0));
                        clipboard.setPrimaryClip(clip);
                    }
                    Toast.makeText(MainActivity.this, "URL copied to clipboard", Toast.LENGTH_SHORT).show();
                } else {
                    builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
                    builder.setTitle("Choose a URL");

                    builder.setItems(urlListItems.toArray(new String[urlListItems.size()]),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                                        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                                CLIPBOARD_SERVICE);
                                        clipboard.setText(urlListItems.get(i));
                                    } else {
                                        @SuppressLint("ServiceCast")
                                        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                                                CLIPBOARD_SERVICE);
                                        android.content.ClipData clip = android.content.ClipData
                                                .newPlainText(urlListItems.get(i), urlListItems.get(i));
                                        clipboard.setPrimaryClip(clip);
                                    }
                                    Toast.makeText(MainActivity.this, "URL copied to clipboard",
                                            Toast.LENGTH_SHORT).show();
                                }
                            });
                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialog = builder.create();
                    dialog.setOwnerActivity(MainActivity.this);
                    dialog.getWindow()
                            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    dialog.show();
                }
            } else if (items[item].equals("Whois")) {
                conn.whois(buffer.cid, selected_user.nick, null);
            } else if (items[item].equals("Send a message")) {
                conn.say(buffer.cid, null, "/query " + selected_user.nick);
            } else if (items[item].equals("Mention")) {
                if (!getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
                    Toast.makeText(MainActivity.this, "Double-tap a message to quickly reply to the sender",
                            Toast.LENGTH_LONG).show();
                    SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit();
                    editor.putBoolean("mentionTip", true);
                    editor.commit();
                }
                onUserDoubleClicked(selected_user.nick);
            } else if (items[item].equals("Invite to a channel")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("");
                prompt.setText("Invite " + selected_user.nick + " to a channel");
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.invite(buffer.cid, input.getText().toString(), selected_user.nick);
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            } else if (items[item].equals("Ignore")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("*!" + selected_user.hostmask);
                prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask");
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.ignore(buffer.cid, input.getText().toString());
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            } else if (items[item].equals("Op")) {
                conn.mode(buffer.cid, buffer.name,
                        "+" + (server != null ? server.MODE_OP : "o") + " " + selected_user.nick);
            } else if (items[item].equals("Deop")) {
                conn.mode(buffer.cid, buffer.name,
                        "-" + (server != null ? server.MODE_OP : "o") + " " + selected_user.nick);
            } else if (items[item].equals("Kick")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("");
                prompt.setText("Give a reason for kicking");
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.kick(buffer.cid, buffer.name, selected_user.nick, input.getText().toString());
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            } else if (items[item].equals("Ban")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("*!" + selected_user.hostmask);
                prompt.setText("Add a banmask for " + selected_user.nick);
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.mode(buffer.cid, buffer.name, "+b " + input.getText().toString());
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            }
            dialogInterface.dismiss();
        }
    });

    AlertDialog dialog = builder.create();
    dialog.setOwnerActivity(this);
    dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            MessageViewFragment mvf = (MessageViewFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.messageViewFragment);
            if (mvf != null)
                mvf.longPressOverride = false;
        }
    });
    dialog.show();
}

From source file:com.irccloud.android.activity.MainActivity.java

public void onIRCEvent(int what, Object obj) {
    super.onIRCEvent(what, obj);
    Integer event_bid = 0;/*w ww  .ja v a  2  s.  c  o m*/
    final IRCCloudJSONObject event;
    final Object o = obj;
    switch (what) {
    case NetworkConnection.EVENT_DEBUG:
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                errorMsg.setVisibility(View.VISIBLE);
                errorMsg.setText(o.toString());
            }
        });
        break;
    case NetworkConnection.EVENT_PROGRESS:
        final float progress = (Float) obj;
        if (progressBar.getProgress() < progress) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressBar.setIndeterminate(false);
                    progressBar.setProgress((int) progress);
                }
            });
        }
        break;
    case NetworkConnection.EVENT_BACKLOG_START:
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setProgress(0);
            }
        });
        break;
    case NetworkConnection.EVENT_RENAMECONVERSATION:
        if (buffer != null && (Integer) obj == buffer.bid) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    update_subtitle();
                }
            });
        }
        break;
    case NetworkConnection.EVENT_CHANNELTOPICIS:
        event = (IRCCloudJSONObject) obj;
        if (buffer != null && buffer.cid == event.cid()
                && buffer.name.equalsIgnoreCase(event.getString("chan"))) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    update_subtitle();
                    show_topic_popup();
                }
            });
        }
        break;
    case NetworkConnection.EVENT_LINKCHANNEL:
        event = (IRCCloudJSONObject) obj;
        if (event != null && cidToOpen == event.cid() && event.has("invalid_chan") && event.has("valid_chan")
                && event.getString("invalid_chan").equalsIgnoreCase(bufferToOpen)) {
            bufferToOpen = event.getString("valid_chan");
            obj = BuffersDataSource.getInstance().getBuffer(event.bid());
        } else {
            bufferToOpen = null;
            return;
        }
    case NetworkConnection.EVENT_MAKEBUFFER:
        BuffersDataSource.Buffer b = (BuffersDataSource.Buffer) obj;
        if (cidToOpen == b.cid && (bufferToOpen == null || (b.name.equalsIgnoreCase(bufferToOpen)
                && (buffer == null || !bufferToOpen.equalsIgnoreCase(buffer.name))))) {
            server = null;
            final int bid = b.bid;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onBufferSelected(bid);
                }
            });
            bufferToOpen = null;
            cidToOpen = -1;
        }
        break;
    case NetworkConnection.EVENT_OPENBUFFER:
        event = (IRCCloudJSONObject) obj;
        try {
            bufferToOpen = event.getString("name");
            cidToOpen = event.cid();
            b = BuffersDataSource.getInstance().getBufferByName(cidToOpen, bufferToOpen);
            if (b != null && !bufferToOpen.equalsIgnoreCase(buffer.name)) {
                server = null;
                bufferToOpen = null;
                cidToOpen = -1;
                final int bid = b.bid;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onBufferSelected(bid);
                    }
                });
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        break;
    case NetworkConnection.EVENT_CONNECTIVITY:
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateReconnecting();
            }
        });
        if (conn != null) {
            if (conn.getState() == NetworkConnection.STATE_CONNECTED) {
                for (EventsDataSource.Event e : pendingEvents.values()) {
                    try {
                        e.expiration_timer.cancel();
                    } catch (Exception ex) {
                        //Task already cancellled
                    }
                    e.expiration_timer = null;
                    e.failed = true;
                    e.bg_color = R.color.error;
                }
                if (drawerLayout != null && NetworkConnection.getInstance().ready) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                            getSupportActionBar().setHomeButtonEnabled(true);
                            updateUsersListFragmentVisibility();
                        }
                    });
                }
                if (server != null && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sendBtn.setEnabled(true);
                            if (Build.VERSION.SDK_INT >= 11)
                                sendBtn.setAlpha(1);
                        }
                    });
                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (drawerLayout != null && !NetworkConnection.getInstance().ready) {
                            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                            getSupportActionBar().setHomeButtonEnabled(false);
                        }
                        sendBtn.setEnabled(false);
                        if (Build.VERSION.SDK_INT >= 11)
                            sendBtn.setAlpha(0.5f);
                        photoBtn.setEnabled(false);
                        if (Build.VERSION.SDK_INT >= 11)
                            photoBtn.setAlpha(0.5f);
                    }
                });
            }
        }
        break;
    case NetworkConnection.EVENT_BANLIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (event != null && event.cid() == buffer.cid) {
                    Bundle args = new Bundle();
                    args.putInt("cid", event.cid());
                    BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(event.cid(),
                            event.getString("channel"));
                    if (b != null)
                        args.putInt("bid", b.bid);
                    args.putString("mode", "b");
                    args.putString("placeholder",
                            "No bans in effect.\n\nYou can ban someone by tapping their nickname in the user list, long-pressing a message, or by using /ban.");
                    args.putString("mask", "mask");
                    args.putString("list", "bans");
                    args.putString("title", "Ban list for " + event.getString("channel"));
                    args.putString("event", event.toString());
                    ChannelModeListFragment channelModeList = (ChannelModeListFragment) getSupportFragmentManager()
                            .findFragmentByTag("banlist");
                    if (channelModeList == null) {
                        channelModeList = new ChannelModeListFragment();
                        channelModeList.setArguments(args);
                        try {
                            channelModeList.show(getSupportFragmentManager(), "banlist");
                        } catch (IllegalStateException e) {
                            //App lost focus already
                        }
                    } else {
                        channelModeList.setArguments(args);
                    }
                }
            }
        });
        break;
    case NetworkConnection.EVENT_QUIETLIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (event != null && event.cid() == buffer.cid) {
                    Bundle args = new Bundle();
                    args.putInt("cid", event.cid());
                    BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(event.cid(),
                            event.getString("channel"));
                    if (b != null)
                        args.putInt("bid", b.bid);
                    args.putString("mode", "q");
                    args.putString("placeholder", "Empty quiet list.");
                    args.putString("mask", "quiet_mask");
                    args.putString("list", "list");
                    args.putString("title", "Quiet list for " + event.getString("channel"));
                    args.putString("event", event.toString());
                    ChannelModeListFragment channelModeList = (ChannelModeListFragment) getSupportFragmentManager()
                            .findFragmentByTag("quietlist");
                    if (channelModeList == null) {
                        channelModeList = new ChannelModeListFragment();
                        channelModeList.setArguments(args);
                        try {
                            channelModeList.show(getSupportFragmentManager(), "quietlist");
                        } catch (IllegalStateException e) {
                            //App lost focus already
                        }
                    } else {
                        channelModeList.setArguments(args);
                    }
                }
            }
        });
        break;
    case NetworkConnection.EVENT_BANEXCEPTIONLIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (event != null && event.cid() == buffer.cid) {
                    Bundle args = new Bundle();
                    args.putInt("cid", event.cid());
                    BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(event.cid(),
                            event.getString("channel"));
                    if (b != null)
                        args.putInt("bid", b.bid);
                    args.putString("mode", "e");
                    args.putString("placeholder", "Empty exception list.");
                    args.putString("mask", "mask");
                    args.putString("list", "exceptions");
                    args.putString("title", "Exception list for " + event.getString("channel"));
                    args.putString("event", event.toString());
                    ChannelModeListFragment channelModeList = (ChannelModeListFragment) getSupportFragmentManager()
                            .findFragmentByTag("exceptionlist");
                    if (channelModeList == null) {
                        channelModeList = new ChannelModeListFragment();
                        channelModeList.setArguments(args);
                        try {
                            channelModeList.show(getSupportFragmentManager(), "exceptionlist");
                        } catch (IllegalStateException e) {
                            //App lost focus already
                        }
                    } else {
                        channelModeList.setArguments(args);
                    }
                }
            }
        });
        break;
    case NetworkConnection.EVENT_INVITELIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (event != null && event.cid() == buffer.cid) {
                    Bundle args = new Bundle();
                    args.putInt("cid", event.cid());
                    BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(event.cid(),
                            event.getString("channel"));
                    if (b != null)
                        args.putInt("bid", b.bid);
                    args.putString("mode", "I");
                    args.putString("placeholder", "Empty invite list");
                    args.putString("mask", "mask");
                    args.putString("list", "list");
                    args.putString("title", "Invite list for " + event.getString("channel"));
                    args.putString("event", event.toString());
                    ChannelModeListFragment channelModeList = (ChannelModeListFragment) getSupportFragmentManager()
                            .findFragmentByTag("invitelist");
                    if (channelModeList == null) {
                        channelModeList = new ChannelModeListFragment();
                        channelModeList.setArguments(args);
                        try {
                            channelModeList.show(getSupportFragmentManager(), "invitelist");
                        } catch (IllegalStateException e) {
                            //App lost focus already
                        }
                    } else {
                        channelModeList.setArguments(args);
                    }
                }
            }
        });
        break;
    case NetworkConnection.EVENT_ACCEPTLIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (event != null && event.cid() == buffer.cid) {
                    Bundle args = new Bundle();
                    args.putInt("cid", buffer.cid);
                    args.putString("event", event.toString());
                    AcceptListFragment acceptList = (AcceptListFragment) getSupportFragmentManager()
                            .findFragmentByTag("acceptlist");
                    if (acceptList == null) {
                        acceptList = new AcceptListFragment();
                        acceptList.setArguments(args);
                        try {
                            acceptList.show(getSupportFragmentManager(), "acceptlist");
                        } catch (IllegalStateException e) {
                            //App lost focus already
                        }
                    } else {
                        acceptList.setArguments(args);
                    }
                }
            }
        });
        break;
    case NetworkConnection.EVENT_WHOLIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Bundle args = new Bundle();
                args.putString("event", event.toString());
                WhoListFragment whoList = (WhoListFragment) getSupportFragmentManager()
                        .findFragmentByTag("wholist");
                if (whoList == null) {
                    whoList = new WhoListFragment();
                    whoList.setArguments(args);
                    try {
                        whoList.show(getSupportFragmentManager(), "wholist");
                    } catch (IllegalStateException e) {
                        //App lost focus already
                    }
                } else {
                    whoList.setArguments(args);
                }
            }
        });
        break;
    case NetworkConnection.EVENT_NAMESLIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Bundle args = new Bundle();
                args.putString("event", event.toString());
                NamesListFragment namesList = (NamesListFragment) getSupportFragmentManager()
                        .findFragmentByTag("nameslist");
                if (namesList == null) {
                    namesList = new NamesListFragment();
                    namesList.setArguments(args);
                    try {
                        namesList.show(getSupportFragmentManager(), "nameslist");
                    } catch (IllegalStateException e) {
                        //App lost focus already
                    }
                } else {
                    namesList.setArguments(args);
                }
            }
        });
        break;
    case NetworkConnection.EVENT_SERVERMAPLIST:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Bundle args = new Bundle();
                args.putString("event", event.toString());
                ServerMapListFragment serversList = (ServerMapListFragment) getSupportFragmentManager()
                        .findFragmentByTag("serverslist");
                if (serversList == null) {
                    serversList = new ServerMapListFragment();
                    serversList.setArguments(args);
                    try {
                        serversList.show(getSupportFragmentManager(), "serverslist");
                    } catch (IllegalStateException e) {
                        //App lost focus already
                    }
                } else {
                    serversList.setArguments(args);
                }
            }
        });
        break;
    case NetworkConnection.EVENT_WHOIS:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Bundle args = new Bundle();
                args.putString("event", event.toString());
                WhoisFragment whois = (WhoisFragment) getSupportFragmentManager().findFragmentByTag("whois");
                if (whois == null) {
                    whois = new WhoisFragment();
                    whois.setArguments(args);
                    try {
                        whois.show(getSupportFragmentManager(), "whois");
                    } catch (IllegalStateException e) {
                        //App lost focus already
                    }
                } else {
                    whois.setArguments(args);
                }
            }
        });
        break;
    case NetworkConnection.EVENT_LISTRESPONSEFETCHING:
        event = (IRCCloudJSONObject) obj;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String dialogtitle = "List of channels on "
                        + ServersDataSource.getInstance().getServer(event.cid()).hostname;
                if (channelsListDialog == null) {
                    Context ctx = MainActivity.this;
                    final AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
                    builder.setView(getLayoutInflater().inflate(R.layout.dialog_channelslist, null));
                    builder.setTitle(dialogtitle);
                    builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    channelsListDialog = builder.create();
                    channelsListDialog.setOwnerActivity(MainActivity.this);
                } else {
                    channelsListDialog.setTitle(dialogtitle);
                }
                try {
                    channelsListDialog.show();
                } catch (IllegalStateException e) {
                    //App lost focus already
                }
                ChannelListFragment channels = (ChannelListFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.channelListFragment);
                Bundle args = new Bundle();
                args.putInt("cid", event.cid());
                channels.setArguments(args);
            }
        });
        break;
    case NetworkConnection.EVENT_USERINFO:
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateUsersListFragmentVisibility();
                supportInvalidateOptionsMenu();
                if (refreshUpIndicatorTask != null)
                    refreshUpIndicatorTask.cancel(true);
                refreshUpIndicatorTask = new RefreshUpIndicatorTask();
                refreshUpIndicatorTask.execute((Void) null);
            }
        });
        if (launchBid == -1 && server == null && conn != null && conn.getUserInfo() != null)
            launchBid = conn.getUserInfo().last_selected_bid;
        break;
    case NetworkConnection.EVENT_STATUSCHANGED:
        try {
            event = (IRCCloudJSONObject) obj;
            if (event != null && server != null && event.cid() == server.cid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        supportInvalidateOptionsMenu();
                    }
                });
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        break;
    case NetworkConnection.EVENT_MAKESERVER:
        ServersDataSource.Server s = (ServersDataSource.Server) obj;
        if (server != null && s != null && s.cid == server.cid) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    supportInvalidateOptionsMenu();
                    update_subtitle();
                }
            });
        } else {
            cidToOpen = s.cid;
            bufferToOpen = "*";
        }
        break;
    case NetworkConnection.EVENT_BUFFERARCHIVED:
    case NetworkConnection.EVENT_BUFFERUNARCHIVED:
        event_bid = (Integer) obj;
        if (buffer != null && event_bid == buffer.bid) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    update_subtitle();
                }
            });
        }
        if (refreshUpIndicatorTask != null)
            refreshUpIndicatorTask.cancel(true);
        refreshUpIndicatorTask = new RefreshUpIndicatorTask();
        refreshUpIndicatorTask.execute((Void) null);
        break;
    case NetworkConnection.EVENT_JOIN:
        event = (IRCCloudJSONObject) obj;
        if (event != null && buffer != null && event.bid() == buffer.bid
                && event.type().equals("you_joined_channel")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    supportInvalidateOptionsMenu();
                    updateUsersListFragmentVisibility();
                }
            });
        }
        break;
    case NetworkConnection.EVENT_PART:
    case NetworkConnection.EVENT_KICK:
        event = (IRCCloudJSONObject) obj;
        if (event != null && buffer != null && event.bid() == buffer.bid
                && event.type().toLowerCase().startsWith("you_")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    supportInvalidateOptionsMenu();
                    updateUsersListFragmentVisibility();
                }
            });
        }
        break;
    case NetworkConnection.EVENT_CHANNELINIT:
        ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel) obj;
        if (channel != null && buffer != null && channel.bid == buffer.bid) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    update_subtitle();
                    supportInvalidateOptionsMenu();
                    updateUsersListFragmentVisibility();
                }
            });
        }
        break;
    case NetworkConnection.EVENT_BACKLOG_END:
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                errorMsg.setVisibility(View.GONE);
                error = null;
                if (progressBar.getVisibility() == View.VISIBLE) {
                    if (Build.VERSION.SDK_INT >= 16) {
                        progressBar.animate().alpha(0).setDuration(200).withEndAction(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                            }
                        });
                    } else {
                        progressBar.setVisibility(View.GONE);
                    }
                }
                getSupportActionBar().setDisplayShowTitleEnabled(false);
                getSupportActionBar().setDisplayShowCustomEnabled(true);
                if (drawerLayout != null) {
                    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                    getSupportActionBar().setHomeButtonEnabled(true);
                    updateUsersListFragmentVisibility();
                }
                if (ServersDataSource.getInstance().count() < 1) {
                    Crashlytics.log(Log.DEBUG, "IRCCloud", "No servers configured, launching add dialog");
                    addNetwork();
                } else {
                    if (server == null || launchURI != null || launchBid != -1) {
                        Crashlytics.log(Log.DEBUG, "IRCCloud",
                                "Backlog loaded and we're waiting for a buffer, switching now");
                        if (launchURI == null || !open_uri(launchURI)) {
                            if (launchBid == -1 || !open_bid(launchBid)) {
                                if (conn == null || conn.getUserInfo() == null
                                        || !open_bid(conn.getUserInfo().last_selected_bid)) {
                                    if (!open_bid(BuffersDataSource.getInstance().firstBid())) {
                                        if (drawerLayout != null && NetworkConnection.getInstance().ready
                                                && findViewById(R.id.usersListFragment2) == null) {
                                            drawerLayout.openDrawer(Gravity.LEFT);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    update_subtitle();
                }
                if (refreshUpIndicatorTask != null)
                    refreshUpIndicatorTask.cancel(true);
                refreshUpIndicatorTask = new RefreshUpIndicatorTask();
                refreshUpIndicatorTask.execute((Void) null);
                photoBtn.setEnabled(true);
                if (Build.VERSION.SDK_INT >= 11)
                    photoBtn.setAlpha(1);
            }
        });
        //TODO: prune and pop the back stack if the current BID has disappeared
        break;
    case NetworkConnection.EVENT_CONNECTIONDELETED:
    case NetworkConnection.EVENT_DELETEBUFFER:
        Integer id = (Integer) obj;
        if (what == NetworkConnection.EVENT_DELETEBUFFER) {
            synchronized (backStack) {
                for (int i = 0; i < backStack.size(); i++) {
                    if (backStack.get(i).equals(id)) {
                        backStack.remove(i);
                        i--;
                    }
                }
            }
        }
        if (buffer != null
                && id == ((what == NetworkConnection.EVENT_CONNECTIONDELETED) ? buffer.cid : buffer.bid)) {
            synchronized (backStack) {
                while (backStack != null && backStack.size() > 0) {
                    final Integer bid = backStack.get(0);
                    backStack.remove(0);
                    b = BuffersDataSource.getInstance().getBuffer(bid);
                    if (b != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                onBufferSelected(bid);
                                if (backStack.size() > 0)
                                    backStack.remove(0);
                            }
                        });
                        return;
                    }
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (BuffersDataSource.getInstance().count() == 0) {
                        startActivity(new Intent(MainActivity.this, EditConnectionActivity.class));
                        finish();
                    } else {
                        if ((NetworkConnection.getInstance().getUserInfo() == null
                                || !open_bid(NetworkConnection.getInstance().getUserInfo().last_selected_bid))
                                && !open_bid(BuffersDataSource.getInstance().firstBid()))
                            finish();
                    }
                }
            });
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (refreshUpIndicatorTask != null)
                    refreshUpIndicatorTask.cancel(true);
                refreshUpIndicatorTask = new RefreshUpIndicatorTask();
                refreshUpIndicatorTask.execute((Void) null);
            }
        });
        break;
    case NetworkConnection.EVENT_CHANNELMODE:
    case NetworkConnection.EVENT_CHANNELTOPIC:
        event = (IRCCloudJSONObject) obj;
        if (event != null && buffer != null && event.bid() == buffer.bid) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    update_subtitle();
                }
            });
        }
        break;
    case NetworkConnection.EVENT_SELFBACK:
    case NetworkConnection.EVENT_AWAY:
        try {
            event = (IRCCloudJSONObject) obj;
            if (event != null && buffer != null && event.cid() == buffer.cid
                    && event.getString("nick").equalsIgnoreCase(buffer.name)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        update_subtitle();
                    }
                });
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        break;
    case NetworkConnection.EVENT_HEARTBEATECHO:
        boolean shouldRefresh = false;
        event = (IRCCloudJSONObject) obj;
        JsonNode seenEids = event.getJsonNode("seenEids");
        Iterator<Map.Entry<String, JsonNode>> iterator = seenEids.fields();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonNode> entry = iterator.next();
            JsonNode eids = entry.getValue();
            Iterator<Map.Entry<String, JsonNode>> j = eids.fields();
            while (j.hasNext()) {
                Map.Entry<String, JsonNode> eidentry = j.next();
                Integer bid = Integer.valueOf(eidentry.getKey());
                if (buffer != null && bid != buffer.bid) {
                    shouldRefresh = true;
                }
            }
        }
        if (shouldRefresh) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (refreshUpIndicatorTask != null)
                        refreshUpIndicatorTask.cancel(true);
                    refreshUpIndicatorTask = new RefreshUpIndicatorTask();
                    refreshUpIndicatorTask.execute((Void) null);
                }
            });
        }
        break;
    case NetworkConnection.EVENT_FAILURE_MSG:
        event = (IRCCloudJSONObject) obj;
        if (event != null && event.has("_reqid")) {
            int reqid = event.getInt("_reqid");
            if (pendingEvents.containsKey(reqid)) {
                EventsDataSource.Event e = pendingEvents.get(reqid);
                EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
                pendingEvents.remove(event.getInt("_reqid"));
                e.failed = true;
                e.bg_color = R.color.error;
                if (e.expiration_timer != null)
                    e.expiration_timer.cancel();
                conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e);
            }
        } else {
            if (event.getString("message").equalsIgnoreCase("auth")) {
                conn.logout();
                Intent i = new Intent(MainActivity.this, LoginActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                finish();
            }
            if (event.getString("message").equalsIgnoreCase("set_shard")) {
                NetworkConnection.getInstance().disconnect();
                NetworkConnection.getInstance().ready = false;
                SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit();
                editor.putString("session_key", event.getString("cookie"));
                if (event.has("websocket_host")) {
                    NetworkConnection.IRCCLOUD_HOST = event.getString("websocket_host");
                    NetworkConnection.IRCCLOUD_PATH = event.getString("websocket_path");
                }
                editor.putString("host", NetworkConnection.IRCCLOUD_HOST);
                editor.putString("path", NetworkConnection.IRCCLOUD_PATH);
                editor.commit();
                NetworkConnection.getInstance().connect(event.getString("cookie"));
            }
        }
        try {
            error = event.getString("message");
            if (error.equals("temp_unavailable"))
                error = "Your account is temporarily unavailable";
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateReconnecting();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;
    case NetworkConnection.EVENT_BUFFERMSG:
        try {
            EventsDataSource.Event e = (EventsDataSource.Event) obj;
            if (e != null && buffer != null) {
                if (e.bid != buffer.bid && upDrawable != null) {
                    BuffersDataSource.Buffer buf = BuffersDataSource.getInstance().getBuffer(e.bid);
                    if (e.isImportant(buf.type)) {
                        if (upDrawable.getColor() != redColor
                                && (e.highlight || buf.type.equals("conversation"))) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    upDrawable.setColor(redColor);
                                }
                            });
                        } else if (upDrawable.getColor() == greyColor) {
                            JSONObject channelDisabledMap = null;
                            JSONObject bufferDisabledMap = null;
                            if (NetworkConnection.getInstance().getUserInfo() != null
                                    && NetworkConnection.getInstance().getUserInfo().prefs != null) {
                                try {
                                    if (NetworkConnection.getInstance().getUserInfo().prefs
                                            .has("channel-disableTrackUnread"))
                                        channelDisabledMap = NetworkConnection.getInstance().getUserInfo().prefs
                                                .getJSONObject("channel-disableTrackUnread");
                                    if (NetworkConnection.getInstance().getUserInfo().prefs
                                            .has("buffer-disableTrackUnread"))
                                        bufferDisabledMap = NetworkConnection.getInstance().getUserInfo().prefs
                                                .getJSONObject("buffer-disableTrackUnread");
                                } catch (Exception e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                            }
                            if (buf.type.equalsIgnoreCase("channel") && channelDisabledMap != null
                                    && channelDisabledMap.has(String.valueOf(buf.bid))
                                    && channelDisabledMap.getBoolean(String.valueOf(buf.bid)))
                                break;
                            else if (bufferDisabledMap != null && bufferDisabledMap.has(String.valueOf(buf.bid))
                                    && bufferDisabledMap.getBoolean(String.valueOf(buf.bid)))
                                break;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    upDrawable.setColor(blueColor);
                                }
                            });
                        }
                    }
                }
                if (e.from.equalsIgnoreCase(buffer.name)) {
                    pendingEvents.clear();
                } else if (pendingEvents.containsKey(e.reqid)) {
                    pendingEvents.remove(e.reqid);
                }
            }
        } catch (Exception e1) {
        }
        break;
    }
}