How to see large debug message - android

I use android Log class for general purpose debugging but now the need is to display large text in the device itself as logcat message are truncated and inconvenient.
I tried to create a popup window with a textview inside but it seems like I cannot place it anywhere I want, if I do it may get WindowLeaked error etc.
I would like to place the debug window anywhere on the ui system such as anywhere in the activity class or Views.
Does android has any built-in debug-ui, something like
Dialog.debug(String message);
Otherwise what hack will require to achieve that?
EDIT
This I need not for viewing LogCat log but seeing any random variables in code.

Use this
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
class ReadLogDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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) {
log.append(line);
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
} catch (IOException e) { }
}
}
Courtesy: log to be viewed in activity

Related

Android Studio: how to use streamscraper, to get shoutcast metadata

I'm a newbie in Android Development. I want to get metadata from Shoutcast Server, and found streamscraper to be the easiest one to use. But my problem is, I don't know how to use it. The homepage itself only showing something like in how to use it:
import java.net.URI;
import java.util.List;
import net.moraleboost.streamscraper.Stream;
import net.moraleboost.streamscraper.Scraper;
import net.moraleboost.streamscraper.scraper.IceCastScraper;
public class Harvester {
public static void main(String[] args) throws Exception {
Scraper scraper = new IceCastScraper();
List streams = scraper.scrape(new URI("http://host:port/"));
for (Stream stream: streams) {
System.out.println("Song Title: " + stream.getCurrentSong());
System.out.println("URI: " + stream.getUri());
}
}
}
Searched anywhere and found no project sample of how to use this. I hope one of you can post the code of how to use it, or make a tutorial for it.
No need to use external libraries. The following pages give you:
Current song: http://yourstream:port/currentsong?sid=#
Last 20 songs: http://yourstream:port/played.html?sid#
Next songs: http://yourstream:port/nextsongs?sid=#
An Android java class which prints the current song:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class NowPlaying {
public void CurrentSong() {
try
{
URL url = new URL("http://www.mofosounds.com:8000/currentsong?sid=#");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
Note: the nextsongs?sid=#feature must be supported by the player of the stream.

XML simple parsing

I have a question about parsing (Android Studio). It is not about something in particular. My code just doesn't run. No errors. I want to be able to press a button and show a specific text, parsed from an XML file.
For now, i'll omit the button part and throw you the codes just for printing this text on a humble textview
XML CODE (app/src/main/assets follder. articles.xml)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE articles[
<!ELEMENT articles ANY>
<!ELEMENT article ANY>
<!ATTLIST article ID ID #IMPLIED> ]>
<articles>
<article ID="a1">TEST
</article>
<article ID="a2">1.TEST2
</article>
CLASS CODE
package com.blah.blah;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MainActivity extends AppCompatActivity {
TextView textView;
String stringArticle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager assetManager = this.getAssets();
InputStream inputStream = null;
try {
// Loads your XML file as an InputStream
inputStream = assetManager.open("articles");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element article = doc.getElementById("a1");
String stringArticle = article.getTextContent();
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringArticle);
} catch (IOException e) {
// Exception Handling Code
e.printStackTrace();
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
I haven't tried the techniques that return you a Nodelist, because I dont want to iterate over anything. I find it useless for my project. What I want is something extremely primitive. It's like those simple bible apps. You press the button with the verse and the corresponding text pops up. That simple.
And again, no errors at all! Just not working. I think the TRY part is not executed. Because it gives me the default 'hello world' text on the TextView. But, once i put the
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringarticle);
lines after the TRY/CATCH blocks, I just get an empty TextView.
TY!
You can place your XML file in "app/src/main/assets" directory. After that you can easily access your XML file via "AssetManager" class.
You can use below code as a reference:-
AssetManager assetManager = this.getAssets();
InputStream inputStream = null;
try {
// Loads your XML file as an InputStream
inputStream = assetManager.open("articles.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element article = doc.getElementById("1");
String stringarticle = article.getTextContent();
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringarticle);
} catch (IOException e) {
// Exception Handling Code
e.printStackTrace();
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
Just Remember to place your file in mentioned directory, otherwise "AssetManager" class won't be able to read it.
Cheers !!

Trying to use class HttpsURLConnection in android studio, getting a error saying cannot resolve symbol HttpsURLConnection

I have a class developed in eclipse (on the same computer ) and I am trying to bring it over to Android Studio. Android Studio gives me an error, it cannot resolve symbol HttpsURLConnection
On Oracle's website and it is said the class is in java.net.URLConnection, when I import it the line is greyed saying it was already imported.
code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
public class cBitTrex {
static int test;
/////////////////////////////////////////////////////////////////////
// Run code to talk to server on a thread
// Every onunce in a while code to tal to server will freex
// WEcall thread methed run and then wait for thread to exit with a time out
public class cThread extends Thread{
String reply=null;
String url;
public void run()
{
String ireply;
error="";
ireply="";
try {
ireply="";
URL myurl = new URL(url);
System.out.println("Open thread connection");
// This is where the error is
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setConnectTimeout(15000);
System.out.println("Get input thread stream");
InputStream ins = con.getInputStream();
System.out.println("Create reader");
InputStreamReader isr = new InputStreamReader(ins);
System.out.println("Creat buffer threadreader");
BufferedReader in = new BufferedReader(isr);
String inputLine;
System.out.println("THREAD Read indata2");
int t;
while ((t= in.read()) != -1)
{
ireply+=(char)t;;
}
System.out.println("finish Read indata");
} catch (Exception e)
{
error=new String(e.getMessage());
System.out.println("Exception in getting data from API server");
reply=null;
}
// Set return valur at end of thread so if thread call tiimout we will not
// get any data
reply=ireply;
}
};
..
...
}
This class you are searching for does not exist, at least in Android. The one that is provided by the Android SDK is java.net.HttpURLConnection. By the way, something you really have to take into account is programming for Android is not just like normal Java, it has some special rules. The correct documentation to search at is the one located in the Android SDK official Page.
Beside that, your error can be that you were importing in Eclipse a Library that you are not using anymore in Android Studio.

read file from assets android

I'm trying to build a card viewer in android for a trading card game. My plan was to use an arraylist to populate the cards into the database. I would read in all values from file and would be displayed via listview. My listview code and arraylist code is fine (after testing without using file input). The problem occurs when I attempt to read in from file. I'm at a loss of what to do. When I run the program like this, it crashes. When I remove the "parseInt" method (because i'm reading in an integer from file), it runs, but none of my data is populated. What is wrong with my io code?
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.io.*;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DeckBuilderActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deck_builder);
//populate database************************************************************************
ArrayList<Card> database = new ArrayList<Card>(); //create new arraylist of datatype card
//value holders
String cardName, expansion, cardNum, unitType, unitClan, unitRace, trigger, unitSkill, cardLore,
imageId;
int unitGrade, unitPower, unitShield;
//exception handling
try{
String myfile = "cardmaindatabase.txt";
InputStream inputReader = getAssets().open(myfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputReader)); //open file
//begin populating with a for loop
int i = 0; //incrementer
while(reader.readLine() != null) //while not end of file
{
//assign values to placeholders
//add new card and take parameters
database.add(new Card());
database.get(i).setCardName(reader.readLine());
database.get(i).setExpansion(reader.readLine());
database.get(i).setCardNum(reader.readLine());
database.get(i).setUnitGrade(Integer.parseInt(reader.readLine()));
}
} catch (IOException e) {
e.printStackTrace();
}
//******************************************************************************************
//populate arraylist
ArrayAdapter<Card> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, database);
ListView lv = (ListView) findViewById(R.id.card_database_listview);
lv.setAdapter(adapter);
}
StringBuffer stringBuffer = new StringBuffer();
try {
InputStream is = mContext.getResources().getAssets().open("your-file-path");
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
//play with each line here
}
}...
Try this code to get data from the assets.
OR if you don't want to clear your code. try modify your code like this. I think the problem is in your loop.
String line = null;
while((line = reader.readLine()) != null) //while not end of file
{
//play with each line here
}
but collecting/storing data like this is unstable and hard to maintain. i'll suggest to use JSON. to store data in asset,so you could be able to collect and store data as fast as possible.

Android saving logs on every run for crash report [duplicate]

This question already has answers here:
How do I obtain crash-data from my Android application?
(30 answers)
Closed 5 months ago.
I'm currently developing an android app. I noticed a very rare error which leeds to a crash of my app. Unfortunately, I had my smartphone never connected to my pc when it occured. So, is there a way to automatically save all logs (and especially the thrown runtimeexceptions) to a file when my app starts, so that I can copy this file to my pc and analyse the error? The file should be overwritten on every start of my app, so that it contains only the logs of the last run... How can I achieve that?
regards
You can find help by following this link Writing crash reports into device sd card
You don't need to add external library.
import com.wordpress.doandroid.Training.R;
import android.app.Activity;
import android.os.Bundle;
public class CaptureExceptionActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sets the default uncaught exception handler. This handler is invoked
// in case any Thread dies due to an unhandled exception.
Thread.setDefaultUncaughtExceptionHandler(new CustomizedExceptionHandler(
"/mnt/sdcard/"));
String nullString = null;
System.out.println(nullString.toString());
setContentView(R.layout.main);
}
}
And the Handler implementation
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Environment;
import android.util.Log;
public class CustomizedExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
private String localPath;
public CustomizedExceptionHandler(String localPath) {
this.localPath = localPath;
//Getting the the default exception handler
//that's executed when uncaught exception terminates a thread
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
public void uncaughtException(Thread t, Throwable e) {
//Write a printable representation of this Throwable
//The StringWriter gives the lock used to synchronize access to this writer.
final Writer stringBuffSync = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringBuffSync);
e.printStackTrace(printWriter);
String stacktrace = stringBuffSync.toString();
printWriter.close();
if (localPath != null) {
writeToFile(stacktrace);
}
//Used only to prevent from any code getting executed.
// Not needed in this example
defaultUEH.uncaughtException(t, e);
}
private void writeToFile(String currentStacktrace) {
try {
//Gets the Android external storage directory & Create new folder Crash_Reports
File dir = new File(Environment.getExternalStorageDirectory(),
"Crash_Reports");
if (!dir.exists()) {
dir.mkdirs();
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
Date date = new Date();
String filename = dateFormat.format(date) + ".STACKTRACE";
// Write the file into the folder
File reportFile = new File(dir, filename);
FileWriter fileWriter = new FileWriter(reportFile);
fileWriter.append(currentStacktrace);
fileWriter.flush();
fileWriter.close();
} catch (Exception e) {
Log.e("ExceptionHandler", e.getMessage());
}
}
}
Don't forget to add this permission in the manifest WRITE_EXTERNAL_STORAGE

Categories

Resources