Example usage for android.app AlertDialog.Builder show

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

Introduction

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

Prototype

public void show() 

Source Link

Document

Start the dialog and display it on screen.

Usage

From source file:butter.droid.tv.fragments.TVOverviewFragment.java

private void openPlayerTestDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    final String[] file_types = getResources().getStringArray(R.array.file_types);
    final String[] files = getResources().getStringArray(R.array.files);

    builder.setTitle("Player Tests").setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override/*from  ww w .j a v  a  2s.c  o  m*/
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    }).setSingleChoiceItems(file_types, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int index) {
            dialogInterface.dismiss();
            final String location = files[index];
            if (location.equals("dialog")) {
                final EditText dialogInput = new EditText(getActivity());
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setView(dialogInput)
                        .setPositiveButton("Start", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Movie media = new Movie(new MoviesProvider(), new YSubsProvider());

                                media.videoId = "dialogtestvideo";
                                media.title = "User input test video";

                                TVVideoPlayerActivity.startActivity(getActivity(),
                                        new StreamInfo(media, null, null, null, null, location), 0);
                            }
                        });
                builder.show();
            }

            final Movie media = new Movie(new MoviesProvider(), new YSubsProvider());
            media.videoId = "bigbucksbunny";
            media.title = file_types[index];
            media.subtitles = new HashMap<>();
            media.subtitles.put("en", "http://sv244.cf/bbb-subs.srt");

            SubsProvider.download(getActivity(), media, "en", new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    TVVideoPlayerActivity.startActivity(getActivity(),
                            new StreamInfo(media, null, null, null, null, location));
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    TVVideoPlayerActivity.startActivity(getActivity(),
                            new StreamInfo(media, null, null, null, null, location));
                }
            });
        }
    });

    builder.show();
}

From source file:com.playrtc.sample.handler.PlayRTCHandler.java

@Override
public void onRing(final PlayRTC obj, final String peerId, final String peerUid) {

    activity.appnedLogMessage(">>[" + peerId + "] onRing....");
    AlertDialog.Builder alert = new AlertDialog.Builder(activity);
    alert.setTitle("PlayRTC");
    alert.setMessage(peerId + "? ? .");

    alert.setPositiveButton("", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();//  w  ww.j  av  a  2  s.c  o m

            Utils.showToast(activity, "[" + peerId + "] accept....");
            activity.appnedLogMessage(">>[" + peerId + "] accept....");

            obj.accept(peerId);
        }
    });
    alert.setNegativeButton("", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();

            Utils.showToast(activity, "[" + peerId + "] reject....");
            activity.appnedLogMessage(">>[" + peerId + "] reject....");

            obj.reject(peerId);
        }
    });
    alert.show();

}

