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:org.catrobat.catroid.ui.controller.LookController.java

public void copyLook(int position, ArrayList<LookData> lookDataList, final Activity activity,
        LookFragment fragment) {//from  w ww. j  a v a  2  s  .  com
    LookData lookData = lookDataList.get(position);

    try {
        String projectName = ProjectManager.getInstance().getCurrentProject().getName();

        StorageHandler.getInstance().copyImage(projectName, lookData.getAbsolutePath(), null);

        String imageName = lookData.getLookName() + "_" + activity.getString(R.string.copy_addition);
        String imageFileName = lookData.getLookFileName();

        updateLookAdapter(imageName, imageFileName, lookDataList, fragment);
    } catch (IOException ioException) {
        Utils.showErrorDialog(activity, R.string.error_load_image);
        Log.e(TAG, Log.getStackTraceString(ioException));
    }
    activity.sendBroadcast(new Intent(ScriptActivity.ACTION_BRICK_LIST_CHANGED));
}

From source file:com.activiti.android.platform.provider.transfer.ContentTransferManager.java

public static void requestUpload(Fragment fr, Uri uri, String objectId, int type, String mimetyp) {
    Cursor cursor = null;/*from   w  w w  .ja  v  a  2  s  .co m*/
    String name = null, source, sourceId, mimetype = mimetyp;
    try {
        Bundle settingsBundle = new Bundle();

        // Retrieve other info
        cursor = fr.getActivity().getContentResolver().query(uri, null, null, null, null);

        if (cursor == null && uri != null) {
            // Is it a file ?
            File file = new File(uri.getPath());
            if (file.exists()) {
                // It's a file
                name = file.getName();
                settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_CONTENT_PATH, file.getPath());
                if (mimetype == null) {
                    MimeType mime = MimeTypeManager.getInstance(fr.getActivity()).getMimetype(file.getName());
                    mimetype = (mime != null) ? mime.getMimeType() : mimetyp;
                }
            }
        } else if (cursor != null && cursor.moveToFirst()) {
            name = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME));
            mimetype = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE));
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_CONTENT_URI, uri.toString());
        } else {
            throw new Exception("Cursor is empty");
        }

        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);

        settingsBundle.putInt(ContentTransferSyncAdapter.ARGUMENT_MODE,
                ContentTransferSyncAdapter.MODE_SAF_UPLOAD);
        settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_FILE_PATH, name);
        if (type == TYPE_TASK_ID) {
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_TASK_ID, objectId);
        } else if (type == TYPE_PROCESS_ID) {
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_PROCESS_ID, objectId);
        } else if (type == TYPE_PROFILE_ID) {
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_PROFILE_ID, objectId);
        }
        settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_MIMETYPE, mimetype);
        ContentResolver.requestSync(
                ActivitiAccountManager.getInstance(fr.getActivity()).getCurrentAndroidAccount(),
                ContentTransferProvider.AUTHORITY, settingsBundle);
    } catch (Exception e) {
        Log.w("COntent Transfer", Log.getStackTraceString(e));
    } finally {
        CursorUtils.closeCursor(cursor);
    }
}

From source file:hku.fyp14017.blencode.ui.controller.LookController.java

