Example usage for android.app ProgressDialog dismiss

List of usage examples for android.app ProgressDialog dismiss

Introduction

In this page you can find the example usage for android.app ProgressDialog dismiss.

Prototype

@Override
public void dismiss() 

Source Link

Document

Dismiss this dialog, removing it from the screen.

Usage

From source file:com.lostad.app.base.util.DownloadUtil.java

public static void downFileAsyn(final Activity ctx, final String upgradeUrl, final String savedPath,
        final MyCallback<Boolean> callback) {
    final ProgressDialog xh_pDialog = new ProgressDialog(ctx);
    // ?/*from   w w w  .  j ava2 s  . c  o m*/
    xh_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    // ProgressDialog 
    xh_pDialog.setTitle("???");
    // ProgressDialog???
    xh_pDialog.setMessage("...");
    // ProgressDialog
    // xh_pDialog.setIcon(R.drawable.img2);
    // ProgressDialog ??? false ??
    xh_pDialog.setIndeterminate(false);
    // ProgressDialog ?
    // xh_pDialog.setProgress(100);
    // ProgressDialog ???
    xh_pDialog.setCancelable(true);
    // ProgressDialog
    xh_pDialog.show();

    new Thread() {
        public void run() {

            boolean downloadSuccess = true;
            FileOutputStream fileOutputStream = null;
            try {
                Looper.prepare();
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(upgradeUrl);

                File f = new File(savedPath);
                if (!f.exists()) {
                    f.createNewFile();
                }

                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                // ?
                Long length = entity.getContentLength();
                xh_pDialog.setMax(length.intValue());
                //
                InputStream is = entity.getContent();
                fileOutputStream = null;

                if (is != null && length > 0) {

                    fileOutputStream = new FileOutputStream(f);

                    byte[] buf = new byte[1024];
                    int ch = -1;
                    int count = 0;
                    while ((ch = is.read(buf)) != -1) {

                        if (xh_pDialog.isShowing()) {
                            fileOutputStream.write(buf, 0, ch);
                            // ?
                            count += ch;
                            xh_pDialog.setProgress(count);
                        } else {
                            downloadSuccess = false;
                            break;// ?
                        }
                    }

                } else {
                    callback.onCallback(false);
                }

                if (downloadSuccess && fileOutputStream != null) {
                    xh_pDialog.dismiss();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    callback.onCallback(true);// ?
                }
                Looper.loop();
            } catch (FileNotFoundException e) {
                xh_pDialog.dismiss();
                e.printStackTrace();
                callback.onCallback(false);
                xh_pDialog.dismiss();
            } catch (Exception e) {
                xh_pDialog.dismiss();
                e.printStackTrace();
                callback.onCallback(false);
            } finally {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }.start();

}

From source file:fm.smart.r1.activity.CreateExampleActivity.java

public void onClick(View v) {
    EditText exampleInput = (EditText) findViewById(R.id.create_example_sentence);
    EditText translationInput = (EditText) findViewById(R.id.create_example_translation);
    EditText exampleTransliterationInput = (EditText) findViewById(R.id.sentence_transliteration);
    EditText translationTransliterationInput = (EditText) findViewById(R.id.translation_transliteration);
    final String example = exampleInput.getText().toString();
    final String translation = translationInput.getText().toString();
    if (TextUtils.isEmpty(example) || TextUtils.isEmpty(translation)) {
        Toast t = Toast.makeText(this, "Example and translation are required fields", 150);
        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();/*ww w .  ja v a  2 s  . c o m*/
    } else {
        final String example_language_code = Utils.LANGUAGE_MAP.get(example_language);
        final String translation_language_code = Utils.LANGUAGE_MAP.get(translation_language);
        final String example_transliteration = exampleTransliterationInput.getText().toString();
        final String translation_transliteration = translationTransliterationInput.getText().toString();

        if (Main.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // avoid
            // navigation
            // back to this?
            LoginActivity.return_to = CreateExampleActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("list_id", list_id);
            LoginActivity.params.put("item_id", item_id);
            LoginActivity.params.put("example", example);
            LoginActivity.params.put("translation", translation);
            LoginActivity.params.put("example_language", example_language);
            LoginActivity.params.put("translation_language", translation_language);
            LoginActivity.params.put("example_transliteration", example_transliteration);
            LoginActivity.params.put("translation_transliteration", translation_transliteration);
            startActivity(intent);
        } else {

            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Creating Example ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread create_example = new Thread() {
                public void run() {
                    // TODO make this interruptable .../*if
                    // (!this.isInterrupted())*/
                    try {
                        // TODO failures here could derail all ...
                        CreateExampleActivity.add_item_list_result = ItemActivity.addItemToList(list_id,
                                item_id, CreateExampleActivity.this);
                        CreateExampleActivity.create_example_result = createExample(example,
                                example_language_code, example_transliteration, translation,
                                translation_language_code, translation_transliteration, item_id, list_id);
                        CreateExampleActivity.add_sentence_list_result = ItemActivity.addSentenceToList(
                                CreateExampleActivity.create_example_result.http_response, item_id, list_id,
                                CreateExampleActivity.this);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    myOtherProgressDialog.dismiss();

                }
            };
            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    create_example.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    create_example.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            myOtherProgressDialog.show();
            create_example.start();
        }
    }
}

From source file:org.catnut.ui.ComposeTweetActivity.java

private void shorten() {
    String text = mText.getText().toString();
    final Matcher matcher = TweetTextView.WEB_URL.matcher(text);
    String urls = "";
    while (matcher.find()) {
        urls += matcher.group() + ""; // ?
    }// www . j  a v  a 2  s .  c o  m
    // http request
    if (!TextUtils.isEmpty(urls)) {
        final ProgressDialog dialog = ProgressDialog.show(this, null, getString(R.string.converting), true,
                false);
        CatnutAPI api = StuffAPI.shorten(urls.split(""));
        mApp.getRequestQueue()
                .add(new JsonObjectRequest(api.method, api.uri, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        matcher.reset(); // ?
                        JSONArray _urls = response.optJSONArray("urls");
                        StringBuffer sb = new StringBuffer();
                        int i = 0;
                        try {
                            while (matcher.find()) {
                                matcher.appendReplacement(sb, _urls.optJSONObject(i).optString("url_short"));
                                i++;
                            }
                            matcher.appendTail(sb);
                            mText.setText(sb);
                            mText.setSelection(mText.length());
                        } catch (Exception ex) {
                            Log.e(TAG, "replace shorten url error!", ex);
                        }
                        dialog.dismiss();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dialog.dismiss();
                        WeiboAPIError weiboAPIError = WeiboAPIError.fromVolleyError(error);
                        Toast.makeText(ComposeTweetActivity.this, weiboAPIError.error, Toast.LENGTH_SHORT)
                                .show();
                    }
                }));
    } else {
        Toast.makeText(this, getString(R.string.no_links_hint), Toast.LENGTH_SHORT).show();
    }
}

From source file:org.kde.necessitas.ministro.MinistroActivity.java

private void checkNetworkAndDownload(final boolean update) {
    if (isOnline(this))
        new CheckLibraries().execute(update);
    else {/*from  ww w.ja v a2s  .c o m*/
        AlertDialog.Builder builder = new AlertDialog.Builder(MinistroActivity.this);
        builder.setMessage(getResources().getString(R.string.ministro_network_access_msg));
        builder.setCancelable(true);
        builder.setNeutralButton(getResources().getString(R.string.settings_msg),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        final ProgressDialog m_dialog = ProgressDialog.show(MinistroActivity.this, null,
                                getResources().getString(R.string.wait_for_network_connection_msg), true, true,
                                new DialogInterface.OnCancelListener() {
                                    public void onCancel(DialogInterface dialog) {
                                        finishMe();
                                    }
                                });
                        getApplication().registerReceiver(new BroadcastReceiver() {
                            @Override
                            public void onReceive(Context context, Intent intent) {
                                if (isOnline(MinistroActivity.this)) {
                                    try {
                                        getApplication().unregisterReceiver(this);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            m_dialog.dismiss();
                                            new CheckLibraries().execute(update);
                                        }
                                    });
                                }
                            }
                        }, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                        try {
                            startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                        } catch (Exception e) {
                            e.printStackTrace();
                            try {
                                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                            } catch (Exception e1) {

                                e1.printStackTrace();
                            }
                        }
                        dialog.dismiss();
                    }
                });
        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                finishMe();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