From source file:com.sssemil.sonyirremote.ir.ir.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        setContentView(R.layout.settings_ir);
        main = false;//from   w  w  w .ja  v a 2  s .  c  om

        final GetAwItems getAwItems1 = new GetAwItems(ir.this);
        String ret = getAwItems1.execute().get();

        spinner6 = ((Spinner) findViewById(R.id.spinner6));
        spinner6.setSelection(0);

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                ar);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner6.setAdapter(dataAdapter);

        prepItemBrandArray();

        return true;
    } else if (id == R.id.action_about) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.about));
        PackageInfo pInfo = null;
        String version = "?";
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        version = pInfo.versionName;
        builder.setMessage(getResources().getString(R.string.license1) + " v" + version + "\n"
                + getResources().getString(R.string.license2) + "\n"
                + getResources().getString(R.string.license3) + "\n"
                + getResources().getString(R.string.license4));
        builder.setPositiveButton("OK", null);
        AlertDialog dialog = builder.show();

        TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
        messageView.setGravity(Gravity.CENTER);
        return true;
    } else if (id == R.id.action_exit) {
        stopIR();
        System.exit(0);
        return true;
    } else if (id == R.id.action_update) {
        update();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:gr.scify.newsum.ui.ViewActivity.java

@Override
public void run() {
    // take the String from the TopicActivity
    Bundle extras = getIntent().getExtras();
    Category = extras.getString(CATEGORY_INTENT_VAR);

    // Make sure we have updated the data source
    NewSumUiActivity.setDataSource(this);

    // Get user sources
    String sUserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

    // get Topics from TopicActivity (avoid multiple server calls)
    TopicInfo[] tiTopics = TopicActivity.getTopics(sUserSources, Category, this);

    // Also get Topic Titles, to display to adapter
    final String[] saTopicTitles = new String[tiTopics.length];
    // Also get Topic IDs
    final String[] saTopicIDs = new String[tiTopics.length];
    // Also get Dates, in order to show in summary title
    final String[] saTopicDates = new String[tiTopics.length];
    // DeHTML titles
    for (int iCnt = 0; iCnt < tiTopics.length; iCnt++) {
        // update Titles Array
        saTopicTitles[iCnt] = Html.fromHtml(tiTopics[iCnt].getTitle()).toString();
        // update IDs Array
        saTopicIDs[iCnt] = tiTopics[iCnt].getID();
        // update Date Array
        saTopicDates[iCnt] = tiTopics[iCnt].getPrintableDate(NewSumUiActivity.getDefaultLocale());
    }//from www.  j  a  v  a 2 s. co  m
    // get the value of the TopicIDs list size (to use in swipe)
    saTopicIDsLength = saTopicIDs.length;
    final TextView title = (TextView) findViewById(R.id.title);
    // Fill topic spinner
    final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, saTopicTitles);

    final TextView tx = (TextView) findViewById(R.id.textView1);
    //      final float minm = tx.getTextSize();
    //      final float maxm = (minm + 24);

    // Get active topic
    int iTopicNum;
    // If we have returned from a pause
    if (iPrvSelectedItem >= 0)
        // use previous selection before pause
        iTopicNum = iPrvSelectedItem;
    // else
    else
        // use selection from topic page
        iTopicNum = extras.getInt(TOPIC_ID_INTENT_VAR);
    final int num = iTopicNum;

    // create an invisible spinner just to control the summaries of the
    // category (i will use it later on Swipe)
    final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            spinner.setAdapter(adapter);

            // Scroll view init
            final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
            final String[] saTopicTitlesArg = saTopicTitles;
            final String[] saTopicIDsArg = saTopicIDs;
            final String[] SaTopicDatesArg = saTopicDates;

            // Add selection event
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    // Changing summary
                    loading = true;
                    showWaitingDialog();
                    // Update visibility of rating bar
                    final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar);
                    rb.setRating(0.0f);
                    rb.setVisibility(View.VISIBLE);
                    final TextView rateLbl = (TextView) findViewById(R.id.rateLbl);
                    rateLbl.setVisibility(View.VISIBLE);
                    scroll.scrollTo(0, 0);

                    String UserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

                    String[] saTopicIDs = saTopicIDsArg;

                    // track summary views per category and topic title
                    if (getAnalyticsPref()) {
                        EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, Category,
                                saTopicTitlesArg[arg2], 0l);
                    }

                    if (sCustomCategory.trim().length() > 0) {
                        if (Category.equals(sCustomCategory)) {
                            Context ctxCur = NewSumUiActivity.getAppContext(ViewActivity.this);
                            String sCustomCategoryURL = ctxCur.getResources()
                                    .getString(R.string.custom_category_url);
                            // Check if specific element needs to be read
                            String sElementID = ctxCur.getResources()
                                    .getString(R.string.custom_category_elementId);
                            // If an element needs to be selected
                            if (sElementID.trim().length() > 0) {
                                try {
                                    // Check if specific element needs to be read
                                    String sViewOriginalPage = ctxCur.getResources()
                                            .getString(R.string.custom_category_visit_source);
                                    // Init text by a link to the original page
                                    sText = "<p><a href='" + sCustomCategoryURL + "'>" + sViewOriginalPage
                                            + "</a></p>";
                                    // Get document
                                    Document doc = Jsoup.connect(sCustomCategoryURL).get();
                                    // If a table
                                    Element eCur = doc.getElementById(sElementID);
                                    if (eCur.tagName().equalsIgnoreCase("table")) {
                                        // Get table rows
                                        Elements eRows = eCur.select("tr");

                                        // For each row
                                        StringBuffer sTextBuf = new StringBuffer();
                                        for (Element eCurRow : eRows) {
                                            // Append content
                                            // TODO: Use HTML if possible. Now problematic (crashes when we click on link)
                                            sTextBuf.append("<p>" + eCurRow.text() + "</p>");
                                        }
                                        // Return as string
                                        sText = sText + sTextBuf.toString();
                                    } else
                                        // else get text
                                        sText = eCur.text();

                                } catch (IOException e) {
                                    // Show unavailable text
                                    sText = ctxCur.getResources()
                                            .getString(R.string.custom_category_unavailable);
                                    e.printStackTrace();
                                }

                            } else
                                sText = Utils.getFromHttp(sCustomCategoryURL, false);
                        }

                    } else {
                        // call getSummary with (sTopicID, sUserSources). Use "All" for
                        // all Sources
                        String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources);
                        // check if Summary exists, otherwise display message
                        if (Summary.length == 0) { // DONE APPLICATION HANGS, DOES NOT
                            // WORK. Updated: Probably OK
                            nothingFound = true;
                            AlertDialog.Builder al = new AlertDialog.Builder(ViewActivity.this);
                            al.setMessage(R.string.shouldReloadSummaries);
                            al.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // Reset cache
                                    CacheController.clearCache();
                                    // Restart main activity
                                    startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class)
                                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                                }
                            });
                            al.setCancelable(false);
                            al.show();
                            // Return to home activity
                            loading = false;
                            return;
                        }
                        // Generate Summary text for normal categories
                        sText = generateSummaryText(Summary, ViewActivity.this);
                        pText = generatesummarypost(Summary, ViewActivity.this);
                    }

                    // Update HTML
                    tx.setText(Html.fromHtml(sText));
                    // Allow links to be followed into browser
                    tx.setMovementMethod(LinkMovementMethod.getInstance());
                    // Also Add Date to Topic Title inside Summary
                    title.setText(saTopicTitlesArg[arg2] + " : " + SaTopicDatesArg[arg2]);

                    // Update size
                    updateTextSize();

                    // Update visited topics
                    TopicActivity.addVisitedTopicID(saTopicIDs[arg2]);
                    // Done
                    loading = false;
                    closeWaitingDialog();
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                }

            });

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // Get active topic
                    spinner.setSelection(num);
                }
            });

        }
    });

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            showHelpDialog();
        }
    });

    closeWaitingDialog();
}

