Android - Printing receipt to Bluetooth Printer - java

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

Related

Youtube live stream to specific Channel

I am using the below code to create event in Youtube for Live Streaming. Everything works fine, my problem, I want users to live stream to our company's Channel.
At present events are getting created in users channel, this is wrong, we want to create the event in our channel and live stream should come to our company's channel. I would like to know how we should specify our company's channel to create the events.
I tried to specify
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
liveBroadcastInsert.onBehalfOfContentOwner("user#company.com");
liveBroadcastInsert.onBehalfOfContentOwnerChannel("ChannelID");
Both did not work. It gave error
"errors": [
{
"domain": "youtube.common",
"message": "The authenticated user cannot act on behalf of the specified Google account.",
"reason": "accountDelegationForbidden"
}
//// Code ///
import com.google.android.gms.common.Scopes;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.util.DateTime;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTube.LiveBroadcasts.Transition;
import com.google.api.services.youtube.YouTubeScopes;
import com.google.api.services.youtube.model.CdnSettings;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.IngestionInfo;
import com.google.api.services.youtube.model.LiveBroadcast;
import com.google.api.services.youtube.model.LiveBroadcastContentDetails;
import com.google.api.services.youtube.model.LiveBroadcastListResponse;
import com.google.api.services.youtube.model.LiveBroadcastSnippet;
import com.google.api.services.youtube.model.LiveBroadcastStatus;
import com.google.api.services.youtube.model.LiveStream;
import com.google.api.services.youtube.model.LiveStreamListResponse;
import com.google.api.services.youtube.model.LiveStreamSnippet;
import com.google.api.services.youtube.model.MonitorStreamInfo;
import com.test.tv.usb.MainActivity;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class YouTubeApi {
public static final String RTMP_URL_KEY = "rtmpUrl";
public static final String BROADCAST_ID_KEY = "broadcastId";
private static final int FUTURE_DATE_OFFSET_MILLIS = 5 * 1000;
public static void createLiveEvent(YouTube youtube, String description,
String name) {
// We need a date that's in the proper ISO format and is in the future,
// since the API won't
// create events that start in the past.
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
long futureDateMillis = System.currentTimeMillis()
+ FUTURE_DATE_OFFSET_MILLIS;
Date futureDate = new Date();
futureDate.setTime(futureDateMillis);
String date = dateFormat.format(futureDate);
Log.i(MainActivity.APP_NAME, String.format(
"Creating event: name='%s', description='%s', date='%s'.",
name, description, date));
try {
LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
broadcastSnippet.setTitle(name);
broadcastSnippet.setScheduledStartTime(new DateTime(futureDate));
LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
MonitorStreamInfo monitorStream = new MonitorStreamInfo();
monitorStream.setEnableMonitorStream(false);
contentDetails.setMonitorStream(monitorStream);
// Create LiveBroadcastStatus with privacy status.
LiveBroadcastStatus status = new LiveBroadcastStatus();
status.setPrivacyStatus("public");
LiveBroadcast broadcast = new LiveBroadcast();
broadcast.setKind("youtube#liveBroadcast");
broadcast.setSnippet(broadcastSnippet);
broadcast.setStatus(status);
broadcast.setContentDetails(contentDetails);
// Create the insert request
String[] lbInsert = {"snippet", "status","contentDetails"};
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
// Request is executed and inserted broadcast is returned
LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();
// Create a snippet with title.
LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
streamSnippet.setTitle(name);
// Create content distribution network with format and ingestion
// type.
CdnSettings cdn = new CdnSettings();
cdn.setIngestionType("rtmp");
cdn.setResolution("1080p");
cdn.setFrameRate("30fps");
LiveStream stream = new LiveStream();
stream.setKind("youtube#liveStream");
stream.setSnippet(streamSnippet);
stream.setCdn(cdn);
// Create the insert request
String[] lsInsert = {"snippet", "cdn"};
YouTube.LiveStreams.Insert liveStreamInsert = youtube.liveStreams()
.insert(Arrays.asList(lsInsert), stream);
// Request is executed and inserted stream is returned
LiveStream returnedStream = liveStreamInsert.execute();
// Create the bind request
String[] lbBind = {"id", "contentDetails"};
YouTube.LiveBroadcasts.Bind liveBroadcastBind = youtube
.liveBroadcasts().bind(returnedBroadcast.getId(),
Arrays.asList(lbBind));
// Set stream id to bind
liveBroadcastBind.setStreamId(returnedStream.getId());
// Request is executed and bound broadcast is returned
liveBroadcastBind.execute();
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: "
+ e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getStackTrace());
t.printStackTrace();
}
}
// TODO: Catch those exceptions and handle them here.
public static List<EventData> getLiveEvents(
YouTube youtube) throws IOException {
Log.i(MainActivity.APP_NAME, "Requesting live events.");
String[] yReq = {"id", "snippet", "contentDetails"};
YouTube.LiveBroadcasts.List liveBroadcastRequest = youtube
.liveBroadcasts().list(Arrays.asList(yReq));
// liveBroadcastRequest.setMine(true);
liveBroadcastRequest.setBroadcastStatus("upcoming");
// List request is executed and list of broadcasts are returned
LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
// Get the list of broadcasts associated with the user.
List<LiveBroadcast> returnedList = returnedListResponse.getItems();
List<EventData> resultList = new ArrayList<EventData>(returnedList.size());
EventData event;
for (LiveBroadcast broadcast : returnedList) {
event = new EventData();
event.setEvent(broadcast);
String streamId = broadcast.getContentDetails().getBoundStreamId();
if (streamId != null) {
String[] strID = {streamId};
String ingestionAddress = getIngestionAddress(youtube, strID);
event.setIngestionAddress(ingestionAddress);
}
resultList.add(event);
}
return resultList;
}
public static void startEvent(YouTube youtube, String broadcastId)
throws IOException {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e(MainActivity.APP_NAME, "", e);
}
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"live", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static void endEvent(YouTube youtube, String broadcastId)
throws IOException {
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"complete", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static String getIngestionAddress(YouTube youtube, String[] streamId)
throws IOException {
String[] tReq = {"cdn"};
YouTube.LiveStreams.List liveStreamRequest = youtube.liveStreams()
.list(Arrays.asList(tReq));
liveStreamRequest.setId(Arrays.asList(streamId));
LiveStreamListResponse returnedStream = liveStreamRequest.execute();
List<LiveStream> streamList = returnedStream.getItems();
if (streamList.isEmpty()) {
return "";
}
IngestionInfo ingestionInfo = streamList.get(0).getCdn().getIngestionInfo();
return ingestionInfo.getIngestionAddress() + "/"
+ ingestionInfo.getStreamName();
}
}

libusb cannot deinitialize context

I need some help with a IllegalStateException in Java.
I got a sourcecode that should read out Data from a USB Device.
That code is not finished yet, but I already got the following error report
Exception in thread "main" java.lang.IllegalStateException: default context is not initialized at org.usb4java.Libusb.exit(Native Method) at testnew.main(testnew.java:122)
Line 122 is LibUsb.exit(null)
Code is below
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbInterface;
import javax.usb.UsbInterfacePolicy;
import javax.usb.UsbNotActiveException;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.usb4java.BufferUtils;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
public class testnew {
private final static short VENDOR_ID = 0x0403;
private final static short PRODUCT_ID = 0x6001;
private static byte IN_ENDPOINT = (byte) 0x81;
private static long TIMEOUT = 5000;
private final static int INTERFACE = 0;
private final static Object CONNECT_HEADER = 000;
private final static Object CONNECT_BODY = 000;
public static UsbDevice getHygrometerDevice(UsbHub hub) {
UsbDevice launcher = null;
for (Object object : hub.getAttachedUsbDevices()) {
UsbDevice device = (UsbDevice) object;
if (device.isUsbHub()) {
launcher = getHygrometerDevice((UsbHub) device);
if (launcher != null)
return launcher;
} else {
UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
if (desc.idVendor() == VENDOR_ID && desc.idProduct() == PRODUCT_ID)
return device;
}
}
return null;
}
public static char readKey() {
try {
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
if (line.length() > 0)
return line.charAt(0);
return 0;
} catch (IOException e) {
throw new RuntimeException("Unable to read key", e);
}
}
public static ByteBuffer read(DeviceHandle handle, int size) {
ByteBuffer buffer = BufferUtils.allocateByteBuffer(size).order(ByteOrder.LITTLE_ENDIAN);
IntBuffer transferred = BufferUtils.allocateIntBuffer();
int result = LibUsb.bulkTransfer(handle, IN_ENDPOINT, buffer, transferred, TIMEOUT);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to read data", result);
}
System.out.println(transferred.get() + " bytes read from device");
return buffer;
}
public static void main(String[] args) {
// Search for the missile launcher USB device and stop when not found
UsbDevice device;
try {
device = getHygrometerDevice(UsbHostManager.getUsbServices().getRootUsbHub());
if (device == null) {
System.err.println("Missile launcher not found.");
System.exit(1);
return;
}
// Claim the interface
UsbConfiguration configuration = device.getUsbConfiguration((byte) 1);
UsbInterface iface = configuration.getUsbInterface((byte) INTERFACE);
iface.claim(new UsbInterfacePolicy() {
#Override
public boolean forceClaim(UsbInterface usbInterface) {
return true;
}
});
iface.getUsbEndpoint(IN_ENDPOINT).getUsbPipe().addUsbPipeListener(new UsbPipeListener() {
#Override
public void errorEventOccurred(UsbPipeErrorEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void dataEventOccurred(UsbPipeDataEvent arg0) {
for (byte b : arg0.getData())
System.out.print(b);
System.out.print("\n");
}
});
;
} catch (UsbNotActiveException | UsbDisconnectedException | UsbException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Deinitialize the libusb context
LibUsb.exit(null);
}
}
Any suggestions?
you did not initialize the context this is why you get the error when you try to deinitialize it, see http://www.programcreek.com/java-api-examples/index.php?api=org.usb4javaLibUsb example 17
public static void main(String[] args)
{
//Initialize the libusb context
int result = LibUsb.Init(null);
if (result != LibUsb.SUCCESS){
throw new LibUsbException("Unable to initialze libusb",result);
}
[...]
how to open the pipe depends on what transfer type you want to choose (bulk transfer, sychronous transfer, asynchronous transfer), see http://usb4java.org/quickstart/javax-usb.html
for synchronous transfer you can use (copied from http://usb4java.org/quickstart/javax-usb.html)
UsbEndpoint endpoint = iface.getUsbEndpoint((byte) 0x83);
UsbPipe pipe = endpoint.getUsbPipe();
pipe.open();
try
{
byte[] data = new byte[8];
int received = pipe.syncSubmit(data);
System.out.println(received + " bytes received");
}
finally
{
pipe.close();
}
There are IN endpoints and OUT endpoints, you write to OUT and read from IN. Control transfers go to EP0. All USB communication is initiated by the host device, meaning the USB device can not even initiate a communication.
for deeper information on USB protocol see http://www.beyondlogic.org/usbnutshell/usb1.shtml

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.

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

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"));

How to read MP3 file tags

I want to have a program that reads metadata from an MP3 file. My program should also able to edit these metadata. What can I do?
I got to search out for some open source code. But they have code; but not simplified idea for my job they are going to do.
When I read further I found the metadata is stored in the MP3 file itself. But I am yet not able to make a full idea of my baby program.
Any help will be appreciated; with a program or very idea (like an algorithm). :)
The last 128 bytes of a mp3 file contains meta data about the mp3 file., You can write a program to read the last 128 bytes...
UPDATE:
ID3v1 Implementation
The Information is stored in the last 128 bytes of an MP3. The Tag
has got the following fields, and the offsets given here, are from
0-127.
Field Length Offsets
Tag 3 0-2
Songname 30 3-32
Artist 30 33-62
Album 30 63-92
Year 4 93-96
Comment 30 97-126
Genre 1 127
WARINING- This is just an ugly way of getting metadata and it might not actually be there because the world has moved to id3v2. id3v1 is actually obsolete. Id3v2 is more complex than this, so ideally you should use existing libraries to read id3v2 data from mp3s . Just putting this out there.
You can use apache tika Java API for meta-data parsing from MP3 such as title, album, genre, duraion, composer, artist and etc.. required jars are tika-parsers-1.4, tika-core-1.4.
Sample Program:
package com.parse.mp3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AudioParser {
/**
* #param args
*/
public static void main(String[] args) {
String fileLocation = "G:/asas/album/song.mp3";
try {
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("----------------------------------------------");
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : "+metadata.get("xmpDM:composer"));
System.out.println("Genre : "+metadata.get("xmpDM:genre"));
System.out.println("Album : "+metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
For J2ME(which is what I was struggling with), here's the code that worked for me..
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MetaDataControl;
import javax.microedition.midlet.MIDlet;
public class MetaDataControlMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private List list = new List("Message", List.IMPLICIT);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Alert alert = new Alert("Message");
private Player player = null;
public MetaDataControlMIDlet() {
display = Display.getDisplay(this);
alert.addCommand(exitCommand);
alert.setCommandListener(this);
list.addCommand(exitCommand);
list.setCommandListener(this);
//display.setCurrent(list);
}
public void startApp() {
try {
FileConnection connection = (FileConnection) Connector.open("file:///e:/breathe.mp3");
InputStream is = null;
is = connection.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.prefetch();
player.realize();
} catch (Exception e) {
alert.setString(e.getMessage());
display.setCurrent(alert);
e.printStackTrace();
}
if (player != null) {
MetaDataControl mControl = (MetaDataControl) player.getControl("javax.microedition.media.control.MetaDataControl");
if (mControl == null) {
alert.setString("No Meta Information");
display.setCurrent(alert);
} else {
String[] keys = mControl.getKeys();
for (int i = 0; i < keys.length; i++) {
list.append(keys[i] + " -- " + mControl.getKeyValue(keys[i]), null);
}
display.setCurrent(list);
}
}
}
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
notifyDestroyed();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Categories