From source file:cn.ucai.superwechat.fragments.ContactlistFragment.java

/**
 * ?//from ww  w .  j  a  va2  s .com
 * 
 * @param tobeDeleteUser
 */
public void deleteContact(final Contact tobeDeleteUser) {
    String st1 = getResources().getString(cn.ucai.superwechat.R.string.deleting);
    final String st2 = getResources().getString(cn.ucai.superwechat.R.string.Delete_failed);
    final ProgressDialog pd = new ProgressDialog(getActivity());
    pd.setMessage(st1);
    pd.setCanceledOnTouchOutside(false);
    pd.show();

    try {
        String path = new ApiParams()
                .with(I.Contact.USER_NAME, SuperWeChatApplication.getInstance().getUserName())
                .with(I.Contact.CU_NAME, tobeDeleteUser.getMContactCname())
                .getRequestUrl(I.REQUEST_DELETE_CONTACT);
        ((MainActivity) getActivity()).executeRequest(new GsonRequest<Boolean>(path, Boolean.class,
                responseDeleteContactListener(tobeDeleteUser), ((MainActivity) getActivity()).errorListener()));
    } catch (Exception e) {
        e.printStackTrace();
    }

    new Thread(new Runnable() {
        public void run() {
            try {
                EMContactManager.getInstance().deleteContact(tobeDeleteUser.getMContactCname());
                // db?
                EMUserDao dao = new EMUserDao(getActivity());
                dao.deleteContact(tobeDeleteUser.getMContactCname());
                ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList()
                        .remove(tobeDeleteUser.getMContactCname());
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        adapter.remove(tobeDeleteUser);
                        adapter.notifyDataSetChanged();

                    }
                });
            } catch (final Exception e) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getActivity(), st2 + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }).start();
}