From source file:org.yaoha.YaohaActivity.java

private void openFavMenu(final ImageButton btn, final TextView tv) {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    alert.setTitle("Adding favorite");
    alert.setMessage("Enter your favorite search");
    alert.setView(input);//  w  w w.j  av  a 2s  . c om

    alert.setPositiveButton("Set", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            final Editor edit = prefs.edit();
            String tmp = "";
            tv.setText(input.getText());
            btn.setImageResource(R.drawable.placeholder_logo);
            if (btn.getId() == button_favorite_1.getId()) {
                tmp = "saved_fav_1_text";
            } else if (btn.getId() == button_favorite_2.getId()) {
                tmp = "saved_fav_2_text";
            } else if (btn.getId() == button_favorite_3.getId()) {
                tmp = "saved_fav_3_text";
            } else if (btn.getId() == button_favorite_4.getId()) {
                tmp = "saved_fav_4_text";
            } else if (btn.getId() == button_favorite_5.getId()) {
                tmp = "saved_fav_5_text";
            } else if (btn.getId() == button_favorite_6.getId()) {
                tmp = "saved_fav_6_text";
            }
            edit.putString(tmp, input.getText().toString());
            edit.commit();
            //TODO add method to catch pre-defined store-icons
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled. 
        }
    });
    alert.show();
}

