Example usage for android.widget EditText getText

List of usage examples for android.widget EditText getText

Introduction

In this page you can find the example usage for android.widget EditText getText.

Prototype

@Override
    public Editable getText() 

Source Link

Usage

From source file:com.piusvelte.sonet.core.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);/* w  w w .  j  av  a2  s.  c  om*/
    mHttpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Sonet.Accounts.SERVICE, Sonet.INVALID_SERVICE);
            mServiceName = Sonet.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Sonet.EXTRA_ACCOUNT_ID, Sonet.INVALID_ACCOUNT_ID);
            mSonetWebView = new SonetWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mSonetOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mSonetWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mSonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mSonetWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            case MYSPACE:
                mSonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET);
                asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE,
                        MYSPACE_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case FOURSQUARE:
                mSonetWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mSonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Sonet.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            case IDENTICA:
                mSonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET);
                asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case GOOGLEPLUS:
                mSonetWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            case CHATTER:
                mSonetWebView
                        .open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
                break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:com.piusvelte.sonet.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);/*from   w w w .java  2s .co  m*/
    mHttpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Sonet.Accounts.SERVICE, Sonet.INVALID_SERVICE);
            mServiceName = Sonet.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Sonet.EXTRA_ACCOUNT_ID, Sonet.INVALID_ACCOUNT_ID);
            mSonetWebView = new SonetWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mSonetOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mSonetWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mSonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mSonetWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL,
                        BuildConfig.FACEBOOK_ID, FACEBOOK_CALLBACK.toString()));
                break;
            case MYSPACE:
                mSonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET);
                asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE,
                        MYSPACE_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case FOURSQUARE:
                mSonetWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, BuildConfig.FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mSonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Sonet.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            case IDENTICA:
                mSonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET);
                asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case GOOGLEPLUS:
                mSonetWebView.open(String.format(GOOGLEPLUS_AUTHORIZE, BuildConfig.GOOGLECLIENT_ID,
                        "urn:ietf:wg:oauth:2.0:oob"));
                break;
            case CHATTER:
                mSonetWebView.open(String.format(CHATTER_URL_AUTHORIZE, BuildConfig.CHATTER_KEY,
                        CHATTER_CALLBACK.toString()));
                break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:it.feio.android.omninotes.SettingsFragment.java

private void export(View v) {
    final List<String> backups = Arrays.asList(StorageHelper.getExternalStoragePublicDir().list());

    // Sets default export file name
    SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_EXPORT);
    String fileName = sdf.format(Calendar.getInstance().getTime());
    final EditText fileNameEditText = (EditText) v.findViewById(R.id.export_file_name);
    final TextView backupExistingTextView = (TextView) v.findViewById(R.id.backup_existing);
    fileNameEditText.setHint(fileName);/*  w w  w .  j  a v a  2 s  .c  o m*/
    fileNameEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            if (backups.contains(arg0.toString())) {
                backupExistingTextView.setText(R.string.backup_existing);
            } else {
                backupExistingTextView.setText("");
            }
        }
    });

    new MaterialDialog.Builder(getActivity()).title(R.string.data_export_message).customView(v, false)
            .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog materialDialog) {
                    AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_export_data");
                    // An IntentService will be launched to accomplish the export task
                    Intent service = new Intent(getActivity(), DataBackupIntentService.class);
                    service.setAction(DataBackupIntentService.ACTION_DATA_EXPORT);
                    String backupName = StringUtils.isEmpty(fileNameEditText.getText().toString())
                            ? fileNameEditText.getHint().toString()
                            : fileNameEditText.getText().toString();
                    service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, backupName);
                    getActivity().startService(service);
                }
            }).build().show();
}