From source file:org.ros.android.app_chooser.ExchangeActivity.java

public void uninstallApp(View view) {
    final ExchangeActivity activity = this;
    final ProgressDialog progress = ProgressDialog.show(activity, "Uninstalling App",
            "Uninstalling " + appSelectedDisplay + "...", true, false);
    progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    appManager.uninstallApp(appSelected, new ServiceResponseListener<UninstallApp.Response>() {
        @Override//from   w ww . j  a va 2s .co  m
        public void onSuccess(UninstallApp.Response message) {
            if (!message.uninstalled) {
                final String errorMessage = message.message;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new AlertDialog.Builder(activity).setTitle("Error on Uninstallation!")
                                .setCancelable(false).setMessage("ERROR: " + errorMessage)
                                .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create().show();
                    }
                });
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.dismiss();
                }
            });
        }

        @Override
        public void onFailure(final RemoteException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(activity).setTitle("Error on Uninstallation").setCancelable(false)
                            .setMessage("Failed: cannot contact robot: " + e.toString())
                            .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create().show();
                    progress.dismiss();
                }
            });
        }
    });
}

From source file:org.telegram.ui.SessionsActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("SessionsTitle", R.string.SessionsTitle));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override/*w w  w  .  j  a  v  a 2  s  . c  o  m*/
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

    emptyLayout = new LinearLayout(context);
    emptyLayout.setOrientation(LinearLayout.VERTICAL);
    emptyLayout.setGravity(Gravity.CENTER);
    //emptyLayout.setBackgroundResource(R.drawable.greydivider_bottom);
    emptyLayout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
            AndroidUtilities.displaySize.y - ActionBar.getCurrentActionBarHeight()));

    ImageView imageView = new ImageView(context);
    imageView.setImageResource(R.drawable.devices);
    emptyLayout.addView(imageView);
    LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) imageView.getLayoutParams();
    layoutParams2.width = LayoutHelper.WRAP_CONTENT;
    layoutParams2.height = LayoutHelper.WRAP_CONTENT;
    imageView.setLayoutParams(layoutParams2);

    TextView textView = new TextView(context);
    textView.setTextColor(ContextCompat.getColor(context, R.color.disabled_text) /*0xff8a8a8a*/);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    textView.setText(LocaleController.getString("NoOtherSessions", R.string.NoOtherSessions));
    emptyLayout.addView(textView);
    layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams();
    layoutParams2.topMargin = AndroidUtilities.dp(16);
    layoutParams2.width = LayoutHelper.WRAP_CONTENT;
    layoutParams2.height = LayoutHelper.WRAP_CONTENT;
    layoutParams2.gravity = Gravity.CENTER;
    textView.setLayoutParams(layoutParams2);

    textView = new TextView(context);
    textView.setTextColor(ContextCompat.getColor(context, R.color.disabled_text) /*0xff8a8a8a*/);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    textView.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0);
    textView.setText(LocaleController.getString("NoOtherSessionsInfo", R.string.NoOtherSessionsInfo));
    emptyLayout.addView(textView);
    layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams();
    layoutParams2.topMargin = AndroidUtilities.dp(14);
    layoutParams2.width = LayoutHelper.WRAP_CONTENT;
    layoutParams2.height = LayoutHelper.WRAP_CONTENT;
    layoutParams2.gravity = Gravity.CENTER;
    textView.setLayoutParams(layoutParams2);

    FrameLayout progressView = new FrameLayout(context);
    frameLayout.addView(progressView);
    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams();
    layoutParams.width = LayoutHelper.MATCH_PARENT;
    layoutParams.height = LayoutHelper.MATCH_PARENT;
    progressView.setLayoutParams(layoutParams);
    progressView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    ProgressBar progressBar = new ProgressBar(context);
    progressView.addView(progressBar);
    layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams();
    layoutParams.width = LayoutHelper.WRAP_CONTENT;
    layoutParams.height = LayoutHelper.WRAP_CONTENT;
    layoutParams.gravity = Gravity.CENTER;
    progressView.setLayoutParams(layoutParams);

    ListView listView = new ListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    listView.setDrawSelectorOnTop(true);
    listView.setEmptyView(progressView);
    frameLayout.addView(listView);
    layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
    layoutParams.width = LayoutHelper.MATCH_PARENT;
    layoutParams.height = LayoutHelper.MATCH_PARENT;
    layoutParams.gravity = Gravity.TOP;
    listView.setLayoutParams(layoutParams);
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
            if (i == terminateAllSessionsRow) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(
                        LocaleController.getString("AreYouSureSessions", R.string.AreYouSureSessions));
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                TLRPC.TL_auth_resetAuthorizations req = new TLRPC.TL_auth_resetAuthorizations();
                                ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                    @Override
                                    public void run(final TLObject response, final TLRPC.TL_error error) {
                                        AndroidUtilities.runOnUIThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (getParentActivity() == null) {
                                                    return;
                                                }
                                                if (error == null && response instanceof TLRPC.TL_boolTrue) {
                                                    Toast toast = Toast.makeText(getParentActivity(),
                                                            LocaleController.getString("TerminateAllSessions",
                                                                    R.string.TerminateAllSessions),
                                                            Toast.LENGTH_SHORT);
                                                    toast.show();
                                                } else {
                                                    Toast toast = Toast
                                                            .makeText(getParentActivity(),
                                                                    LocaleController.getString("UnknownError",
                                                                            R.string.UnknownError),
                                                                    Toast.LENGTH_SHORT);
                                                    toast.show();
                                                }
                                                finishFragment();
                                            }
                                        });
                                        UserConfig.registeredForPush = false;
                                        UserConfig.saveConfig(false);
                                        MessagesController.getInstance().registerForPush(UserConfig.pushString);
                                        ConnectionsManager.getInstance()
                                                .setUserId(UserConfig.getClientUserId());
                                    }
                                });
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (i >= otherSessionsStartRow && i < otherSessionsEndRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(LocaleController.getString("TerminateSessionQuestion",
                        R.string.TerminateSessionQuestion));
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int option) {
                                final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
                                progressDialog
                                        .setMessage(LocaleController.getString("Loading", R.string.Loading));
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setCancelable(false);
                                progressDialog.show();

                                final TLRPC.TL_authorization authorization = sessions
                                        .get(i - otherSessionsStartRow);
                                TLRPC.TL_account_resetAuthorization req = new TLRPC.TL_account_resetAuthorization();
                                req.hash = authorization.hash;
                                ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                    @Override
                                    public void run(final TLObject response, final TLRPC.TL_error error) {
                                        AndroidUtilities.runOnUIThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    progressDialog.dismiss();
                                                } catch (Exception e) {
                                                    FileLog.e("tmessages", e);
                                                }
                                                if (error == null) {
                                                    sessions.remove(authorization);
                                                    updateRows();
                                                    if (listAdapter != null) {
                                                        listAdapter.notifyDataSetChanged();
                                                    }
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            }
        }
    });

    return fragmentView;
}

