Example usage for android.util Log getStackTraceString

List of usage examples for android.util Log getStackTraceString

Introduction

In this page you can find the example usage for android.util Log getStackTraceString.

Prototype

public static String getStackTraceString(Throwable tr) 

Source Link

Document

Handy function to get a loggable stack trace from a Throwable

Usage

From source file:net.olejon.mdapp.InteractionsCardsActivity.java

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

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*w w w.  j av  a2  s. c  om*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_interactions_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.interactions_cards_toolbar);
    mToolbar.setTitle(getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.interactions_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.interactions_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.interactions_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No interactions
    mNoInteractionsLayout = (LinearLayout) findViewById(R.id.interactions_cards_no_interactions);

    Button noInteractionsButton = (Button) findViewById(R.id.interactions_cards_no_interactions_button);

    noInteractionsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "http://interaksjoner.no/analyser.asp?PreparatNavn="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&submit1=Sjekk");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("InteractionsCards", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(InteractionsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

                                                SQLiteDatabase sqLiteDatabase = new InteractionsSQLiteHelper(
                                                        mContext).getWritableDatabase();

                                                sqLiteDatabase.delete(InteractionsSQLiteHelper.TABLE,
                                                        InteractionsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(InteractionsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(R.string.interactions_cards_search)
                                                        + ": \"" + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoInteractionsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("InteractionsCards", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("InteractionsCards", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("InteractionsCards", Log.getStackTraceString(e));
    }
}

From source file:net.olejon.mdapp.ClinicalTrialsCardsActivity.java

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

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();//  ww w .  ja  v a2  s .c  om

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_clinicaltrials_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.clinicaltrials_cards_toolbar);
    mToolbar.setTitle(getString(R.string.clinicaltrials_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.clinicaltrials_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.clinicaltrials_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.clinicaltrials_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new ClinicalTrialsCardsAdapter(mContext, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No clinical trials
    mNoClinicalTrialsLayout = (LinearLayout) findViewById(R.id.clinicaltrials_cards_no_clinicaltrials);

    Button noClinicalTrialsButton = (Button) findViewById(R.id.clinicaltrials_cards_no_results_button);

    noClinicalTrialsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.clinicaltrials_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "https://clinicaltrials.gov/ct2/results?term="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&no_unk=Y");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(ClinicalTrialsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

                                                SQLiteDatabase sqLiteDatabase = new ClinicalTrialsSQLiteHelper(
                                                        mContext).getWritableDatabase();

                                                sqLiteDatabase.delete(ClinicalTrialsSQLiteHelper.TABLE,
                                                        ClinicalTrialsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(ClinicalTrialsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(
                                                        getString(R.string.clinicaltrials_cards_search) + ": \""
                                                                + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoClinicalTrialsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("ClinicalTrialsCards", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
    }
}

From source file:net.olejon.mdapp.NotificationsFromSlvAdapter.java

@Override
public void onBindViewHolder(NotificationViewHolder viewHolder, int i) {
    try {/*from   ww w. j  a va 2s  .  c o m*/
        final JSONObject notificationsJsonObject = mNotifications.getJSONObject(i);

        viewHolder.title.setText(notificationsJsonObject.getString("title"));
        viewHolder.date.setText(notificationsJsonObject.getString("date"));
        viewHolder.type.setText(notificationsJsonObject.getString("type"));
        viewHolder.message.setText(notificationsJsonObject.getString("message"));

        final String title = notificationsJsonObject.getString("title");
        final String uri = notificationsJsonObject.getString("uri");

        if (uri.equals("")) {
            viewHolder.uriSeparator.setVisibility(View.GONE);
            viewHolder.uri.setVisibility(View.GONE);
        } else {
            viewHolder.uriSeparator.setVisibility(View.VISIBLE);
            viewHolder.uri.setVisibility(View.VISIBLE);

            viewHolder.title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (uri.matches("^https?://.*?\\.pdf$")) {
                        mTools.downloadFile(title, uri);
                    } else {
                        Intent intent = new Intent(mContext, MainWebViewActivity.class);
                        intent.putExtra("title", title);
                        intent.putExtra("uri", uri);
                        mContext.startActivity(intent);
                    }
                }
            });

            viewHolder.uri.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (uri.matches("^https?://.*?\\.pdf$")) {
                        mTools.downloadFile(title, uri);
                    } else {
                        Intent intent = new Intent(mContext, MainWebViewActivity.class);
                        intent.putExtra("title", title);
                        intent.putExtra("uri", uri);
                        mContext.startActivity(intent);
                    }
                }
            });
        }

        animateView(viewHolder.card, i);
    } catch (Exception e) {
        Log.e("NotificationsFromSlv", Log.getStackTraceString(e));
    }
}

From source file:org.alfresco.mobile.android.application.operations.batch.sync.SyncPrepareThread.java

@Override
protected LoaderResult<Void> doInBackground() {
    LoaderResult<Void> result = new LoaderResult<Void>();
    try {/*from   w w  w .  j av  a 2s.co  m*/
        Log.d(TAG, "Sync Scan Started");
        result = super.doInBackground();

        // Timestamp the scan process
        SynchroManager.saveStartSyncPrepareTimestamp(context);
        syncScanningTimeStamp = new GregorianCalendar(TimeZone.getTimeZone("GMT")).getTimeInMillis();

        // DISPATCHER
        // Depending on what we want to achieve we use the associated helper
        if (syncManager.hasActivateSync(acc)) {
            if (syncManager.canSyncEverything(acc)) {
                // SYNC ANYTHING
                group = new PrepareSyncHelper(context, this, syncScanningTimeStamp).prepare();
            } else {
                // FAVORITE SYNC
                group = new PrepareFavoriteSyncHelper(context, this, syncScanningTimeStamp).prepare();
            }
        } else {
            // FAVORITE (WITHOUT CONTENT)
            group = new PrepareFavoriteHelper(context, this, syncScanningTimeStamp).prepare();
        }

        // Retrieve the result of the scan
        SyncScanInfo currentSyncScan = syncManager.getScanInfo(getAccount());

        switch (currentSyncScan.getScanResult()) {
        // Normal Case
        // Scan is Success ==> Launch the sync
        case SyncScanInfo.RESULT_SUCCESS:
            if (group != null && !group.getRequests().isEmpty()) {
                syncManager.enqueue(group);
            }
            break;
        // Warning Case
        // Scan raised a warning ==> request user decision
        case SyncScanInfo.RESULT_WARNING_LOW_STORAGE:
        case SyncScanInfo.RESULT_WARNING_MOBILE_DATA:
            syncManager.saveOperationGroup(group);
            break;
        // ERROR Case
        // Scan raised an error ==> alert the user
        case SyncScanInfo.RESULT_ERROR_NOT_ENOUGH_STORAGE:
            group = null;
            break;
        default:
            break;
        }

        // Flag the execution of last sync
        currentSyncScan.save(context, acc);
        SynchroManager.saveSyncPrepareTimestamp(context);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
        result.setException(e);
    } finally {
        CursorUtils.closeCursor(localSyncCursor);
    }
    return result;
}

From source file:com.dm.wallpaper.board.fragments.dialogs.RefreshDurationFragment.java

private void setDividerColor(NumberPicker picker) {
    java.lang.reflect.Field[] pickerFields = NumberPicker.class.getDeclaredFields();
    for (java.lang.reflect.Field pf : pickerFields) {
        if (pf.getName().equals("mSelectionDivider")) {
            pf.setAccessible(true);/*from   w  w  w  . ja v  a2 s.c o  m*/
            try {
                int color = ColorHelper.getAttributeColor(getActivity(), R.attr.colorAccent);
                pf.set(picker, DrawableHelper.getTintedDrawable(getActivity(), R.drawable.numberpicker_divider,
                        color));
            } catch (Exception e) {
                LogUtil.e(Log.getStackTraceString(e));
            }
            break;
        }
    }
}

From source file:net.olejon.mdapp.MessageIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final Context mContext = this;

    final MyTools mTools = new MyTools(mContext);

    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    int projectVersionCode = mTools.getProjectVersionCode();

    String device = mTools.getDevice();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            getString(R.string.project_website_uri) + "api/1/message/?version_code=" + projectVersionCode
                    + "&device=" + device,
            new Response.Listener<JSONObject>() {
                @SuppressLint("InlinedApi")
                @Override/*from w w  w . ja  va  2 s .  c o  m*/
                public void onResponse(JSONObject response) {
                    try {
                        final long id = response.getLong("id");
                        final String title = response.getString("title");
                        final String message = response.getString("message");
                        final String bigMessage = response.getString("big_message");
                        final String button = response.getString("button");
                        final String uri = response.getString("uri");

                        final long lastId = mTools.getSharedPreferencesLong("MESSAGE_LAST_ID");

                        mTools.setSharedPreferencesLong("MESSAGE_LAST_ID", id);

                        if (lastId != 0 && id != lastId) {
                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                    R.drawable.ic_launcher);

                            NotificationManagerCompat notificationManager = NotificationManagerCompat
                                    .from(mContext);
                            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                    mContext);

                            notificationBuilder.setWhen(mTools.getCurrentTime()).setAutoCancel(true)
                                    .setPriority(Notification.PRIORITY_HIGH)
                                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                                    .setCategory(Notification.CATEGORY_MESSAGE).setLargeIcon(bitmap)
                                    .setSmallIcon(R.drawable.ic_local_hospital_white_24dp)
                                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                    .setLights(Color.BLUE, 1000, 2000).setTicker(message).setContentTitle(title)
                                    .setContentText(message)
                                    .setStyle(new NotificationCompat.BigTextStyle().bigText(bigMessage));

                            if (!uri.equals("")) {
                                Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                PendingIntent launchPendingIntent = PendingIntent.getActivity(mContext, 0,
                                        launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                                notificationBuilder.setContentIntent(launchPendingIntent).addAction(
                                        R.drawable.ic_local_hospital_white_24dp, button, launchPendingIntent);
                            }

                            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
                        }
                    } catch (Exception e) {
                        Log.e("MessageIntentService", Log.getStackTraceString(e));
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("MessageIntentService", error.toString());
                }
            });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(jsonObjectRequest);
}