From source file:com.shafiq.myfeedle.core.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);/*w  ww.  j a  va 2  s . c om*/
    mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE);
            mServiceName = Myfeedle.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID);
            mMyfeedleWebView = new MyfeedleWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mMyfeedleWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            // case MYSPACE:
            //     mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET);
            //     asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case FOURSQUARE:
                mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Myfeedle.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            // case IDENTICA:
            //     mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET);
            //     asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case GOOGLEPLUS:
                mMyfeedleWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            // case CHATTER:
            //     mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
            //     break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:au.com.wallaceit.reddinator.SubredditSelectActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.subredditselect);

    // load personal list from saved prefereces, if null use default and save
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(SubredditSelectActivity.this);
    global = ((GlobalObjects) SubredditSelectActivity.this.getApplicationContext());

    // get subreddit list and set adapter
    subredditList = global.getSubredditManager().getSubredditNames();
    subsAdapter = new MySubredditsAdapter(this, subredditList);
    ListView subListView = (ListView) findViewById(R.id.sublist);
    subListView.setAdapter(subsAdapter);
    subListView.setTextFilterEnabled(true);
    subListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String subreddit = ((TextView) view.findViewById(R.id.subreddit_name)).getText().toString();
            global.getSubredditManager().setFeedSubreddit(mAppWidgetId, subreddit);
            updateFeedAndFinish();/*  ww w .j  a v a  2  s .com*/
            //System.out.println(sreddit+" selected");
        }
    });
    subsAdapter.sort(new Comparator<String>() {
        @Override
        public int compare(String s, String t1) {
            return s.compareToIgnoreCase(t1);
        }
    });
    // get multi list and set adapter
    mMultiAdapter = new MyMultisAdapter(this);
    ListView multiListView = (ListView) findViewById(R.id.multilist);
    multiListView.setAdapter(mMultiAdapter);
    multiListView.setTextFilterEnabled(true);
    multiListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == mMultiAdapter.getCount() - 1) {
                LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_multi_add,
                        parent, false);
                final EditText name = (EditText) layout.findViewById(R.id.new_multi_name);
                AlertDialog.Builder builder = new AlertDialog.Builder(SubredditSelectActivity.this);
                builder.setTitle("Create A Multi").setView(layout)
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (name.getText().toString().equals("")) {
                                    Toast.makeText(SubredditSelectActivity.this,
                                            "Please enter a name for the multi", Toast.LENGTH_LONG).show();
                                    return;
                                }
                                new SubscriptionEditTask(SubscriptionEditTask.ACTION_MULTI_CREATE)
                                        .execute(name.getText().toString());
                                dialogInterface.dismiss();
                            }
                        }).show();
            } else {
                JSONObject multiObj = mMultiAdapter.getItem(position);
                try {
                    String name = multiObj.getString("display_name");
                    String path = multiObj.getString("path");
                    global.getSubredditManager().setFeed(mAppWidgetId, name, path, true);
                    updateFeedAndFinish();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(SubredditSelectActivity.this, "Error setting multi.", Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    });

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            mAppWidgetId = 0; // Id of 4 zeros indicates its the app view, not a widget, that is being updated
        } else {
            String action = getIntent().getAction();
            widgetFirstTimeSetup = action != null
                    && action.equals("android.appwidget.action.APPWIDGET_CONFIGURE");
        }
    } else {
        mAppWidgetId = 0;
    }

    final ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(new SimpleTabsAdapter(new String[] { "My Subreddits", "My Multis" },
            new int[] { R.id.sublist, R.id.multilist }, SubredditSelectActivity.this, null));

    LinearLayout tabsLayout = (LinearLayout) findViewById(R.id.tab_widget);
    tabs = new SimpleTabsWidget(SubredditSelectActivity.this, tabsLayout);
    tabs.setViewPager(pager);

    addButton = (Button) findViewById(R.id.addsrbutton);
    addButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent(SubredditSelectActivity.this, ViewAllSubredditsActivity.class);
            startActivityForResult(intent, 1);
        }
    });
    refreshButton = (Button) findViewById(R.id.refreshloginbutton);
    refreshButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (global.mRedditData.isLoggedIn()) {
                if (pager.getCurrentItem() == 1) {
                    refreshMultireddits();
                } else {
                    refreshSubreddits();
                }
            } else {
                global.mRedditData.initiateLogin(SubredditSelectActivity.this);
            }
        }
    });
    // sort button
    sortBtn = (Button) findViewById(R.id.sortselect);
    String sortTxt = "Sort:  "
            + mSharedPreferences.getString("sort-" + (mAppWidgetId == 0 ? "app" : mAppWidgetId), "hot");
    sortBtn.setText(sortTxt);
    sortBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            showSortDialog();
        }
    });

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    // set theme colors
    setThemeColors();

    GlobalObjects.doShowWelcomeDialog(SubredditSelectActivity.this);
}