From source file:org.naturenet.ui.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    userList = FetchData.getInstance().getUsers();
    setContentView(R.layout.activity_main);
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    logout = navigationView.getMenu().findItem(R.id.nav_logout);
    settings = navigationView.getMenu().findItem(R.id.nav_settings);
    header = navigationView.getHeaderView(0);
    sign_in = (Button) header.findViewById(R.id.nav_b_sign_in);
    join = (Button) header.findViewById(R.id.nav_b_join);
    nav_iv = (ImageView) header.findViewById(R.id.nav_iv);
    display_name = (TextView) header.findViewById(R.id.nav_tv_display_name);
    affiliation = (TextView) header.findViewById(R.id.nav_tv_affiliation);
    licenses = (TextView) navigationView.findViewById(R.id.licenses);
    setSupportActionBar(toolbar);//  w w w. java 2  s .  c  om
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    navigationView.setNavigationItemSelectedListener(this);
    add_observation_button = (ImageView) findViewById(R.id.addObsButton);
    selectionStack = new Stack<>();
    selectedImages = new ArrayList<>();
    mFirebase = FirebaseDatabase.getInstance().getReference();
    tabLayout = (TabLayout) findViewById(R.id.TabLayout);

    if (getSupportActionBar() != null)
        getSupportActionBar().setDisplayShowTitleEnabled(false);

    //Handle the intent from Firebase Notifications.
    if (getIntent().getExtras() != null) {
        Bundle dataBundle = getIntent().getExtras();
        //get the parent and context
        String parent = (String) dataBundle.get("parent");
        String context = (String) dataBundle.get("context");

        if (parent != null && context != null) {
            switch (context) {
            case "observations":
                Intent observationIntent = new Intent(MainActivity.this, ObservationActivity.class);
                observationIntent.putExtra("observation", parent);
                startActivity(observationIntent);
                break;
            case "ideas": {
                final Intent ideaIntent = new Intent(MainActivity.this, IdeaDetailsActivity.class);
                final ProgressDialog dialog;
                dialog = ProgressDialog.show(MainActivity.this, "Loading", "", true, false);
                dialog.show();

                mFirebase.child(Idea.NODE_NAME).child(parent)
                        .addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                Idea idea = dataSnapshot.getValue(Idea.class);
                                ideaIntent.putExtra("idea", idea);
                                dialog.dismiss();
                                startActivity(ideaIntent);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                Toast.makeText(MainActivity.this, "Could not load Design Idea",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });

                break;
            }
            case "activities": {
                final Intent projectIntent = new Intent(MainActivity.this, ProjectActivity.class);
                final ProgressDialog dialog;
                dialog = ProgressDialog.show(MainActivity.this, "Loading", "", true, false);
                dialog.show();

                mFirebase.child(Project.NODE_NAME).child(parent)
                        .addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                Project project = dataSnapshot.getValue(Project.class);
                                projectIntent.putExtra("project", project);
                                dialog.dismiss();
                                startActivity(projectIntent);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                Toast.makeText(MainActivity.this, "Could not load New Project",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                break;
            }
            }
        }

    }

    //Set listener for the tab layout
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            //Position for the map view
            if (tab.getPosition() == 0) {
                getFragmentManager().popBackStack();
                getFragmentManager().beginTransaction()
                        .replace(R.id.fragment_container, ExploreFragment.newInstance(user_home_site))
                        .addToBackStack(ExploreFragment.FRAGMENT_TAG).commit();
            }
            //Position for the gallery view
            else if (tab.getPosition() == 1) {
                getFragmentManager().popBackStack();
                getFragmentManager().beginTransaction()
                        .replace(R.id.fragment_container, new ObservationGalleryFragment())
                        .addToBackStack(ObservationGalleryFragment.FRAGMENT_TAG).commit();
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    licenses.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(v.getContext())
                    .setView(View.inflate(MainActivity.this, R.layout.about, null))
                    .setNegativeButton("Dismiss", null).setCancelable(false).show();
        }
    });

    this.invalidateOptionsMenu();

    /**
     * When user selects the camera icon, check to see if we have permission to view their images.
     */
    add_observation_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, REQUEST_CODE_GALLERY);
            } else {
                setGallery();
            }

            select.setVisibility(View.GONE);
            dialog_add_observation.setVisibility(View.VISIBLE);
        }
    });

    sign_in.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (((NatureNetApplication) getApplication()).isConnected()) {
                MainActivity.this.goToLoginActivity();
            } else {
                Toast.makeText(MainActivity.this, R.string.no_connection, Toast.LENGTH_SHORT).show();
            }
        }
    });

    join.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (((NatureNetApplication) getApplication()).isConnected()) {
                MainActivity.this.goToJoinActivity();
            } else {
                Toast.makeText(MainActivity.this, R.string.no_connection, Toast.LENGTH_SHORT).show();
            }
        }
    });

    showNoUser();

    getFragmentManager().beginTransaction().add(R.id.fragment_container, new LaunchFragment()).commit();

    mUserAuthSubscription = ((NatureNetApplication) getApplication()).getCurrentUserObservable()
            .subscribe(new Consumer<Optional<Users>>() {
                @Override
                public void accept(Optional<Users> user) throws Exception {
                    if (user.isPresent()) {

                        onUserSignIn(user.get());

                        if (getFragmentManager().getBackStackEntryCount() == 0) {
                            getFragmentManager().beginTransaction()
                                    .add(R.id.fragment_container, ExploreFragment.newInstance(user_home_site))
                                    .commitAllowingStateLoss();
                        }
                        tabLayout.setVisibility(View.VISIBLE);
                    } else {
                        if (signed_user != null) {
                            onUserSignOut();
                        }
                        showNoUser();
                    }
                }
            });

    //click listener for when user selects profile image
    nav_iv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (signed_user != null)
                goToProfileSettingsActivity();
        }
    });

    display_name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (signed_user != null)
                goToProfileSettingsActivity();
        }
    });

    affiliation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (signed_user != null)
                goToProfileSettingsActivity();
        }
    });

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
            final Status status = locationSettingsResult.getStatus();
            if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
                try {
                    status.startResolutionForResult(MainActivity.this, REQUEST_CODE_CHECK_LOCATION_SETTINGS);
                } catch (IntentSender.SendIntentException e) {
                    Timber.w(e, "Unable to resolve location settings");
                }
            } else if (status.getStatusCode() == LocationSettingsStatusCodes.SUCCESS) {
                requestLocationUpdates();
            }
        }
    });

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (lastLocation != null) {
            latValue = lastLocation.getLatitude();
            longValue = lastLocation.getLongitude();
        }
    } else {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                REQUEST_CODE_CHECK_LOCATION_SETTINGS);
    }

    latValue = 0.0;
    longValue = 0.0;

    dialog_add_observation = (LinearLayout) findViewById(R.id.ll_dialog_add_observation);
    add_observation_cancel = (ImageView) findViewById(R.id.dialog_add_observation_iv_cancel);
    camera = (Button) findViewById(R.id.dialog_add_observation_b_camera);
    gallery = (Button) findViewById(R.id.dialog_add_observation_b_gallery);
    select = (TextView) findViewById(R.id.dialog_add_observation_tv_select);
    gridview = (GridView) findViewById(R.id.dialog_add_observation_gv);
    gallery_item = (ImageView) findViewById(R.id.gallery_iv);
    cameraPhoto = new CameraPhoto(this);
    galleryPhoto = new GalleryPhoto(this);

    add_observation_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            selectedImages.clear();
            select.setVisibility(View.GONE);
            dialog_add_observation.setVisibility(View.GONE);
        }
    });

    /**
     * Click listener for when user selects images they want to upload.
     */
    select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Picasso.with(MainActivity.this).cancelTag(ImageGalleryAdapter.class.getSimpleName());
            setGallery();
            goToAddObservationActivity(false);
        }
    });

    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (isStoragePermitted()) {
                setGallery();
                select.setVisibility(View.GONE);

                try {
                    startActivityForResult(cameraPhoto.takePhotoIntent(), REQUEST_CODE_CAMERA);
                } catch (IOException e) {
                    Toast.makeText(MainActivity.this, "Something Wrong while taking photo", Toast.LENGTH_SHORT)
                            .show();
                }
            } else
                Toast.makeText(MainActivity.this, R.string.permission_rejected, Toast.LENGTH_LONG).show();
        }
    });

    gallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (isStoragePermitted()) {
                select.setVisibility(View.GONE);
                selectedImages.clear();

                //Check to see if the user is on API 18 or above.
                if (usingApiEighteenAndAbove()) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY_IMAGES);
                } else {
                    //If not on 18 or above, go to the custom Gallery Activity
                    Intent intent = new Intent(getApplicationContext(), ImagePicker.class);
                    startActivityForResult(intent, IMAGE_PICKER_RESULTS);
                }
            } else
                Toast.makeText(MainActivity.this, R.string.permission_rejected, Toast.LENGTH_LONG).show();

        }
    });

    dialog_add_observation.setVisibility(View.GONE);
}