From source file:net.olejon.mdapp.BarcodeScannerActivity.java

@Override
public void handleResult(Result result) {
    mTools.showToast(getString(R.string.barcode_scanner_wait), 0);

    String barcode = result.getText();

    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            getString(R.string.project_website_uri) + "api/1/barcode/?search=" + barcode,
            new Response.Listener<JSONObject>() {
                @Override/*w  w  w  . j  av a2s  . c o m*/
                public void onResponse(JSONObject response) {
                    try {
                        String medicationName = response.getString("name");

                        if (medicationName.equals("")) {
                            mTools.showToast(getString(R.string.barcode_scanner_no_results), 1);

                            finish();
                        } else {
                            SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext)
                                    .getReadableDatabase();

                            String[] queryColumns = { SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID };
                            Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_MEDICATIONS,
                                    queryColumns,
                                    SlDataSQLiteHelper.MEDICATIONS_COLUMN_NAME + " LIKE "
                                            + mTools.sqe("%" + medicationName + "%") + " COLLATE NOCASE",
                                    null, null, null, null);

                            if (cursor.moveToFirst()) {
                                long id = cursor.getLong(
                                        cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID));

                                Intent intent = new Intent(mContext, MedicationActivity.class);

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    if (mTools.getDefaultSharedPreferencesBoolean(
                                            "MEDICATION_MULTIPLE_DOCUMENTS"))
                                        intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                                                | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
                                }

                                intent.putExtra("id", id);
                                startActivity(intent);
                            }

                            cursor.close();
                            sqLiteDatabase.close();

                            finish();
                        }
                    } catch (Exception e) {
                        mTools.showToast(getString(R.string.barcode_scanner_no_results), 1);

                        Log.e("BarcodeScannerActivity", Log.getStackTraceString(e));

                        finish();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("FelleskatalogenService", error.toString());
                }
            });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(jsonObjectRequest);
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private void handleException(Exception ex, CallbackContext callbackContext) {

    Log.e("SecureLocalStorage", "exception", ex);

    PluginResult pluginResult;//from   ww w.  j a v a  2s .  c  om
    JSONObject error = new JSONObject();
    try {
        error.put("message", ex.getMessage());
        error.put("trace", Log.getStackTraceString(ex));
        pluginResult = new PluginResult(PluginResult.Status.ERROR, error);
    } catch (JSONException jsex) {
        pluginResult = new PluginResult(PluginResult.Status.ERROR, ex.getMessage());
    }

    pluginResult.setKeepCallback(false);
    callbackContext.sendPluginResult(pluginResult);
}

