Brendan Brendan - 7 months ago 27
Java Question

How should I log to the UI in Android?

I'm trying to find a good way to display log messages in a TextView in an Activity. I tried to display logcat messages in the TextView, but the results vary every time I open and close the Fragment and not all messages are shown. I'm logging in multiple Activities and classes, so I'm trying to find a way to log without coupling it to every class. Is there an alternative to logcat or something, some type of system logging that I could access and display? Or any useful libraries or anything?



I ended up saving the history to a member variable and only appending the new log lines each time I open the dialog.

public class LogsDialogFragment extends DialogFragment {

    private StringBuilder log = new StringBuilder();

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Sets the Layout for the UI
        LayoutInflater i = getActivity().getLayoutInflater();
        View rootView = i.inflate(R.layout.fragment_logs_dialog, null);

        TextView logTextView = (TextView) rootView.findViewById(;
        logTextView.setMovementMethod(new ScrollingMovementMethod());

        try {
            Process process = Runtime.getRuntime().exec("logcat -d");
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            StringBuilder log = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(WifiDirectHandler.LOG_TAG)){
                    // Removes log tag and PID from the log line
                    log.append(line.substring(line.indexOf(": ") + 2)).append("\n");

            this.log.append(log.toString().replace(this.log.toString(), ""));
        } catch (IOException e) {
            Log.e("wifiDirectHandler", "Failure reading logcat");

        // Creates and returns the AlertDialog for the logs
        AlertDialog.Builder dialogBuilder =  new  AlertDialog.Builder(getActivity())
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
        return dialogBuilder.create();