From source file:cn.ucai.yizhesale.activity.ChatActivity.java

protected void onChatRoomViewCreation() {

    final ProgressDialog pd = ProgressDialog.show(this, "", "Joining......");
    EMChatManager.getInstance().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {

        @Override/*www.  j a va2s.  c  om*/
        public void onSuccess(EMChatRoom value) {
            // TODO Auto-generated method stub
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                    room = EMChatManager.getInstance().getChatRoom(toChatUsername);
                    if (room != null) {
                        ((TextView) findViewById(cn.ucai.yizhesale.R.id.name)).setText(room.getName());
                    } else {
                        ((TextView) findViewById(cn.ucai.yizhesale.R.id.name)).setText(toChatUsername);
                    }
                    EMLog.d(TAG, "join room success : " + room.getName());

                    onConversationInit();

                    onListViewCreation();
                }
            });
        }

        @Override
        public void onError(final int error, String errorMsg) {
            // TODO Auto-generated method stub
            EMLog.d(TAG, "join room failure : " + error);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                }
            });
            finish();
        }
    });
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

public void publish(final Activity activity, final FbSimplePost post, final String pageId,
        final NewObjectListener listener) {

    if (!mFacebook.isSessionValid()) {

        login(activity, new SimpleRequestListener() {

            public void onFail(Throwable thr) {
                listener.onFail(thr);/*from w w w  .j a  va  2s  .co m*/
            }

            public void onCancel() {
                listener.onCancel();
            }

            public void onComplete() {
                publish(activity, post, pageId, listener);
            }
        });
    } else {

        final FbTextDialog dialog = new FbTextDialog(activity);
        dialog.setTitle(R.string.dialog_post_to_wall_title);
        dialog.setPlaceHolder(R.string.dialog_post_to_wall_placeholder);

        dialog.setDialogListener(new DialogListener() {

            public void onComplete(Bundle values) {

                final ProgressDialog spinner = new ProgressDialog(activity);
                spinner.setMessage(spinner.getContext().getString(R.string.loading));
                spinner.setCancelable(false);
                spinner.show();

                Bundle params = paramsForPost(post);
                params.putAll(values);

                facebookRequest(activity, pageId + "/feed", params, "POST", true, new RequestAdapter() {

                    public void onFail(Throwable thr, Object state) {
                        listener.onFail(thr);
                        spinner.dismiss();
                        dialog.dismiss();
                    }

                    public void onComplete(JSONObject jsonResponse, Object state) {
                        listener.onComplete(jsonResponse.optString("id"));
                        spinner.dismiss();
                        dialog.dismiss();
                    }

                    public void onCancel() {
                        listener.onCancel();
                        spinner.dismiss();
                        dialog.dismiss();
                    }
                });
            }

            public void onFacebookError(FacebookError e) {
                listener.onFail(e);
            }

            public void onError(DialogError e) {
                listener.onFail(e);
            }

            public void onCancel() {
                listener.onCancel();
            }
        });

        dialog.show();
    }
}