Checking a wallet's balance (bitcoinj) - java

I am trying to create a p2p android wallet for bitcoin using bitcoinj.
I created an address and added it as a wachedAddress in the wallet.
When I add some coins from http://tpfaucet.appspot.com/ my listener shows me that 0.02 coins have been added to my address but when I try to see the balance in my app is shows me 0 BTC. What am I missing?
Here is the code of my listener:
public class WalletListener extends AbstractWalletEventListener {
public static final String TAG = "WalletListener";
private WalletState walletState;
private Wallet wallet;
#Override
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
Log.d(TAG, "-----> coins resceived: " + tx.getHashAsString());
Log.d(TAG, "received: " + tx.getValue(wallet));
walletState = WalletState.getInstantce();
wallet = walletState.getReadyWallet();
Log.d(TAG, "The balance is: " + wallet.getBalance().toFriendlyString());
}
}
and here is the code for my WalletState class
package com.tools;
import android.os.AsyncTask;
import android.util.Log;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.mybitcoinwallet.WalletActivity;
import com.mybitcoinwallet.adapter.MyPagerAdapter;
import com.mybitcoinwallet.fragment.WalletFragment;
import com.mybitcoinwallet.listeners.WalletListener;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.CheckpointManager;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.InsufficientMoneyException;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerGroup;
import org.bitcoinj.core.ScriptException;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.Wallet;
import org.bitcoinj.crypto.KeyCrypterException;
import org.bitcoinj.net.discovery.DnsDiscovery;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.SPVBlockStore;
import org.bitcoinj.store.UnreadableWalletException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Created by Mihail on 5/23/15.
*/
public class WalletState {
public static final String TAG = "WalletState";
private NetworkParameters network = TestNet3Params.get();
private Wallet wallet;
private Address address;
private MyPagerAdapter pagerAdapter;
private static WalletState walletState;
private PeerGroup peerGroup;
private BlockStore blockStore;
private File walletFile;
private WalletState() {
}
public void initiate() {
new BackgroundTask().execute();
}
public static WalletState getInstantce() {
if (walletState == null) {
walletState = new WalletState();
}
return walletState;
}
public static Wallet getWallet(NetworkParameters netParams) {
File walletFile = new File(WalletActivity.getMainActivity().getFilesDir().getPath().toString()
+ "my_wallet_file");
Log.i(TAG, WalletActivity.getMainActivity().getFilesDir().getPath().toString()
+ "my_wallet_file");
Wallet wallet;
try {
wallet = Wallet.loadFromFile(walletFile);
} catch (UnreadableWalletException e) {
wallet = new Wallet(netParams);
ECKey key = new ECKey();
wallet.addKey(key);
try {
wallet.saveToFile(walletFile);
} catch (IOException a) {
Log.e(TAG, "Caught IOException: ", a);
}
}
return wallet;
}
public class BackgroundTask extends AsyncTask {
public static final String TAG = "BackgroundTask";
#Override
protected Object doInBackground(Object[] params) {
try {
Log.d(TAG, "Started");
wallet = getWallet(network);
wallet.addEventListener(new WalletListener());
ECKey key = wallet.getImportedKeys().iterator().next();
File file = new File(WalletActivity.getMainActivity().getFilesDir().getPath()
+ "my_wallet_file" + ".spvchain");
boolean chainExistedAlready = file.exists();
blockStore = new SPVBlockStore(network, file);
if (!chainExistedAlready) {
File checkpointsFile = new File("checkpoints");
if (checkpointsFile.exists()) {
FileInputStream stream = new FileInputStream(checkpointsFile);
CheckpointManager.checkpoint(network, stream, blockStore, key.getCreationTimeSeconds());
}
}
BlockChain chain = new BlockChain(network, wallet, blockStore);
// Connect to the localhost node. One minute timeout since we won't try any other peers
Log.i(TAG, "Connecting ...");
peerGroup = new PeerGroup(network, chain);
peerGroup.setUserAgent("PingService", "1.0");
peerGroup.addPeerDiscovery(new DnsDiscovery(network));
peerGroup.addWallet(wallet);
peerGroup.startAsync();
peerGroup.awaitRunning();
Log.i(TAG, "Peers are fully synchronized! ");
address = wallet.currentReceiveAddress();
Log.i(TAG, "currentReceiveAddress: " + address);
wallet.addWatchedAddress(address);
ECKey ecKey = wallet.currentReceiveKey();
// Making sure that everything is shut down cleanly!
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
System.out.print("Shutting down ... ");
peerGroup.stopAsync();
peerGroup.awaitTerminated();
wallet.saveToFile(walletFile);
blockStore.close();
System.out.print("done ");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
} catch (Exception e) {
Log.e(TAG, "AAAAAA Exception!!!!!!", e);
}
return null;
}
#Override
protected void onPostExecute(Object o) {
Log.i(TAG, "onPostExecute! finally and the Key is: " + address.toString());
pagerAdapter = WalletActivity.getMainActivity().getPagerAdapter();
WalletFragment fragment = pagerAdapter.getFragment();
fragment.setmTextView(address.toString());
Coin balance = wallet.getBalance();
fragment.setBalanceText(balance.toFriendlyString());
Log.i(TAG, "The balance is " + balance.toFriendlyString());
fragment.setWallet_progressBar_visibility();
}
}
public void sendCoins(final Wallet wallet, Transaction tx) {
// It's impossible to pick one specific identity that you receive coins from in Bitcoin as there
// could be inputs from many addresses. So instead we just pick the first and assume they were all
// owned by the same person.
try {
Coin value = tx.getValueSentToMe(wallet);
TransactionInput input = tx.getInputs().get(0);
Address from = input.getFromAddress();
final Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, from, value);
System.out.println("Sending ...");
Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
public void onSuccess(Transaction transaction) {
System.out.println("Sent coins back! Transaction hash is " + sendResult.tx.getHashAsString());
// The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
}
public void onFailure(Throwable throwable) {
System.err.println("Failed to send coins :(");
throwable.printStackTrace();
}
});
} catch (ScriptException e) {
// If we didn't understand the scriptSig, just crash.
throw new RuntimeException(e);
} catch (KeyCrypterException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (InsufficientMoneyException e) {
e.printStackTrace();
}
}
public Wallet getReadyWallet() {
if (wallet != null) {
Log.i(TAG, "The ready wallet was returned");
return wallet;
}
return getWallet(network);
}
}