From source file:com.dycody.android.idealnote.SettingsFragment.java

private void export(View v) {
    final List<String> backups = Arrays.asList(StorageHelper.getExternalStoragePublicDir().list());

    // Sets default export file name
    SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_EXPORT);
    String fileName = sdf.format(Calendar.getInstance().getTime());
    final EditText fileNameEditText = (EditText) v.findViewById(R.id.export_file_name);
    final TextView backupExistingTextView = (TextView) v.findViewById(R.id.backup_existing);
    fileNameEditText.setHint(fileName);/*from  ww w .  j  av a  2 s  . com*/
    fileNameEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            if (backups.contains(arg0.toString())) {
                backupExistingTextView.setText(R.string.backup_existing);
            } else {
                backupExistingTextView.setText("");
            }
        }
    });

    new MaterialDialog.Builder(getActivity()).title(R.string.data_export_message).customView(v, false)
            .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog materialDialog) {
                    ((IdealNote) getActivity().getApplication()).getAnalyticsHelper()
                            .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_export_data");
                    // An IntentService will be launched to accomplish the export task
                    Intent service = new Intent(getActivity(), DataBackupIntentService.class);
                    service.setAction(DataBackupIntentService.ACTION_DATA_EXPORT);
                    String backupName = StringUtils.isEmpty(fileNameEditText.getText().toString())
                            ? fileNameEditText.getHint().toString()
                            : fileNameEditText.getText().toString();
                    service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, backupName);
                    getActivity().startService(service);
                }
            }).build().show();
}

