XML simple parsing - android

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 !!

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.

How to see large debug message

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

How to retrieve data from spreadsheet in android?

I want the data from spreadsheet to my application so that i can use the data in my application. I want the data from the spread sheet having two columns i can use the data from the spread sheet.
Just like you do in java. Use Apache-POI or JExcelApi. JExcelAPI is easier to use, but POI is easier on memory. JExcel holds everything in memory. POI is better maintained.
You can use the code of James Moore: very-simple-google-spreadsheet-code
package com.banshee;
import java.io.IOException;
import java.net.URL;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CustomElementCollection;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.util.ServiceException;
public class SpreadsheetSucker {
public static void main(String[] args) {
SpreadsheetService service = new SpreadsheetService("com.banshee");
try {
// Notice that the url ends
// with default/public/values.
// That wasn't obvious (at least to me)
// from the documentation.
String urlString = "https://spreadsheets.google.com/feeds/list/0AsaDhyyXNaFSdDJ2VUxtVGVWN1Yza1loU1RPVVU3OFE/default/public/values";
// turn the string into a URL
URL url = new URL(urlString);
// You could substitute a cell feed here in place of
// the list feed
ListFeed feed = service.getFeed(url, ListFeed.class);
for (ListEntry entry : feed.getEntries()) {
CustomElementCollection elements = entry.getCustomElements();
String name = elements.getValue("name");
System.out.println(name);
String number = elements.getValue("Number");
System.out.println(number);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
}

AsyncTask to get text file and transfer lines to strings

How would you get a text file off the internet to download and update pre-determined string names so that the files could be used on a TextView and so the application wouldn't have to be updated when information had to be changed. I have already setup a AsyncTask so the file can be downloaded in the background but how would I get the file downloaded, read and then put into strings and then to have a TextView reloaded so the text could be updated. Any help or code on this would be greatly appreciated and I already have the
protected void doInBackground part setup and ready. I have been having trouble with this for some time so any help could be very handy. I have tried using httppost to get the file but I did not understand what I had to change so it worked. Thanks for reading!
The text file in question is http://nowactivity.webs.com/teststring.txt
Here's a more complete answer:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.os.AsyncTask;
import android.util.Log;
...
#Override
protected String doInBackground(String... params) {
// perform Long time consuming operation
Document doc = null;
String returnValue ="";
String baseWebPage = "http://nowactivity.webs.com/teststring.txt";
for(int i = 0; i< params.length; i++){
try {
doc = Jsoup.connect(
baseWebPage)
.get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("DOC", "The line " + doc.toString());
}
return returnValue;
}
I'm sure you can mange the rest of your implementation ;-)
More about jsoup can be found here.
Cheers

Implementation of WebDAV client on android

I am using jakarta/slide project for implementing webDAV client on my android device.
I got the all necessary jar files into external library,
my code:
package com.android.webdav;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.commons.httpclient.HttpException;
import org.apache.util.HttpURL;
import org.apache.webdav.lib.WebdavResource;
import android.app.Activity;
import android.os.Bundle;
public class Webdav extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpURL hrl = new HttpURL("serverUrl");
hrl.setUserInfo("username", "password");
WebdavResource wdr = new WebdavResource(hrl);
File fn = new File("remote-file");
wdr.getMethod(fn);
File LocFile = new File("mnt/sdcard/test/");
wdr.putMethod(LocFile);
wdr.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
but I am getting error,
java.lang.NoClassDefFoundError: org.apache.webdav.lib.WebdavResource
above class already added in jar.
Required help.
Thanks
Sardine + http://code.google.com/p/httpclientandroidlib/ does not work, because httpclientandroidlib has renamed all package names. See android sardine + httpclientandroidlib -> new package names
Sardine + http://code.google.com/p/httpclientandroidlib/
http://sardine.googlecode.com/
You can use https://github.com/yeonsh/Sardine-Android.

Categories

Resources