From source file:net.olejon.mdapp.PoisoningsCardsActivity.java

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

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*  w ww.jav a 2  s  .c o  m*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_poisonings_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.poisonings_cards_toolbar);
    mToolbar.setTitle(getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.poisonings_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.poisonings_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.poisonings_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new PoisoningsCardsAdapter(mContext, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No poisonings
    mNoPoisoningsLayout = (LinearLayout) findViewById(R.id.poisonings_cards_no_poisonings);

    Button noPoisoningsHelsenorgeButton = (Button) findViewById(R.id.poisonings_cards_check_on_helsenorge);
    Button noPoisoningsHelsebiblioteketButton = (Button) findViewById(
            R.id.poisonings_cards_check_on_helsebiblioteket);

    noPoisoningsHelsenorgeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "https://helsenorge.no/sok/giftinformasjon/?k="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8"));
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
            }
        }
    });

    noPoisoningsHelsebiblioteketButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri",
                        "http://www.helsebiblioteket.no/forgiftninger/alle-anbefalinger?cx=005475784484624053973%3A3bnj2dj_uei&ie=UTF-8&q="
                                + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&sa=S%C3%B8k");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(PoisoningsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

                                                SQLiteDatabase sqLiteDatabase = new PoisoningsSQLiteHelper(
                                                        mContext).getWritableDatabase();

                                                sqLiteDatabase.delete(PoisoningsSQLiteHelper.TABLE,
                                                        PoisoningsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(PoisoningsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(R.string.poisonings_cards_search)
                                                        + ": \"" + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoPoisoningsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("PoisoningsCardsActivity", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
    }
}

From source file:com.maxwen.wallpaper.board.fragments.dialogs.CreditsFragment.java

private void getData() {
    mGetCredits = new AsyncTask<Void, Void, Boolean>() {

        List<Credit> credits;

        @Override//from  w w w.  ja  v  a  2 s. c om
        protected void onPreExecute() {
            super.onPreExecute();
            credits = new ArrayList<>();
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            while (!isCancelled()) {
                try {
                    Thread.sleep(1);
                    int res = getResource(mType);
                    if (res == -1)
                        return false;
                    XmlPullParser xpp = getActivity().getResources().getXml(res);

                    while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                        if (xpp.getEventType() == XmlPullParser.START_TAG) {
                            if (mType == Extras.TYPE_CONTRIBUTORS) {
                                if (xpp.getName().equals("contributor")) {
                                    Credit credit = new Credit(xpp.getAttributeValue(null, "name"),
                                            xpp.getAttributeValue(null, "contribution"),
                                            xpp.getAttributeValue(null, "link"));
                                    credits.add(credit);
                                }
                            }
                        }
                        xpp.next();
                    }
                    return true;
                } catch (Exception e) {
                    LogUtil.e(Log.getStackTraceString(e));
                    return false;
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                mListView.setAdapter(new CreditsAdapter(getActivity(), credits));
            } else {
                dismiss();
            }
            mGetCredits = null;
        }
    }.execute();
}