From source file:com.andrewshu.android.reddit.profile.ProfileActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;//from w w  w.j  a va 2 s  .co  m
    ProgressDialog pdialog;
    AlertDialog.Builder builder;
    LayoutInflater inflater;
    View layout; // used for inflated views for AlertDialog.Builder.setView()

    switch (id) {
    case Constants.DIALOG_LOGIN:
        dialog = new LoginDialog(this, mSettings, false) {
            @Override
            public void onLoginChosen(String user, String password) {
                dismissDialog(Constants.DIALOG_LOGIN);
                new MyLoginTask(user, password).execute();
            }
        };
        break;

    case Constants.DIALOG_COMPOSE:
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        builder = new AlertDialog.Builder(this);
        layout = inflater.inflate(R.layout.compose_dialog, null);
        final EditText composeDestination = (EditText) layout.findViewById(R.id.compose_destination_input);
        final EditText composeSubject = (EditText) layout.findViewById(R.id.compose_subject_input);
        final EditText composeText = (EditText) layout.findViewById(R.id.compose_text_input);
        final Button composeSendButton = (Button) layout.findViewById(R.id.compose_send_button);
        final Button composeCancelButton = (Button) layout.findViewById(R.id.compose_cancel_button);
        final EditText composeCaptcha = (EditText) layout.findViewById(R.id.compose_captcha_input);
        composeDestination.setText(mUsername);

        dialog = builder.setView(layout).create();
        final Dialog composeDialog = dialog;
        composeSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                ThingInfo hi = new ThingInfo();
                // reddit.com performs these sanity checks too.
                if ("".equals(composeDestination.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "please enter a username", Toast.LENGTH_LONG).show();
                    return;
                }
                if ("".equals(composeSubject.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "please enter a subject", Toast.LENGTH_LONG).show();
                    return;
                }
                if ("".equals(composeText.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "you need to enter a message", Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                if (composeCaptcha.getVisibility() == View.VISIBLE
                        && "".equals(composeCaptcha.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "", Toast.LENGTH_LONG).show();
                    return;
                }
                hi.setDest(composeDestination.getText().toString().trim());
                hi.setSubject(composeSubject.getText().toString().trim());
                new MyMessageComposeTask(composeDialog, hi, composeCaptcha.getText().toString().trim())
                        .execute(composeText.getText().toString().trim());
                dismissDialog(Constants.DIALOG_COMPOSE);
            }
        });
        composeCancelButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dismissDialog(Constants.DIALOG_COMPOSE);
            }
        });
        break;

    case Constants.DIALOG_THREAD_CLICK:
        inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        builder = new AlertDialog.Builder(this);
        dialog = builder.setView(inflater.inflate(R.layout.thread_click_dialog, null)).create();
        break;

    // "Please wait"
    case Constants.DIALOG_LOGGING_IN:
        pdialog = new ProgressDialog(this);
        pdialog.setMessage("Logging in...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(false);
        dialog = pdialog;
        break;
    case Constants.DIALOG_REPLYING:
        pdialog = new ProgressDialog(this);
        pdialog.setMessage("Sending reply...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(false);
        dialog = pdialog;
        break;
    case Constants.DIALOG_COMPOSING:
        pdialog = new ProgressDialog(this);
        pdialog.setMessage("Composing message...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(false);
        dialog = pdialog;
        break;

    default:
        throw new IllegalArgumentException("Unexpected dialog id " + id);
    }
    return dialog;
}

From source file:jp.watnow.plugins.dialog.Notification.java

/**
 * /* w w w .jav  a  2 s.c  om*/
 * @param message
 * @param title
 * @param buttonLabels
 * @param defaultTexts
 * @param callbackContext
 */
public synchronized void login(final String title, final String message, final JSONArray buttonLabels,
        final JSONArray defaultTexts, final CallbackContext callbackContext) {

    final CordovaInterface cordova = this.cordova;

    Runnable runnable = new Runnable() {
        public void run() {
            LinearLayout layout = new LinearLayout(cordova.getActivity());
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setPadding(10, 0, 10, 0);
            final EditText usernameInput = new EditText(cordova.getActivity());
            usernameInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
            final EditText passwordInput = new EditText(cordova.getActivity());
            passwordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            try {
                usernameInput.setHint("ID");
                usernameInput.setText(defaultTexts.getString(0));
                passwordInput.setHint("PASSWORD");
                passwordInput.setText(defaultTexts.getString(1));
            } catch (JSONException e1) {
            }

            layout.addView(usernameInput, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            layout.addView(passwordInput, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            dlg.setMessage(message);
            dlg.setTitle(title);
            dlg.setCancelable(false);

            dlg.setView(layout);

            final JSONObject result = new JSONObject();

            try {
                dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        try {
                            result.put("buttonIndex", 1);
                            result.put("input1", usernameInput.getText());
                            result.put("input2", passwordInput.getText());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                    }
                });
            } catch (JSONException e) {
            }

            try {
                dlg.setPositiveButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        try {
                            result.put("buttonIndex", 3);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                    }
                });
            } catch (JSONException e) {
            }

            dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    try {
                        result.put("buttonIndex", 0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                }
            });

            changeTextDirection(dlg);
        };
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:com.mediaexplorer.remote.MexRemoteActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//w ww .j  ava 2s .c o  m

    this.setTitle(R.string.app_name);
    dbg = "MexWebremote";

    text_view = (TextView) findViewById(R.id.text);

    web_view = (WebView) findViewById(R.id.link_view);
    web_view.getSettings().setJavaScriptEnabled(true);/*
                                                      /* Future: setOverScrollMode is API level >8
                                                      * web_view.setOverScrollMode (OVER_SCROLL_NEVER);
                                                      */

    web_view.setBackgroundColor(0);

    web_view.setWebViewClient(new WebViewClient() {
        /* for some reason we only get critical errors so an auth error
         * is not handled here which is why there is some crack that test
         * the connection with a special httpclient
         */
        @Override
        public void onReceivedHttpAuthRequest(final WebView view, final HttpAuthHandler handler,
                final String host, final String realm) {
            String[] userpass = new String[2];

            userpass = view.getHttpAuthUsernamePassword(host, realm);

            HttpResponse response = null;
            HttpGet httpget;
            DefaultHttpClient httpclient;
            String target_host;
            int target_port;

            target_host = MexRemoteActivity.this.target_host;
            target_port = MexRemoteActivity.this.target_port;

            /* We may get null from getHttpAuthUsernamePassword which will
             * break the setCredentials so junk used instead to keep
             * it happy.
             */

            Log.d(dbg, "using the set httpauth, testing auth using client");
            try {
                if (userpass == null) {
                    userpass = new String[2];
                    userpass[0] = "none";
                    userpass[1] = "none";
                }
            } catch (Exception e) {
                userpass = new String[2];
                userpass[0] = "none";
                userpass[1] = "none";
            }

            /* Log.d ("debug",
             *  "trying: GET http://"+userpass[0]+":"+userpass[1]+"@"+target_host+":"+target_port+"/");
             */
            /* We're going to test the authentication credentials that we
             * have before using them so that we can act on the response.
             */

            httpclient = new DefaultHttpClient();

            httpget = new HttpGet("http://" + target_host + ":" + target_port + "/");

            httpclient.getCredentialsProvider().setCredentials(new AuthScope(target_host, target_port),
                    new UsernamePasswordCredentials(userpass[0], userpass[1]));

            try {
                response = httpclient.execute(httpget);
            } catch (IOException e) {
                Log.d(dbg, "Problem executing the http get");
                e.printStackTrace();
            }

            Log.d(dbg, "HTTP reponse:" + Integer.toString(response.getStatusLine().getStatusCode()));
            if (response.getStatusLine().getStatusCode() == 401) {
                /* We got Authentication failed (401) so ask user for u/p */

                /* login dialog box */
                final AlertDialog.Builder logindialog;
                final EditText user;
                final EditText pass;

                LinearLayout layout;
                LayoutParams params;

                TextView label_username;
                TextView label_password;

                logindialog = new AlertDialog.Builder(MexRemoteActivity.this);

                logindialog.setTitle("Mex Webremote login");

                user = new EditText(MexRemoteActivity.this);
                pass = new EditText(MexRemoteActivity.this);

                layout = new LinearLayout(MexRemoteActivity.this);

                pass.setTransformationMethod(new PasswordTransformationMethod());

                layout.setOrientation(LinearLayout.VERTICAL);

                params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

                layout.setLayoutParams(params);
                user.setLayoutParams(params);
                pass.setLayoutParams(params);

                label_username = new TextView(MexRemoteActivity.this);
                label_password = new TextView(MexRemoteActivity.this);

                label_username.setText("Username:");
                label_password.setText("Password:");

                layout.addView(label_username);
                layout.addView(user);
                layout.addView(label_password);
                layout.addView(pass);
                logindialog.setView(layout);

                logindialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });

                logindialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String uvalue = user.getText().toString().trim();
                        String pvalue = pass.getText().toString().trim();
                        view.setHttpAuthUsernamePassword(host, realm, uvalue, pvalue);

                        handler.proceed(uvalue, pvalue);
                    }
                });
                logindialog.show();
                /* End login dialog box */
            } else /* We didn't get a 401 */
            {
                handler.proceed(userpass[0], userpass[1]);
            }
        } /* End onReceivedHttpAuthRequest */
    }); /* End Override */

    /* Run mdns to check for service in a "runnable" (async) */
    handler.post(new Runnable() {
        public void run() {
            startMdns();
        }
    });

    dialog = ProgressDialog.show(MexRemoteActivity.this, "", "Searching...", true);

    /* Let's put something in the webview while we're waiting */
    String summary = "<html><head><style>body { background-color: #000000; color: #ffffff; }></style></head><body><p>Searching for the media explorer webservice</p><p>More infomation on <a href=\"http://media-explorer.github.com\" >Media Explorer's home page</a></p></body></html>";
    web_view.loadData(summary, "text/html", "utf-8");

}

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Display dialog to the user for the browser bookmarks. Allow the user to add a
 * browser bookmark to an existing row or a new row.
 * //from w  w w  .  ja va2s  . c o m
 * @param context
 */