From source file:com.mocap.MocapFragment.java

private void saveDialog(final MyGLSurfaceView GLView) {

    try {/*from   w  w w. ja  v a  2s .  c  o  m*/
        AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
        builder1.setMessage(R.string.save_valid);
        builder1.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                try {

                    SaveOBJ(getActivity(), GLView);
                    //mSaveButton.setEnabled(false);
                    //mSaveButton.getDrawable().setAlpha(150);
                    //mStopButton.setEnabled(false);
                    //mStopButton.getDrawable().setAlpha(150);

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "Erreur save login: " + e, Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder1.setNegativeButton(R.string.Annuler, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                try {

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "Erreur save login: " + e, Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder1.show();
    } catch (Exception e) {
        Log.i(TAG, "Erreur dialog: " + e);
    }
}

From source file:net.fred.feedex.activity.EditFeedActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        finish();//from   w  w w  .jav a 2  s . c  o  m
        return true;
    case R.id.menu_validate: // only in insert mode
        final String name = mNameEditText.getText().toString().trim();
        final String urlOrSearch = mUrlEditText.getText().toString().trim();
        if (urlOrSearch.isEmpty()) {
            UiUtils.showMessage(EditFeedActivity.this, R.string.error_feed_error);
        }

        if (!urlOrSearch.contains(".") || !urlOrSearch.contains("/") || urlOrSearch.contains(" ")) {
            final ProgressDialog pd = new ProgressDialog(EditFeedActivity.this);
            pd.setMessage(getString(R.string.loading));
            pd.setCancelable(true);
            pd.setIndeterminate(true);
            pd.show();

            getLoaderManager().restartLoader(1, null,
                    new LoaderManager.LoaderCallbacks<ArrayList<HashMap<String, String>>>() {

                        @Override
                        public Loader<ArrayList<HashMap<String, String>>> onCreateLoader(int id, Bundle args) {
                            String encodedSearchText = urlOrSearch;
                            try {
                                encodedSearchText = URLEncoder.encode(urlOrSearch, Constants.UTF8);
                            } catch (UnsupportedEncodingException ignored) {
                            }

                            return new GetFeedSearchResultsLoader(EditFeedActivity.this, encodedSearchText);
                        }

                        @Override
                        public void onLoadFinished(Loader<ArrayList<HashMap<String, String>>> loader,
                                final ArrayList<HashMap<String, String>> data) {
                            pd.cancel();

                            if (data == null) {
                                UiUtils.showMessage(EditFeedActivity.this, R.string.error);
                            } else if (data.isEmpty()) {
                                UiUtils.showMessage(EditFeedActivity.this, R.string.no_result);
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(EditFeedActivity.this);
                                builder.setTitle(R.string.feed_search);

                                // create the grid item mapping
                                String[] from = new String[] { FEED_SEARCH_TITLE, FEED_SEARCH_DESC };
                                int[] to = new int[] { android.R.id.text1, android.R.id.text2 };

                                // fill in the grid_item layout
                                SimpleAdapter adapter = new SimpleAdapter(EditFeedActivity.this, data,
                                        R.layout.item_search_result, from, to);
                                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        FeedDataContentProvider.addFeed(EditFeedActivity.this,
                                                data.get(which).get(FEED_SEARCH_URL),
                                                name.isEmpty() ? data.get(which).get(FEED_SEARCH_TITLE) : name,
                                                mRetrieveFulltextCb.isChecked());

                                        setResult(RESULT_OK);
                                        finish();
                                    }
                                });
                                builder.show();
                            }
                        }

                        @Override
                        public void onLoaderReset(Loader<ArrayList<HashMap<String, String>>> loader) {
                        }
                    });
        } else {
            FeedDataContentProvider.addFeed(EditFeedActivity.this, urlOrSearch, name,
                    mRetrieveFulltextCb.isChecked());

            setResult(RESULT_OK);
            finish();
        }
        return true;
    case R.id.menu_add_filter: {
        final View dialogView = getLayoutInflater().inflate(R.layout.dialog_filter_edit, null);

        new AlertDialog.Builder(this) //
                .setTitle(R.string.filter_add_title) //
                .setView(dialogView) //
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        String filterText = ((EditText) dialogView.findViewById(R.id.filterText)).getText()
                                .toString();
                        if (filterText.length() != 0) {
                            String feedId = getIntent().getData().getLastPathSegment();

                            ContentValues values = new ContentValues();
                            values.put(FilterColumns.FILTER_TEXT, filterText);
                            values.put(FilterColumns.IS_REGEX,
                                    ((CheckBox) dialogView.findViewById(R.id.regexCheckBox)).isChecked());
                            values.put(FilterColumns.IS_APPLIED_TO_TITLE,
                                    ((RadioButton) dialogView.findViewById(R.id.applyTitleRadio)).isChecked());
                            values.put(FilterColumns.IS_ACCEPT_RULE,
                                    ((RadioButton) dialogView.findViewById(R.id.acceptRadio)).isChecked());

                            ContentResolver cr = getContentResolver();
                            cr.insert(FilterColumns.FILTERS_FOR_FEED_CONTENT_URI(feedId), values);
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    }
                }).show();
        return true;
    }
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.t2.compassionMeditation.Graphs1Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()");

    // We don't want the screen to timeout in this activity
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView
    setContentView(R.layout.graphs_activity_layout);
    mInstance = this;

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true);
    mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false);
    mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false);

    mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false);

    if (mAntHrmEnabled) {
        mHeartRateSource = HEARTRATE_ANT;
    } else {/*from  www.  j  a v a 2 s  . c  o  m*/
        mHeartRateSource = HEARTRATE_ZEPHYR;
    }

    // The session start time will be used as session id
    // Note this also sets session start time
    // **** This session ID will be prepended to all JSON data stored
    //      in the external database until it's changed (by the start
    //      of a new session.
    Calendar cal = Calendar.getInstance();
    SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
    String sessionDate = sdf.format(new Date());
    String userId = SharedPref.getString(this, "SelectedUser", "");
    long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0);

    mDataOutHandler = new DataOutHandler(this, userId, sessionDate, mAppId,
            DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId);

    if (mDatabaseEnabled) {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String myNumber = telephonyManager.getLine1Number();

        String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name",
                getString(R.string.database_uri));
        //            remoteDatabaseUri += myNumber; 

        Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove
        try {
            mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName,
                    remoteDatabaseUri);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
        mDataOutHandler.setRequiresAuthentication(false);

    }

    mBioDataProcessor.initialize(mDataOutHandler);

    if (mLoggingEnabled) {
        mDataOutHandler.enableLogging(this);
    }

    if (mLogCatEnabled) {
        mDataOutHandler.enableLogCat();
    }

    // Log the version
    try {
        PackageManager packageManager = getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
        mApplicationVersion = info.versionName;
        String versionString = mAppId + " application version: " + mApplicationVersion;

        DataOutPacket packet = new DataOutPacket();
        packet.add(DataOutHandlerTags.version, versionString);
        try {
            mDataOutHandler.handleDataOut(packet);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }

    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    // Set up UI elements
    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();

    mPauseButton = (Button) findViewById(R.id.buttonPause);
    mAddMeasureButton = (Button) findViewById(R.id.buttonAddMeasure);
    mTextInfoView = (TextView) findViewById(R.id.textViewInfo);
    mMeasuresDisplayText = (TextView) findViewById(R.id.measuresDisplayText);

    // Don't actually show skin conductance meter unless we get samples
    ImageView image = (ImageView) findViewById(R.id.imageView1);
    image.setImageResource(R.drawable.signal_bars0);

    // Check to see of there a device configured for EEG, if so then show the skin conductance meter
    String tmp = SharedPref.getString(this, "EEG", null);

    if (tmp != null) {
        image.setVisibility(View.VISIBLE);
    } else {
        image.setVisibility(View.INVISIBLE);
    }

    // Initialize SPINE by passing the fileName with the configuration properties
    try {
        mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, "Exception creating SPINE manager: " + e.toString());
        e.printStackTrace();
    }

    try {
        currentMindsetData = new MindsetData(this);
    } catch (Exception e1) {
        Log.e(TAG, "Exception creating MindsetData: " + e1.toString());
        e1.printStackTrace();
    }

    // Establish nodes for BSPAN

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);

    int itemId = 0;
    eegPos = itemId; // eeg always comes first
    mBioParameters.clear();

    // First create GraphBioParameters for each of the EEG static params (ie mindset)
    for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation
        GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true);
        param.isShimmer = false;
        mBioParameters.add(param);
    }

    // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, EEG, HR, Skin Temp, Resp Rate
    //       String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names);
    String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names_less_eeg);

    for (String paramName : paramNamesStringArray) {
        if (paramName.equalsIgnoreCase("not assigned"))
            continue;

        GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true);

        if (paramName.equalsIgnoreCase("gsr")) {
            gsrPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("emg")) {
            emgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("ecg")) {
            ecgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("heart rate")) {
            heartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("resp rate")) {
            respRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("skin temp")) {
            skinTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Airflow")) {
            eHealthAirFlowPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Temp")) {
            eHealthTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth SpO2")) {
            eHealthSpO2Pos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Heartrate")) {
            eHealthHeartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth GSR")) {
            eHealthGSRPos = itemId;
            param.isShimmer = false;
        }

        itemId++;
        mBioParameters.add(param);
    }

    // Since These are static nodes (Non-spine) we have to manually put them in the active node list
    Node mindsetNode = null;
    mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor
    mManager.getActiveNodes().add(mindsetNode);

    Node zepherNode = null;
    zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR));
    mManager.getActiveNodes().add(zepherNode);

    // The arduino node is programmed to look like a static Spine node
    // Note that currently we don't have  to turn it on or off - it's always streaming
    // Since Spine (in this case) is a static node we have to manually put it in the active node list
    // Since the 
    final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001
    mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE));
    mManager.getActiveNodes().add(mSpineNode);

    final String sessionName;

    // Check to see if we were requested to play back a previous session
    try {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            sessionName = bundle.getString(BioZenConstants.EXTRA_SESSION_NAME);

            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Replay Session " + sessionName + "?");
            alert.setMessage("Make sure to turn off all Bluetooth Sensors!");

            alert.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    try {
                        mDataOutHandler.logNote("Replaying data from session " + sessionName);
                    } catch (DataOutHandlerException e) {
                        Log.e(TAG, e.toString());
                        e.printStackTrace();
                    }

                    replaySessionData(sessionName);
                    AlertDialog.Builder alert1 = new AlertDialog.Builder(mInstance);
                    alert1.setTitle("INFO");
                    alert1.setMessage("Replay of session complete!");
                    alert1.show();

                }
            });
            alert.show();
        }

    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

    if (mInternalSensorMonitoring) {
        // IntentSender Launches our service scheduled with with the alarm manager 
        mBigBrotherService = PendingIntent.getService(Graphs1Activity.this, 0,
                new Intent(Graphs1Activity.this, BigBrotherService.class), 0);

        long firstTime = SystemClock.elapsedRealtime();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000,
                mBigBrotherService);

        // Tell the user about what we did.
        Toast.makeText(Graphs1Activity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show();

    }

    //testFIRFilter();

    //       testHR();

}

From source file:net.evecom.android.PublicOpinionLookActivity.java

/**
 * //from  w  w  w  .  j  a v  a 2 s .  c  om
 * 
 * @param v
 */
public void opinion_more_delete(View v) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(PublicOpinionLookActivity.this);
    builder.setTitle("");
    builder.setIcon(R.drawable.qq_dialog_default_icon);// 
    builder.setMessage("");
    builder.setPositiveButton("", new DialogInterface.OnClickListener() {
        // @Override
        public void onClick(DialogInterface dialog, int which) {
            progressDialog = ProgressDialog.show(PublicOpinionLookActivity.this, "", "...");

            formSubmit();

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

}