lang.ClassCastException: java.lang.Integer android xml rpc - java

i'm ahaving an issue while trying to make an xml rpc request. my serive crashes whith the logcat saying lang.ClassCastException: java.lang.Integer at the line 35 of my code which coresponds to the client call * >>> text = (String) client.call<<<<<*.
package tfe.rma.ciss.be;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.util.Enumeration;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.widget.Toast;
public class Addviewer extends Service {
private XMLRPCClient client;
private URI uri;
String text="", IpAdress;
#Override
public void onCreate(){}
public void onStart(Intent intent, int StartId){
uri = URI.create("http://fuseng.elte.rma.ac.be:8080/RPC2");
client = new XMLRPCClient(uri);
getLocalIpAddress();
if (!IpAdress.equals("R.A.S")){
try {
text = (String) client.call("mission.addViewer",IpAdress+ ":" + 8214, "newImage");
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
text= "erro in adding viewer with the exception:" + e + "/n" + "try again later";
}
Toast.makeText(this,"suscribtion to the viewer with the result " + text, Toast.LENGTH_SHORT).show(); }
else {
Toast.makeText(this,"No network avalaible right now" + "/n" + "try again later", Toast.LENGTH_SHORT).show();
}
}
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
IpAdress= inetAddress.getHostAddress().toString();
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
IpAdress="R.A.S";
}
return null;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
so i changed the sparametr newImage by an integer (i.e 214) and then it (the service) works fine except that the server replies me that it is expecting a string at the second parameter (i was already aware of it)... please help

The problem is that client.call(...) is returning an Integer, not a String. For example, it might be returning 20 (or rather, Integer.valueOf(20)), whereas your code expects it to be returning something like "20". If your goal is to convert its return value of 20 to "20" for display purposes, then you should change this:
text = (String) client.call("mission.addViewer",IpAdress+ ":" + 8214, "newImage");
to this:
text = String.valueOf(client.call("mission.addViewer",IpAdress+ ":" + 8214, "newImage"));

Related

How to use Microsoft Translator API in Android

The Microsoft Translator API for android samples has already been deprecated since march 2017 (just this yr). So I'm having a hard time translating text on android. Can anyone help me make this work on android?. It's just that I already have this working in java but I can't make it work on Android. I already tried using asynctask , but to no avail, no translation is being outputed. Or prolly I just did a wrong asyc task?.
The Interface of the application is like this:
It just have a simple textfield with translation that should be outputed on the other textfield. The translation is from Korean to English.
Github Project File is in here
https://github.com/iamjoshuabcxvii/MSTranslateAPIforAndroid
Android code is this.
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import org.apache.commons.io.IOUtils;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
//MS Translator Key is in here
public static String key = "<The MS Assigned Translator Key>";
private TextView txtTranslatedText, txtOriginalText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOriginalText = findViewById(R.id.txtOriginalText);
txtTranslatedText = findViewById(R.id.txtTranslatedText);
}
public void translate(View view) {
// String textOrig = txtOriginalText.getText().toString();
// String textOrig ="안녕하세요 123 -)^ 친구";
String textOrig;
textOrig=txtOriginalText.getText().toString();
String output;
output=getTranslation(textOrig);
txtTranslatedText.setText(output);
}
public static String getTranslation(String translatedTextStr) {
try {
// Get the access token
// The key got from Azure portal, please see https://learn.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
// System.out.println(token); //Code to Display Token
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
String text = URLEncoder.encode(translatedTextStr, "UTF-8");
String from = "ko";
String to = "en";
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid=%s&text=%s&from=%s&to=%s&maxTranslations=5", appId, text, from, to);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("POST");
translateConn.setRequestProperty("Accept", "application/xml");
translateConn.setRequestProperty("Content-Type", "text/xml");
translateConn.setDoOutput(true);
String TranslationOptions = "<TranslateOptions xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">" +
"<Category>general</Category>" +
"<ContentType>text/plain</ContentType>" +
"<IncludeMultipleMTAlternatives>True</IncludeMultipleMTAlternatives>" +
"<ReservedFlags></ReservedFlags>" +
"<State>contact with each other</State>" +
"</TranslateOptions>";
translateConn.setRequestProperty("TranslationOptions", TranslationOptions);
IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
// System.out.println(resp+"\n\n");
String s=resp;
Pattern assign_op=Pattern.compile("(<TranslatedText>)"
+ "|(<\\/TranslatedText>)"
+ "|[()\\\\[\\\\]{};=#.,'\\\\^:#!$%&_`*-<>]"
+ "|[a-zA-Z0-9\\s]*"
+ "");
Matcher m = assign_op.matcher(s) ;
String actualTranslation="";
Boolean endOfTransTxt=false,startOfTransTxt=false,concat=false;
String foundRegexStr="",tempStr="";
while (m.find()) {
foundRegexStr=m.group();
if(m.group().matches("(<TranslatedText>)")) {
startOfTransTxt=true;
}
else if(m.group().matches("(<\\/TranslatedText>)")) {
endOfTransTxt=true;
concat=false;
}
else{
startOfTransTxt=false;
endOfTransTxt=false;
}
if(startOfTransTxt==true) {
concat=true;
}
else if(concat==true) {
tempStr=tempStr+""+m.group();
}
else {
}
}
// System.out.println("\nTranslated Text: "+tempStr);
translatedTextStr=tempStr;
} catch (Exception e) {
e.printStackTrace();
}
return translatedTextStr;
}
}
I think you did a wrong AsyncTask.
You can do it like this:
private class TransAsynTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... strings) {
String output = getTranslation(strings[0]);
return output;
}
#Override
protected void onPostExecute(String s) {
txtTranslatedText.setText("Output: " + s);
super.onPostExecute(s);
}
}
And in the onCreate you call:
String textOrig;
textOrig = txtOriginalText.getText().toString();
new TransAsynTask().execute(textOrig);
/*String output;
output = getTranslation(textOrig);
txtTranslatedText.setText("Translated Text: " + output);*/