public void copyLook(int position, ArrayList<LookData> lookDataList, final Activity activity,
        LookFragment fragment) {//from   ww w . jav a  2 s .c om
    LookData lookData = lookDataList.get(position);

    try {
        String projectName = ProjectManager.getInstance().getCurrentProject().getName();

        StorageHandler.getInstance().copyImage(projectName, lookData.getAbsolutePath(), null);

        String imageName = lookData.getLookName() + "_"
                + activity.getString(hku.fyp14017.blencode.R.string.copy_addition);
        String imageFileName = lookData.getLookFileName();

        updateLookAdapter(imageName, imageFileName, lookDataList, fragment);
    } catch (IOException ioException) {
        Utils.showErrorDialog(activity, hku.fyp14017.blencode.R.string.error_load_image);
        Log.e(TAG, Log.getStackTraceString(ioException));
    }
    activity.sendBroadcast(new Intent(ScriptActivity.ACTION_BRICK_LIST_CHANGED));
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private HttpClient createHttpClient() {
    if (httpUserAgent == null) {
        final PackageManager pm = getPackageManager();
        String applicationVersion = "0";
        try {//from   w  w w  . j a va 2 s  . com
            final PackageInfo pkgInfo = pm.getPackageInfo(getPackageName(), 0);
            applicationVersion = pkgInfo.versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
        httpUserAgent = "FreeMobileNetstat/" + applicationVersion + " Android/" + Build.VERSION.SDK_INT;
    }

    final HttpClient client = new HttpClient(this);
    client.setConnectTimeout(10000);
    client.setReadTimeout(20000);
    client.setUserAgent(httpUserAgent);
    return client;
}

From source file:io.teak.sdk.TeakNotification.java

static void displayNotification(Context context, TeakNotification teakNotif, Notification nativeNotification) {
    if (notificationManager == null) {
        try {/*from   w  w  w  . ja v a 2s  .  c o m*/
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        } catch (Exception e) {
            Log.e(LOG_TAG, Log.getStackTraceString(e));
            return;
        }
    }

    // Send it out
    if (Teak.isDebug) {
        Log.d(LOG_TAG, "Showing Notification");
        Log.d(LOG_TAG, "       Teak id: " + teakNotif.teakNotifId);
        Log.d(LOG_TAG, "   Platform id: " + teakNotif.platformId);
    }
    notificationManager.notify(NOTIFICATION_TAG, teakNotif.platformId, nativeNotification);

    // TODO: Here is where any kind of thread/update logic will live
}

From source file:com.huison.DriverAssistant_Web.util.LoginHelper.java

public static void changePassword(final BaseActivity activity, final String username, final String phone,
        final String oldPassword, final String newPassword) {
    UmengEventSender.sendEvent(activity, UmengEventTypes.changePW);
    final ProgressDialog pd = new ProgressDialog(activity);
    pd.setMessage("");
    pd.show();/*from w  ww  .j  a  v a2s.c  o  m*/
    AsyncHttpClient client = activity.getAsyncHttpClient();
    RequestParams params = new RequestParams();
    /*
     * Map<String, String> map = new HashMap<String, String>();
     * map.put("sessionkey", BaseActivity.getSESSIONKEY());
     * map.put("userid", username); map.put("mob", phone);
     * map.put("oldpasswork", oldPassword); map.put("passwork",
     * newPassword); map.put("version", activity.getVersionName());
     * params.put("action", CHANGE_PASSWORD_ACTION); params.put("xml",
     * BaseActivity.getXML(map));
     */
    try {
        JSONObject p = new JSONObject();
        p.put("mobile", phone);
        p.put("password", oldPassword);
        p.put("method", "editpassword");
        p.put("version", activity.getVersionName());
        p.put("devicetype", "android");
        p.put("newpassword", newPassword);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());// 
        String time = formatter.format(curDate);
        p.put("time", time);
        Log.v("", p.toString());
        String data = Util.DesJiaMi(p.toString(), "czxms520");
        // Log.v("",data);
        params.put("data", data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    client.post(BaseActivity.REQUESTURL, params, new JsonHttpResponseHandler() {
        @Override
        public void onDispatchSuccess(int statusCode, Header[] headers, String result) {
            try {
                result = Util.decrypt(result, "czxms520");
                Log.v(TAG, "JSON" + result);
                JSONObject jo = new JSONObject(result);
                String code = jo.getString("code");
                String msg = getJSONValueAsString(jo, "message");
                if (code.equals("0")) {
                    // jo = jo.getJSONObject("data");
                    activity.showMessageBoxAndFinish(msg);
                    activity.setPassword(newPassword);
                } else {
                    activity.showMessageBox(msg);
                }
            } catch (JSONException e) {
                activity.showMessageBox(activity.getText(R.string.server404));
                Log.e("change password error", Log.getStackTraceString(e));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailureAnyway(int statusCode, Header[] headers, Throwable throwable,
                BaseBinaryResponse jsonResponse) {
            pd.dismiss();
            activity.showMessageBox(activity.getText(R.string.server404));
        }

        @Override
        public void onSuccessAnyway(int statusCode, Header[] headers, BaseBinaryResponse jsonResponse) {
            pd.dismiss();
            // ChangePasswordActivity.instance.finish();
        }
    });
    TimeCounter.countTime(activity, pd);
}

From source file:de.madvertise.android.sdk.MadvertiseUtil.java

static void logMessage(final String tag, final int level, String message, Throwable throwable,
        StackTraceElement stackTraceElement) {
    String logTag = tag;//from w  w  w  . j  av  a 2s  .c om
    if (!PRINT_LOG) {
        return;
    }

    if (tag == null) {
        logTag = MadvertiseUtil.LOG;
    }

    if (message == null) {
        message = "";
    }

    String fullClassName = stackTraceElement.getClassName();
    String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
    int lineNumber = stackTraceElement.getLineNumber();

    String logMessage = "(" + className + ":" + lineNumber + ") : " + message;
    if (throwable != null) {
        logMessage += '\n' + Log.getStackTraceString(throwable);
    }
    Log.println(level, logTag, logMessage);
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private String getDeviceId() {
    final SQLiteDatabase db = dbHelper.getWritableDatabase();
    String deviceId = null;//from  w ww.  j av a  2  s.  co  m
    Cursor deviceCursor = null;
    try {
        deviceCursor = db.query("device_testing", new String[] { "device_id" }, null, null, null, null, null);
        if (deviceCursor.moveToNext()) {
            deviceId = deviceCursor.getString(0);
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (deviceCursor != null)
                deviceCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }
    if (deviceId == null) {
        // Generate a new device identifier.
        deviceId = UUID.randomUUID().toString();

        // Store this device identifier in the database.
        final ContentValues cv = new ContentValues(1);
        cv.put("device_id", deviceId);
        db.insertOrThrow("device_testing", null, cv);
    }
    return deviceId;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java

private void runTests() {

    MobileServiceClient client = null;/*  ww  w .  j av  a2  s.  c  om*/

    try {
        client = createMobileServiceClient();
    } catch (MalformedURLException e) {
        createAndShowDialog(e, "Error");
    }

    // getMobileServiceRuntimeFeatures(client);

    final TestGroup group = (TestGroup) mTestGroupSpinner.getSelectedItem();
    logWithTimestamp(new Date(), "Tests for group \'" + group.getName() + "\'");

    logSeparator();

    final MobileServiceClient currentClient = client;

    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
            || Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // For android versions 4.0.x
        // Run a first Void AsyncTask on UI thread to enable the possibility
        // of running others on sub threads
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                return null;
            }
        }.execute();

    }

    Thread thread = new Thread() {

        @Override
        public void run() {
            group.runTests(currentClient, new TestExecutionCallback() {

                @Override
                public void onTestStart(TestCase test) {
                    final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }

                    });

                    log("TEST START", test.getName());
                }

                @Override
                public void onTestGroupComplete(TestGroup group, List<TestResult> results) {
                    log("TEST GROUP COMPLETED", group.getName() + " - " + group.getStatus().toString());
                    logSeparator();

                    if (group.getName().startsWith(TestGroup.AllTestsGroupName)) {

                        List<TestCase> tests = new ArrayList<TestCase>();

                        for (TestResult result : results) {
                            tests.add(result.getTestCase());
                        }

                        DaylightLogger logger = new DaylightLogger(getDaylightURL(), getDaylightProject(),
                                getDaylightClientId(), getDaylightClientSecret(), getDaylightRuntime(),
                                getDaylightRunId());
                        try {
                            logger.reportResultsToDaylight(group.getFailedTestCount(), group.getStartTime(),
                                    group.getEndTime(), tests, group.getSourceMap());
                        } catch (Throwable e) {
                            log(e.getMessage());
                        }
                    }

                    if (shouldRunUnattended()) {
                        // String logContent = mLog.toString();
                        // postLogs(logContent, true);

                        boolean passed = true;
                        for (TestResult result : results) {
                            if (result.getStatus() != TestStatus.Passed) {
                                passed = false;
                                break;
                            }
                        }

                        try {
                            String sdCard = Environment.getExternalStorageDirectory().getPath();
                            FileOutputStream fos = new FileOutputStream(sdCard + "/done_android_e2e.txt");
                            OutputStreamWriter osw = new OutputStreamWriter(fos);
                            BufferedWriter bw = new BufferedWriter(osw);
                            bw.write("Completed successfully.\n");
                            bw.write(passed ? "PASSED" : "FAILED");
                            bw.write("\n");
                            bw.close();
                            osw.close();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onTestComplete(TestCase test, TestResult result) {
                    Throwable e = result.getException();
                    if (e != null) {
                        StringBuilder sb = new StringBuilder();
                        while (e != null) {
                            sb.append(e.getClass().getSimpleName() + ": ");
                            sb.append(e.getMessage());
                            sb.append("\n");
                            sb.append(Log.getStackTraceString(e));
                            sb.append("\n\n");
                            e = e.getCause();
                        }

                        test.log("Exception: " + sb.toString());
                    }

                    final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();

                        }

                    });
                    logWithTimestamp(test.getStartTime(),
                            "Logs for test " + test.getName() + " (" + result.getStatus().toString() + ")");
                    String testLogs = test.getLog();
                    if (testLogs.length() > 0) {
                        if (testLogs.endsWith("\n")) {
                            testLogs = testLogs.substring(0, testLogs.length() - 1);
                        }
                        log(testLogs);
                    }

                    logWithTimestamp(test.getEndTime(), "Test " + result.getStatus().toString());
                    logWithTimestamp(test.getEndTime(), "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
                    logSeparator();
                }
            });
        }
    };

    thread.start();
}

From source file:org.proninyaroslav.libretorrent.fragments.DetailTorrentFragment.java

private void initFragments() {
    if (viewPager != null) {
        return;//w  w  w .  j  a  v  a 2s. c om
    }

    ArrayList<BencodeFileItem> files = null;
    ArrayList<Priority> priorities = null;

    if (infoCache != null) {
        files = infoCache.getFiles();
    }

    if (torrent != null && files != null) {
        /*
         * The index position in array must be
         * equal to the priority position in array
         */
        priorities = new ArrayList<>();
        List<Integer> torrentPriorities = torrent.getFilePriorities();

        for (int i = 0; i < torrentPriorities.size(); i++) {
            priorities.add(Priority.fromSwig(torrentPriorities.get(i)));
        }
    }

    DetailTorrentInfoFragment fragmentInfo = DetailTorrentInfoFragment.newInstance(torrent, infoCache);
    DetailTorrentStateFragment fragmentState = DetailTorrentStateFragment.newInstance(infoCache);
    DetailTorrentFilesFragment fragmentFiles = DetailTorrentFilesFragment.newInstance(files, priorities);
    DetailTorrentTrackersFragment fragmentTrackers = DetailTorrentTrackersFragment.newInstance();
    DetailTorrentPeersFragment fragmentPeers = DetailTorrentPeersFragment.newInstance();
    DetailTorrentPiecesFragment fragmentPieces = DetailTorrentPiecesFragment
            .newInstance(infoCache.getNumPieces(), infoCache.getPieceLength());

    viewPager = (ViewPager) activity.findViewById(R.id.detail_torrent_viewpager);

    if (viewPager == null) {
        return;
    }

    /* Removing previous ViewPagerAdapter fragments, if any */
    if (Utils.isTablet(activity.getApplicationContext())) {
        android.support.v4.app.FragmentManager fm = activity.getSupportFragmentManager();
        List<android.support.v4.app.Fragment> fragments = fm.getFragments();

        if (fragments != null) {
            FragmentTransaction ft = fm.beginTransaction();
            for (android.support.v4.app.Fragment f : fragments) {
                if (f != null) {
                    ft.remove(f);
                }
            }

            ft.commitAllowingStateLoss();
        }
    }

    adapter = new ViewPagerAdapter(activity.getSupportFragmentManager());
    adapter.addFragment(fragmentInfo, INFO_FRAG_POS, getString(R.string.torrent_info));
    adapter.addFragment(fragmentState, STATE_FRAG_POS, getString(R.string.torrent_state));
    adapter.addFragment(fragmentFiles, FILE_FRAG_POS, getString(R.string.torrent_files));
    adapter.addFragment(fragmentTrackers, TRACKERS_FRAG_POS, getString(R.string.torrent_trackers));
    adapter.addFragment(fragmentPeers, PEERS_FRAG_POS, getString(R.string.torrent_peers));
    adapter.addFragment(fragmentPieces, PIECES_FRAG_POS, getString(R.string.torrent_pieces));
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(6);
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            /* Nothing */
        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
            case STATE_FRAG_POS:
                DetailTorrentStateFragment stateFrag = (DetailTorrentStateFragment) adapter
                        .getItem(STATE_FRAG_POS);
                if (stateFrag != null) {
                    stateFrag.setState(stateCache);
                    stateFrag.setActiveAndSeedingTime(activeTimeCache, seedingTimeCache);
                }
                break;
            case FILE_FRAG_POS:
                DetailTorrentFilesFragment fileFrag = (DetailTorrentFilesFragment) adapter
                        .getItem(FILE_FRAG_POS);
                if (fileFrag != null) {
                    fileFrag.setFilesReceivedBytes(stateCache.filesReceivedBytes);
                }
                break;
            case TRACKERS_FRAG_POS:
                DetailTorrentTrackersFragment trackersFrag = (DetailTorrentTrackersFragment) adapter
                        .getItem(TRACKERS_FRAG_POS);
                if (trackersFrag != null) {
                    trackersFrag.setTrackersList(new ArrayList<>(trackersCache.getAll()));
                }
                break;
            case PEERS_FRAG_POS:
                DetailTorrentPeersFragment peersFrag = (DetailTorrentPeersFragment) adapter
                        .getItem(PEERS_FRAG_POS);
                if (peersFrag != null) {
                    peersFrag.setPeerList(new ArrayList<>(peersCache.getAll()));
                }
                break;
            case PIECES_FRAG_POS:
                DetailTorrentPiecesFragment piecesFrag = (DetailTorrentPiecesFragment) adapter
                        .getItem(PIECES_FRAG_POS);

                if (piecesFrag != null) {
                    piecesFrag.setPieces(piecesCache);
                    piecesFrag.setDownloadedPiecesCount(stateCache.downloadedPieces);
                }
                break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            /* Nothing */
        }
    });
    tabLayout = (TabLayout) activity.findViewById(R.id.detail_torrent_tabs);

    int colorId = (childInActionMode ? R.color.action_mode : R.color.primary);
    setTabLayoutColor(colorId);

    tabLayout.setupWithViewPager(viewPager);

    if (bound && serviceCallback != null) {
        try {
            ipc.sendTorrentStateOneShot(serviceCallback, clientCallback);

        } catch (RemoteException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }
}