Related

Android telnet client through apache commons

I am fairly new to Android, i want to write a telnet client app for my Android. I have written the code using Apache commons library for telnet. Now i am able to connect to telnet server (for that i have used Asyctask concept) and able to read login banner after a long time i don't know what is causing that. I have modified the example given in Apache commons to work with my android code.I have two java codes in my "src" folder (MainActivity.java and TelnetClientExample.java). First, i want to get the login prompt and then i want user to interact with it please help, Thanks in advance :)
I am posting my screen capture of what i am getting.
MainActivity.java
package com.example.telnetapp;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity{
public static int port_int_address;
private EditText server,port;
private Button connect;
public static String ip,port_address;
public PrintWriter out;
public static TextView textResponse;
static String response;
public InputStream instr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = (EditText)findViewById(R.id.edittext1);
port = (EditText)findViewById(R.id.edittext2);
connect = (Button)findViewById(R.id.connect);
textResponse = (TextView)findViewById(R.id.response);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ip = server.getText().toString();
port_address = port.getText().toString();
port_int_address = Integer.parseInt(port_address);
try{
MyClientTask task = new MyClientTask(ip, port_int_address);
task.execute();
}
catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
TelnetClientExample job;
MyClientTask(String inetAddress, int port){
dstAddress = inetAddress;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
job = new TelnetClientExample();
job.backgroundjob();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
TelnetClientExample.java
package com.example.telnetapp;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.telnet.TelnetClient;
public class TelnetClientExample {
public String remoteip = MainActivity.ip;
public int remoteport= MainActivity.port_int_address;
public static TelnetClient tc = null;
public void backgroundjob() throws IOException {
tc = new TelnetClient();
try {
tc.connect(remoteip, remoteport);
}
catch (Exception e) {
}
}
public void close_con(){
try {
tc.disconnect();
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from disconnecting telnet server ! \n";
}
}
}
The problem is in this code snippet . please look into this and help me to get an interactive session.
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
The problem i am getting -

Check the connected bluetooth devices status

How to know whether a Bluetooth device is still connected to a laptop or not before passing data? I wrote a java program using blue-cove lib to discover and pass the data through the laptop. After passing data for the first time, how can I check whether the device is still connected to laptop before passing data in the next time ?
I saw a similar question like this. But they have asked how to check the Bluetooth device status connected to the android.
You can follow a serie of steps and create an async task to verify the connection while is searching and sharing files between devices.
The functions deviceDiscovered() and inquiryCompleted() are the ones exeuted when a device is found and when the inquiry is finished.
If the device is disconnected, you would get a notify from the method inqueryCompleted and Handle it in the line:
try {
synchronized(lock){
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
In the InterruptedException you can handle the error.
package bt;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.obex.ClientSession;
import javax.obex.HeaderSet;
import javax.obex.Operation;
import javax.obex.ResponseCodes;
import bt.BTListener.MyDeviceListenerFilter;
public class MyDiscoveryListener implements DiscoveryListener{
private static Object lock=new Object();
public ArrayList<RemoteDevice> devices;
public MyDiscoveryListener() {
devices = new ArrayList<RemoteDevice>();
}
public static void main(String[] args) {
MyDiscoveryListener listener = new MyDiscoveryListener();
try{
LocalDevice localDevice = LocalDevice.getLocalDevice();
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
agent.startInquiry(DiscoveryAgent.GIAC, listener);
try {
synchronized(lock){
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("Device Inquiry Completed. ");
UUID[] uuidSet = new UUID[1];
uuidSet[0]=new UUID(0x1105); //OBEX Object Push service
int[] attrIDs = new int[] {
0x0100 // Service name
};
for (RemoteDevice device : listener.devices) {
agent.searchServices(
attrIDs,uuidSet,device,listener);
try {
synchronized(lock){
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("Service search finished.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
String name;
try {
name = btDevice.getFriendlyName(false);
} catch (Exception e) {
name = btDevice.getBluetoothAddress();
}
devices.add(btDevice);
System.out.println("device found: " + name);
}
#Override
public void inquiryCompleted(int arg0) {
synchronized(lock){
lock.notify();
}
}
#Override
public void serviceSearchCompleted(int arg0, int arg1) {
synchronized (lock) {
lock.notify();
}
}
#Override
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
if (serviceName != null) {
System.out.println("service " + serviceName.getValue() + " found " + url);
if(serviceName.getValue().equals("OBEX Object Push")){
sendMessageToDevice(url);
}
} else {
System.out.println("service found " + url);
}
}
}
private static void sendMessageToDevice(String serverURL){
try{
System.out.println("Connecting to " + serverURL);
ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
hsOperation.setHeader(HeaderSet.TYPE, "text");
//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);
// Send some text to server
byte data[] = "Hello World !!!".getBytes("iso-8859-1");
OutputStream os = putOperation.openOutputStream();
os.write(data);
os.close();
putOperation.close();
clientSession.disconnect(null);
clientSession.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

how can i send my message from android client to other android client using my socket java PC server

i have my code that sucessfuly send my client message to server.. can anyone help pls ? i'm new in socket programming. i want to establish a server that sends the message of my android client to other android client... here is my code
CLIENT ANDROID :
package com.example.websocketclient;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Chatroom extends Activity {
public static String msgToServer = null;
TextView uname;
EditText in;
Button snd;
TextView out;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatroom);
uname = (TextView) findViewById(R.id.textViewmynam);
in = (EditText) findViewById(R.id.editTextInput);
snd = (Button) findViewById(R.id.buttonSend);
out = (TextView) findViewById(R.id.textViewOutput);
Bundle bundle = getIntent().getExtras();
String urname = bundle.getString("myname");
uname.setText(urname);
MyClientTask clientTask = new MyClientTask();
clientTask.execute();
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
connect();
return null;
}
}
public void connect() {
Socket sock;
int[] allports = {1111,1919,2020};
int portnum;
for(int i=1;i<allports.length;i++) {
try {
portnum = allports[i];
boolean socketno = Middleware.available(portnum);
String ad = "192.168.149.1";
if(socketno = true) {
sock = new Socket(ad,portnum);
while(socketno) {
sendmsg(sock);
}//while
// sock.close();
}//if
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendmsg (final Socket s) {
snd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//boolean listening = true;
String inmsg = ""+in.getText().toString();
String response = "";
msgToServer = inmsg;
//out.append("you:"+msgToServer+"\n");
try {
DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
DataInputStream inToServer = new DataInputStream(s.getInputStream());
if(outToServer != null){
outToServer.writeBytes(msgToServer+"\n");
}
}
catch (Exception e) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chatroom, menu);
return true;
}
}
Here is my PC Server side :
package Server;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
public class SocketServer extends Thread {
final static int _portNumber = 1919; //Arbitrary port number
public static void main(String[] args)
{
try {
new SocketServer().startServer();
} catch (Exception e) {
System.out.println("I/O failure: " + e.getMessage());
}
}
public void startServer() throws Exception {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(_portNumber);
} catch (IOException e) {
System.err.println("Could not listen on port: " + _portNumber);
System.exit(-1);
}
while (listening) {
System.out.println("Huwat huwat kang client..!");
handleClientRequest(serverSocket);
}
serverSocket.close();
}
private void handleClientRequest(ServerSocket serverSocket) {
try {
new Thread(new ConnectionRequestHandler(serverSocket.accept())).start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Handles client connection requests.
*/
public class ConnectionRequestHandler implements Runnable{
private Socket _socket;
private PrintWriter _out;
private BufferedReader _in;
public ConnectionRequestHandler(Socket socket) {
_socket = socket;
}
public void run() {
String info;
int maxid;
System.out.println("Client connected to socket: " + _socket.toString());
info = _socket.toString();
//incrementing the msg_id
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
_socket.getOutputStream()));
_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
String inputLine;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/finalclient","root","");
PreparedStatement st = con.prepareStatement("select *from msgs order by msg_id desc");
ResultSet r1 = st.executeQuery();
r1.first(); // or r1.next()
maxid = r1.getInt("msg_id") + 1;
while ((inputLine = _in.readLine()) != null) {
System.out.println("Message from Client: "+inputLine);
out.write(inputLine);
try {
PreparedStatement st1=con.prepareStatement("insert into msgs values(?,?,?)");
st1.setInt(1,maxid);
st1.setString(2,info);
st1.setString(3,inputLine);
int count = st1.executeUpdate ();
System.out.println (count + " rows were inserted to Database");
}
catch (Exception e) {
System.out.println("Failed to Insert from DB"+e);
}
}
}
catch (Exception e) {
System.out.println("Failed to Select from DB"+e);
}
}
}
}

Why I am getting java.lang.NullPointerException?

I am trying to test this script, to get print some demo text to my Zebra printer using Android, but I am getting a java.lang.NullPointerException. I have read is something about an initialization, but I can't identify what is the object to initializate.
this is the error:
E/AndroidRuntime(2098):
FATAL EXCEPTION: Thread-9874
Process: com.stihn.sibmovil, PID: 2098
java.lang.NullPointerException
at com.stihn.sibmovil.sendfile.SibPrint.testSendFile(SibPrint.java:88)
at com.stihn.sibmovil.sendfile.SibPrint.access$0(SibPrint.java:86)
at com.stihn.sibmovil.sendfile.SibPrint$1.run(SibPrint.java:53)
at java.lang.Thread.run(Thread.java:841)
Thanks for your help!
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Looper;
import com.stihn.sibmovil.util.SettingsHelper;
import com.zebra.sdk.comm.BluetoothConnection;
import com.zebra.sdk.comm.Connection;
import com.zebra.sdk.comm.ConnectionException;
import com.zebra.sdk.printer.ZebraPrinter;
import com.zebra.sdk.printer.ZebraPrinterFactory;
import com.zebra.sdk.printer.ZebraPrinterLanguageUnknownException;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import com.zebra.sdk.printer.PrinterLanguage;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
public class SibPrint extends Plugin {
ProgressDialog loadingDialog;
Activity activity;
private Context context;
String macAddress;
String filepath;
public PluginResult execute(String action, JSONArray args, String callbackId) {
try {
if (action.equals("sibPrintTicket")) {
String echo = args.getString(0);
filepath = args.getString(1);
macAddress = args.getString(2);
if (echo != null && echo.length() > 0) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
Connection connection = null;
connection = new BluetoothConnection(macAddress);
try {
System.out.println("Imprimiendo ...");
connection.open();
ZebraPrinter printer = ZebraPrinterFactory
.getInstance(connection);
testSendFile(printer);
connection.close();
} catch (ConnectionException e) {
System.out.println("Error Try 1 "
+ e.getMessage());
} catch (ZebraPrinterLanguageUnknownException e) {
System.out.println("Error Catch 1 "
+ e.getMessage());
} finally {
if (activity != null && loadingDialog != null) {
loadingDialog.dismiss();
}
}
Looper.loop();
Looper.myLooper().quit();
}
}).start();
//retornar mensaje de imprimiendo
return new PluginResult(PluginResult.Status.OK, "Imprimiendo..");
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
} else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
private void testSendFile(ZebraPrinter printer) {
try {
File filepath = context.getFileStreamPath("TEST.LBL");
createDemoFile(printer, "TEST.LBL");
printer.sendFileContents(filepath.getAbsolutePath());
this.saveBluetoothAddress(this, macAddress);
} catch (ConnectionException e1) {
System.out.println("Error sending file to printer" + e1.getMessage());
} catch (IOException e) {
System.out.println("Error creating file" + e.getMessage());
}
}
private void saveBluetoothAddress(SibPrint sibPrint,
String macAddress) {
// TODO Auto-generated method stub
}
private void createDemoFile(ZebraPrinter printer, String fileName) throws IOException {
FileOutputStream os = context.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] configLabel = null;
PrinterLanguage pl = printer.getPrinterControlLanguage();
if (pl == PrinterLanguage.ZPL) {
configLabel = "^XA^FO17,16^GB379,371,8^FS^FT65,255^A0N,135,134^FDTEST^FS^XZ".getBytes();
} else if (pl == PrinterLanguage.CPCL) {
String cpclConfigLabel = "! 0 200 200 406 1\r\n" + "ON-FEED IGNORE\r\n" + "BOX 20 20 380 380 8\r\n" + "T 0 6 137 177 TEST\r\n" + "PRINT\r\n";
configLabel = cpclConfigLabel.getBytes();
}
os.write(configLabel);
os.flush();
os.close();
}
}
you got java.lang.NullPointerException in Context
at
File filepath = context.getFileStreamPath("TEST.LBL");
you are not initialize context in your class.
please add
public void SibPrint(Context context){
this.context=context;
}
in your class.
and create consructor in Activity like
SibPrint mSibPrint = new SibPrint(MyActivity.this);
public class SibPrint extends Plugin {
ProgressDialog loadingDialog;
Activity activity;
private Context context;
String macAddress;
String filepath;
//add this method
public void SibPrint(Context context){
this.context=context;
}
.
.
.
}
Try this..
You have not initialize context that's inside testSendFile() method
File filepath = context.getFileStreamPath("TEST.LBL");
you should initialize context before using it otherwise you will get NPE

Track FTP upload data in android?

I have a working FTP system with android, but I want to be able to track the bytes as they get uploaded, so I can update a progress bar as the upload progresses. Is this possible with Android? Right now, I'm using org.apache.common.net.ftp and the code I'm using is below. Also, I am running this in an AsyncTask.
package com.dronnoc.ftp.complex;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;
import org.apache.commons.net.io.Util;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
String text = "BIGFILE"; //Big file here
InputStream data = new ByteArrayInputStream(text.getBytes());
new ComplexFTPTransfer().execute(data);
}
private class ComplexFTPTransfer extends AsyncTask<InputStream, Long[], Void>
{
private FTPClient ftp = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
ftp = new FTPClient();
ftp.connect("hostname");
} catch (SocketException e) {
this.cancel(true);
} catch (IOException e) {
this.cancel(true);
}
Main.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected Void doInBackground(InputStream... params) {
if(!this.isCancelled())
{
try
{
if(ftp.login("user", "pass"))
{
ftp.enterLocalPassiveMode();
InputStream item = params[0];
int streamSize = 0;
while(item.read() != -1)
{
streamSize++;
}
InputStream is = new BufferedInputStream(params[0], streamSize);
OutputStream os = ftp.storeFileStream("/test.txt");
Util.copyStream(is, os, streamSize, streamSize, new CopyStreamListener() {
#Override
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
publishProgress(new Long[] {totalBytesTransferred, streamSize});
}
#Override
public void bytesTransferred(CopyStreamEvent event) {
}
});
ftp.completePendingCommand();
}
ftp.logout();
ftp.disconnect();
}
catch (IOException e) {
}
catch (Exception e) {
}
}
return null;
}
#Override
protected void onProgressUpdate(Long[]... values) {
super.onProgressUpdate(values);
Log.d("UPDATE", values[0] + " of " + values[1] + " copied.");
//TODO Put code here
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Main.this.setProgressBarIndeterminateVisibility(false);
}
}
}
What I want to know is if I can run a progress bar, updating every few uploaded bytes?
Cheers
This question has an implementation of an InputStream that includes a progress callback. Use that InputStream and call publishProgress from that callback for incremental updates during the file upload.
Download this .jar file
httpmime-4.1.1.jar and commons-net.jar
try {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(InetAddress
.getByName(Your host Url));
ftpClient.login(loginName, password);
System.out.println("status :: " + ftpClient.getStatus());
ftpClient.changeWorkingDirectory(your directory name);
ftpClient.setFileType(FTP.IMAGE_FILE_TYPE);
//Your File path set here
File file = new File("/sdcard/my pictures/image.png");
BufferedInputStream buffIn = new BufferedInputStream(
new FileInputStream(myImageFile));
ftpClient.enterLocalPassiveMode();
ProgressInputStream progressInput = new ProgressInputStream(
buffIn);
boolean result = ftpClient.storeFile(UPLOADFILENAME + ".png",
progressInput);
System.out.println("result is :: " + result);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
//ProgressInputStream
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class ProgressInputStream extends InputStream {
/* Key to retrieve progress value from message bundle passed to handler */
public static final String PROGRESS_UPDATE = "progress_update";
private static final int TEN_KILOBYTES = 1024 * 40;
private InputStream inputStream;
//private Handler handler;
private long progress;
private long lastUpdate;
private boolean closed;
public ProgressInputStream(InputStream inputStream) {
this.inputStream = inputStream;
this.progress = 0;
this.lastUpdate = 0;
this.closed = false;
}
#Override
public int read() throws IOException {
int count = inputStream.read();
return incrementCounterAndUpdateDisplay(count);
}
#Override
public int read(byte[] b, int off, int len) throws IOException {
int count = inputStream.read(b, off, len);
return incrementCounterAndUpdateDisplay(count);
}
#Override
public void close() throws IOException {
super.close();
if (closed)
throw new IOException("already closed");
closed = true;
}
private int incrementCounterAndUpdateDisplay(int count) {
if (count < 0)
progress += count;
lastUpdate = maybeUpdateDisplay(progress, lastUpdate);
return count;
}
private long maybeUpdateDisplay(long progress, long lastUpdate) {
if (progress - lastUpdate < TEN_KILOBYTES) {
lastUpdate = progress;
sendLong(PROGRESS_UPDATE, progress);
}
return lastUpdate;
}
public void sendLong(String key, long value) {
Bundle data = new Bundle();
data.putLong(key, value);
Message message = Message.obtain();
message.setData(data);
//handler.sendMessage(message);
}
}
This can be done using Secure FTP Factory library.
You just need to implement an instance of the com.jscape.inet.ftp.FtpListener interface, register the instance with the Ftp class and overload the progress(FtpProgressEvent event) method to capture progress information.
JavaDoc: Overview (secure FTP Factory API)
Download: Java FTP, Java FTPS and Java SFTP Components

Categories