Android - Printing receipt to Bluetooth Printer

Most of the related answers and google contain pretty old contributions referring to this topic. So Im looking for a way to make my Android-Application print receipts (58 mm in width) via a bluetooth thermal receipt printer. Is it necessary to use a printer with a 3rd party API? I thought about to buy a regular bluetooth printer, that can be connected to my device and use the default Android print manager to make a layout for the receipt. Is that possible? Are there any samples, docs or tutorials? Would appreciate it. Thanks in advance
Yes, it's necesary to use a 3rd party SDK. I recommend you Zebra Printers, the have good documentation and code samples, that makes it easy compared to other brands. Download the SDK from here
To make your labels you can use ZebraDesigner that let you visualy create the layout and gives you as output ZPL code that you can send from your app to the Bluetooth printer. Click here to see it.
Hi here is an example of how to print using zebra from a cordova application
package com.custom.plugin;
import android.os.Build;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.Context;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import java.util.Set;
import com.zebra.android.discovery.*;
import com.zebra.sdk.comm.*;
import com.zebra.sdk.printer.*;
import com.zebra.sdk.printer.SGD;
/**
* This class echoes a string called from JavaScript.
*/
public class PrinterDanBreakingNews extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("getListPairedDevices")) {
this.getListPairedDevices(callbackContext);
return true;
}else if(action.equals("print"))
{
this.print(callbackContext,args);
return true;
}
return false;
}
private void getListPairedDevices(CallbackContext callbackContext)
{
try
{
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if( !bluetoothAdapter.isEnabled() )
{
callbackContext.error("Favor encienda el bluetooth");
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
JSONArray lista = new JSONArray();
for (BluetoothDevice device : pairedDevices) {
String bname = device.getName();
String bmac = device.getAddress();
String btype
= getBTMajorDeviceClass(
device.getBluetoothClass().getMajorDeviceClass()
);
JSONObject item = new JSONObject();
item.put("name", bname);
item.put("type", btype);
item.put("mac", bmac);
lista.put(item);
}
callbackContext.success(lista.toString());
}
callbackContext.error("Error. no hay dispositivos registrados");
}
catch( Exception ex )
{
callbackContext.error("Error. " + ex.toString());
}
}
private String getBTMajorDeviceClass(int major){
switch(major){
case BluetoothClass.Device.Major.AUDIO_VIDEO:
return "AUDIO_VIDEO";
case BluetoothClass.Device.Major.COMPUTER:
return "COMPUTER";
case BluetoothClass.Device.Major.HEALTH:
return "HEALTH";
case BluetoothClass.Device.Major.IMAGING:
return "IMAGING";
case BluetoothClass.Device.Major.MISC:
return "MISC";
case BluetoothClass.Device.Major.NETWORKING:
return "NETWORKING";
case BluetoothClass.Device.Major.PERIPHERAL:
return "PERIPHERAL";
case BluetoothClass.Device.Major.PHONE:
return "PHONE";
case BluetoothClass.Device.Major.TOY:
return "TOY";
case BluetoothClass.Device.Major.UNCATEGORIZED:
return "UNCATEGORIZED";
case BluetoothClass.Device.Major.WEARABLE:
return "WEARABLE";
default: return "unknown!";
}
}
public void print(final CallbackContext callbackContext, final JSONArray args){
try
{
new Thread(new Runnable() {
#Override
public void run() {
try {
String mac = "";
String template = "";
String length = "";
if( args.length() > 0 ) {
JSONArray row = args.getJSONArray(0);
JSONObject item = row.getJSONObject(0);
mac = item.getString("mac");
template = item.getString("template");
length = item.getString("length");
}
Connection thePrinterConn = new BluetoothConnectionInsecure(mac);
if (isPrinterReady(thePrinterConn)) {
thePrinterConn.open();
SGD.SET("device.languages", "zpl", thePrinterConn);
SGD.SET("ezpl.media_type", "continuous", thePrinterConn);
SGD.SET("zpl.label_length", length, thePrinterConn);
thePrinterConn.write(template.getBytes());
Thread.sleep(500);
thePrinterConn.close();
callbackContext.success("listo");
} else {
callbackContext.error("Error3, la impresora no esta lista");
}
} catch (Exception ex) {
callbackContext.error("Error2. " + ex.toString());
}
}
}).start();
}
catch(Exception ex)
{
callbackContext.error("Error1. " + ex.toString());
}
}
private Boolean isPrinterReady(Connection connection)
throws Exception {
Boolean isOK = false;
connection.open();
ZebraPrinter printer = ZebraPrinterFactory.getInstance(connection);
PrinterStatus printerStatus = printer.getCurrentStatus();
if (printerStatus.isReadyToPrint) {
isOK = true;
} else if (printerStatus.isPaused) {
//throw new ConnectionException("Cannot print because the printer is paused");
} else if (printerStatus.isHeadOpen) {
//throw new ConnectionException("Cannot print because the printer media door is open");
} else if (printerStatus.isPaperOut) {
//throw new ConnectionException("Cannot print because the paper is out");
} else {
//throw new ConnectionException("Cannot print");
}
//connection.open();
return isOK;
}
}
In the function getListPairedDevices you can get a list of mac addresses to use and then use function print to send your ZLP code.
Here is some ZPL test.
CT~~CD,~CC^~CT~
^XA~TA000~JSN^LT0^MNW^MTD^PON^PMN^LH0,0^JMA^PR4,4~SD0^JUS^LRN^CI0^XZ
^XA
^MMT
^PW575
^LL0799
^LS0
^FT35,720^A0N,20,19^FH\^FDHORA^FS
^FT35,680^A0N,20,19^FH\^FDFECHA^FS
^FT34,644^A0N,20,19^FH\^FDCOURRIER^FS
^FT34,609^A0N,20,19^FH\^FDADR2^FS
^FT34,572^A0N,20,19^FH\^FDADR1^FS
^FT34,533^A0N,20,19^FH\^FDSUCURSAL^FS
^FT34,498^A0N,20,19^FH\^FDDESTINATARIO^FS
^FT34,461^A0N,20,19^FH\^FDREMITENTE^FS
^FT165,720^A0N,20,19^FH\^FD: VHORA^FS
^FT165,680^A0N,20,19^FH\^FD: VFECHA^FS
^FT165,644^A0N,20,19^FH\^FD: VCOURRIER^FS
^FT166,534^A0N,20,19^FH\^FD: VSUCURSAL^FS
^FT166,426^A0N,20,19^FH\^FD: VEMPAQUE^FS
^FT166,461^A0N,20,19^FH\^FD: VREMITENTE^FS
^FT166,497^A0N,20,19^FH\^FD: VDESTINATARIO^FS
^FT34,425^A0N,20,19^FH\^FDEMPAQUE^FS
^FT136,365^A0N,23,24^FH\^FD1138 CHO-CHO-1-1-1-1^FS
^FT185,325^A0N,23,24^FH\^FDGUIA: 11389942705^FS
^FT165,46^A0N,28,28^FH\^FDDIRECTO LOGISTICS^FS
^FT25,214^A0N,138,139^FH\^FD1/2^FS
^FT380,265^BQN,2,8
^FH\^FDLA,101010^FS
^FO20,281^GB536,0,3^FS
^PQ1,0,1,Y^XZ