public static void displayAddBrowserBookmark(final Launcher context) {
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.add_browser_bookmarks_list);

    final EditText nameEditText = (EditText) dialog.findViewById(R.id.rowName);
    final RadioButton currentRadioButton = (RadioButton) dialog.findViewById(R.id.currentRadio);
    currentRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // hide the row name edit field if the current row radio button
            // is selected
            nameEditText.setVisibility(View.GONE);
        }

    });
    final RadioButton newRadioButton = (RadioButton) dialog.findViewById(R.id.newRadio);
    newRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // show the row name edit field if the new radio button is
            // selected
            nameEditText.setVisibility(View.VISIBLE);
            nameEditText.requestFocus();
        }

    });

    ListView listView = (ListView) dialog.findViewById(R.id.list);
    final ArrayList<BookmarkInfo> bookmarks = loadBookmarks(context);
    Collections.sort(bookmarks, new Comparator<BookmarkInfo>() {

        @Override
        public int compare(BookmarkInfo lhs, BookmarkInfo rhs) {
            return lhs.getTitle().toLowerCase().compareTo(rhs.getTitle().toLowerCase());
        }

    });
    listView.setAdapter(new BookmarkAdapter(context, bookmarks));
    listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            // run in thread since network logic needed to get bookmark icon
            new Thread(new Runnable() {
                public void run() {
                    // if the new row radio button is selected, the user must enter
                    // a name for the new row
                    String name = nameEditText.getText().toString().trim();
                    if (newRadioButton.isChecked() && name.length() == 0) {
                        nameEditText.requestFocus();
                        displayAlert(context, context.getString(R.string.dialog_new_row_name_alert));
                        return;
                    }
                    boolean currentRow = !newRadioButton.isChecked();
                    try {
                        BookmarkInfo bookmark = (BookmarkInfo) parent.getAdapter().getItem(position);
                        int rowId = 0;
                        int rowPosition = 0;
                        if (currentRow) {
                            rowId = context.getCurrentGalleryId();
                            ArrayList<ItemInfo> items = ItemsTable.getItems(context, rowId);
                            rowPosition = items.size(); // in last
                            // position
                            // for selected
                            // row
                        } else {
                            rowId = (int) RowsTable.insertRow(context, name, 0, RowInfo.FAVORITE_TYPE);
                            rowPosition = 0;
                        }
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(bookmark.getUrl()));

                        Uri uri = Uri.parse(bookmark.getUrl());
                        Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost());
                        String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost());
                        Log.d(LOG_TAG, "icon1=" + icon);
                        if (icon == null) {
                            // try base host address
                            int count = StringUtils.countMatches(uri.getHost(), ".");
                            if (count > 1) {
                                int index = uri.getHost().indexOf('.');
                                String baseHost = uri.getHost().substring(index + 1);
                                icon = Utils.getWebSiteIcon(context, "http://" + baseHost);
                                Log.d(LOG_TAG, "icon2=" + icon);
                            }
                        }

                        ItemsTable.insertItem(context, rowId, rowPosition, bookmark.getTitle(), intent, icon,
                                DatabaseHelper.SHORTCUT_TYPE);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "displayAddBrowserBookmark", e);
                    }

                    // need to do this on UI thread
                    context.getHandler().post(new Runnable() {
                        public void run() {
                            context.showCover(false);
                            dialog.dismiss();
                            context.reloadAllGalleries();
                        }
                    });

                    if (currentRow) {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK);
                    } else {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK_WITH_ROW);
                    }

                }
            }).start();
        }
    });
    listView.setDrawingCacheEnabled(true);
    listView.setOnKeyListener(onKeyListener);
    dialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            context.showCover(false);
        }

    });
    context.showCover(true);
    dialog.show();
    Analytics.logEvent(Analytics.DIALOG_ADD_BROWSER_BOOKMARK);
}