InetAddress.getLocalHost() returns null in browser

I wrote an applet which takes the MAC address from the local computer.
It works fine on eclipse but at the moment I try to run it via the browser it does not.
after some debugging i've come to realize that this part returns null on browser
InetAddress.getLocalHost();
Can anyone tell me why?
EDIT:
This is code I found somewhere on the web:
import java.applet.Applet;
import java.awt.Graphics;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class LoginApplet extends Applet {
private static final long serialVersionUID = 1L;
private String macAddress;
public void init() {
setMacAddress(getMacAddressFromClient());
}
public void paint(Graphics g)
{
String mac = getMacAddress();
if(mac.isEmpty())
{
mac = "Empty";
}
g.drawString(mac,15,15);
}
public String getMacAddressFromClient() {
String macAddr= "";
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
macAddress += addr.getHostAddress();
NetworkInterface dir = NetworkInterface.getByInetAddress(addr);
byte[] dirMac = dir.getHardwareAddress();
int count=0;
for (int b:dirMac){
if (b<0) b=256+b;
if (b==0) {
macAddr=macAddr.concat("00");
}
if (b>0){
int a=b/16;
if (a==10) macAddr=macAddr.concat("A");
else if (a==11) macAddr=macAddr.concat("B");
else if (a==12) macAddr=macAddr.concat("C");
else if (a==13) macAddr=macAddr.concat("D");
else if (a==14) macAddr=macAddr.concat("E");
else if (a==15) macAddr=macAddr.concat("F");
else macAddr=macAddr.concat(String.valueOf(a));
a = (b%16);
if (a==10) macAddr=macAddr.concat("A");
else if (a==11) macAddr=macAddr.concat("B");
else if (a==12) macAddr=macAddr.concat("C");
else if (a==13) macAddr=macAddr.concat("D");
else if (a==14) macAddr=macAddr.concat("E");
else if (a==15) macAddr=macAddr.concat("F");
else macAddr=macAddr.concat(String.valueOf(a));
}
if (count<dirMac.length-1)macAddr=macAddr.concat("-");
count++;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
macAddr=e.getMessage();
} catch (SocketException e) {
// TODO Auto-generated catch block
macAddr = e.getMessage();
}
return macAddr;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress += macAddress;
}
}
In eclipse: addr has the localhost address
In the browser (IE and chrome) addr is null.

how to get a list of values?

Below is the code which i want to get the output of the names of the particular administrator number , administrator Emailid , but insted of that i am getting the output as : List of ---> com.demo.model.Administrator#91e143 with different numbers , basically i am new to java .Would you please help me in the Loop Iteration .
package com.demo.action;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.demo.model.Administrator;
import com.demo.model.AdministratorDAO;
import com.demo.model.AdministratorDemo;
import com.demo.model.JQueryDataTableParam;
import com.demo.model.JqueryDatatablesParamUtil;
public class AdministratorAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in execute..");
JQueryDataTableParam param = JqueryDatatablesParamUtil
.getParam(request);
String txt2=request.getParameter("txt1");
//String select2=request.getParameter("select1");
//request.setAttribute("e", "select2");
//String select3=request.getParameter("select2");
//System.out.println("txtValue->"+e);
//System.out.println("txtValue->"+select2);
System.out.println("txtValue->"+txt2);
//String var = Administrator.isValidname(sData);
String sEcho = param.sEcho;
int iTotalRecords;
int iTotalDisplayRecords;
int start = param.iDisplayStart;
System.out.println("start" + start);
int last = param.iDisplayLength +param.iDisplayStart;
System.out.println("last" + last);
int sortColumnIndex = param.iSortColumnIndex;
System.out.println("sortColumnIndex" + sortColumnIndex);
String sortDirection = param.sSortDirection;
System.out.println("sortDirection" + sortDirection);
JSONArray data = new JSONArray();
iTotalRecords = AdministratorDemo.getAdminCount();
List<Administrator> Administrators = new LinkedList<Administrator>();
for (Administrator a : AdministratorDemo.getAdimistrators()) {
if (a.getAdministrator_nm() != null
&& a.getAdministrator_nm().toLowerCase()
.contains(param.sSearch.toLowerCase())
|| a.getAdmin_Email_ID() != null
&& a.getAdmin_Email_ID().toLowerCase()
.contains(param.sSearch.toLowerCase())
|| a.getAdmin_Fax_Phone_Num_Tx() != null
&& a.getAdmin_Fax_Phone_Num_Tx().toLowerCase()
.contains(param.sSearch.toLowerCase())) {
Administrators.add(a);
}
}
iTotalDisplayRecords = iTotalRecords;
if (Administrators.size() < param.iDisplayStart + param.iDisplayLength)
Administrators = Administrators.subList(param.iDisplayLength,
Administrators.size());
else
Administrators = Administrators.subList(param.iDisplayStart,
param.iDisplayStart + param.iDisplayLength);
System.out.println("End of the operations");
try {
JSONObject jsonresponse = new JSONObject();
jsonresponse.put("sEcho", sEcho);
jsonresponse.put("iTotalRecords", iTotalRecords);
jsonresponse.put("iTotalDisplayRecords", iTotalDisplayRecords);
JSONArray row = new JSONArray();
for(Iterator<Administrator> i = AdministratorDemo.getAdimistrators().iterator();i.hasNext();)
{
System.out.println(i.next());
}
jsonresponse.put("aaData", data);
response.setContentType("application/json");
response.getWriter().print(jsonresponse.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
response.setContentType("text/html");
response.getWriter().print(e1.getMessage());
}
System.out.println("In execute method.");
return null;
}
public String getXMLObject(HttpServletRequest request) {
return new java.util.Date().toString()
+ " sent by vasu from Date Action";
}
}
The result that you are seeing (com.demo.model.Administrator#91e143) is the default string representation of the Administrator object, more specifically, it's what is returned by the default toString() method inherited from Object
To print useful information, override public String toString() of Administrator
You need to override Object#toString() in your Administrator class.
This method can return any meaningful representation of the object you want, e.g:
#Override
public String toString() {
return "id = " + id + "email = " + email;
}
You're making a list of Administrators, where you want to make a list of Strings.
Alternatively (and probably better), if you can change the Administrator class, just implement the toString method in it, that will return the string you want to see on the screen.

On Android simple-xml serial.read() throws StackOverflowError

I'm trying to learn to use xml in Java (Android platform, using Eclipse and simple-xml-2.5.2).
I keep getting a weird java.lang.StackOverflowError in the "serial.read" line in "Training.java".
Can you help fixing the problem? Is it an xml definition error?
I include the source below:
File beacons.java:
package com.marcos.training;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
#Element
public class Beacons {
#ElementList(inline=true)
private List<Beacon> list;
#Element
private String id;
public String getId() {
return id;
}
public Integer getSize() {
return list.size();
}
public List<Beacon> getList() {
return list;
}
}
File Beacon.java:
package com.marcos.training;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
#Root
public class Beacon {
#Attribute
protected String ssid;
#Element
protected String bssid;
public String getSsid() {
return ssid;
}
public String getBssid() {
return bssid;
}
}
File Training.java:
package com.marcos.training;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.content.res.Resources.NotFoundException;
public class Training extends Activity {
private final static String TAG = Training.class.getCanonicalName();
TextView textStatus;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textStatus = (TextView) findViewById(R.id.textStatus);
Serializer serial = new Persister();
try {
Beacons myBeacons;
try {
myBeacons = serial.read(Beacons.class, getResources().openRawResource(R.xml.beacons));
Log.i(TAG, "Number of Beacons: " + myBeacons.getSize());
} catch (NotFoundException e) {
Log.d(TAG, "Uncaught exception", e);
return;
} catch (Exception e) {
Log.d(TAG, "Uncaught exception", e);
return;
}
int len = myBeacons.getSize();
for (int i = 0; i < len; i++) {
Beacon b = myBeacons.getList().get(i);
textStatus.append("Beacon " + (i+1) + "\n");
textStatus.append(" SSID : " + b.getSsid() + "\n");
textStatus.append(" BSSID : " + b.getBssid() + "\n");
textStatus.append("\n");;
}
} catch (Exception e) {
Log.d(TAG, "Uncaught exception", e);
}
}
}
File beacons.xml:
<?xml version="1.0" encoding="utf-8"?>
<beacons id="1">
<beacon ssid="north">
<bssid>01:02:03:04:05:06</bssid>
</beacon>
<beacon ssid="east">
<bssid>02:03:04:05:06:07</bssid>
</beacon>
<beacon ssid="south">
<bssid>03:04:05:06:07:08</bssid>
</beacon>
<beacon ssid="west">
<bssid>04:05:06:07:08:09</bssid>
</beacon>
</beacons>
By putting your XML file into the XML directory of the resources, the Android build system is assuming you want that compiled down into a binary format and it obliges you. Therefore, when you access that input stream and then try to treat it as a textual XML representation it just doesn't work. You have 2 choices.
Move your XML file into the res\raw directory.
Leave it where it is and use the getResources().getXml(R.xml.beacons) API and create a pull parser for your particular XML.
See this link for more details.

Categories