I have an android app that lets me scan barcodes and it saves to csv upon pressing a save button.
Would it be possible for me to auto-save data upon the scan result of a certain column?
So in short save after scan initiated in a certain edit text location.
**EDIT !:
packages and imports used.:
package kinjal.com.barcodescanner;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;**
//btn_save = (Button) findViewById(R.id.button4);
btn_scanecode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanBar(view);
}
});
btn_savedata.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
final String binlocation = edt_binlocation.getText().toString().trim();
final String islenumber = edt_islenumber.getText().toString().trim();
final String shelfnumber = edt_shelf_number.getText().toString().trim();
final String sku_barcode = edt_skubarcode.getText().toString().trim();
final String quantity = edt_quantity.getText().toString().trim();
if (binlocation.length() == 0)
{
edt_binlocation.setError("Enter BIN Location");
} else if (islenumber.length() == 0) {
edt_islenumber.setError("Enter ISLE Number");
} else if (shelfnumber.length() == 0) {
edt_shelf_number.setError("Enter Shelf Number");
} else if (sku_barcode.length() == 0) {
edt_skubarcode.setError("Scan the Item");
} else if (quantity.length() == 0) {
edt_quantity.setError("Enter Quantity");
} else {
try {
File folder = new File(Environment.getExternalStorageDirectory()
+ "/Download/ScannedData");
boolean var = false;
if (!folder.exists())
var = folder.mkdir();
final String filename = folder.toString() + "/" + "ScannedDataFile.csv";
// show waiting screen
// CharSequence contentTitle = getString(R.string.app_name);
//FileWriter(filename, boolean append);
// output = new BufferedWriter(new FileWriter(filename, true));
try {
//BufferedWriter fw = new BufferedWriter(new FileWriter(filename, true));
FileWriter fw = new FileWriter(filename, true);
{
BufferedReader br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
if (line == null) {
fw.append("BIN Number");
fw.write(",");
fw.append("ISIE Number");
fw.write(",");
fw.append("Shelf Number");
fw.write(",");
fw.append("SKU");
fw.write(",");
fw.append("Quantity");
fw.write(",");
fw.write("\n");
}
fw.append(binlocation);
fw.append(',');
fw.append(islenumber);
fw.append(',');
fw.append(shelfnumber);
fw.append(',');
fw.append(sku_barcode);
fw.append(',');
fw.append(quantity);
fw.append(',');
fw.append('\n');
Toast.makeText(Main2Activity.this, "Row Inserted..", Toast.LENGTH_SHORT).show();
fw.flush();
edt_skubarcode.setText("");
edt_quantity.setText("1");
edt_skubarcode.requestFocus();
}
} catch (Exception e) {
}
} catch (Exception e) {
}
}
}
});
}
Related
From the below code I can convert a image file to byte array in my mobile app.But I cannot Convert a video file since OutOfMemoryError exception comes. I want to send a video file to a arduino board. Since I can send a string from android app to arduino, I am trying to send a video file like that. But it fails. I there any other solution to solve my problem?please help.
Code for converting image to byte array
package com.example.krishan.detectusbplugin;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory() + "/Output/" +"My.mp4");
// convertFileToByteArray(file);
System.out.println(Arrays.toString(convertFileToByteArray(file)));
try {
System.out.write(convertFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
}
Code for sending a string to arduino through usb cable
package com.hariharan.arduinousb;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.hariharan.arduinousb.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
tvAppend(textView, "Serial Connection Opened!\n");
} else {
Log.d("SERIAL", "PORT NOT OPEN");
Toast.makeText(getApplicationContext(), "SERIAL , PORT NOT OPEN", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PORT IS NULLPORT IS NULL");
Toast.makeText(getApplicationContext(), "SERIAL , PORT IS NULL", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
Toast.makeText(getApplicationContext(), "SERIAL , PERM NOT GRANTED", Toast.LENGTH_LONG).show();
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int devicePID = device.getProductId();
if (devicePID == 0x0043)//Arduino Product ID in Hexa
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
Toast.makeText(getApplicationContext(), "PID does not match", Toast.LENGTH_LONG).show();
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView, "\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}
I'm learning how to create app with android studio,
this is my code source:
package com.example.droide;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class DroideSphereRuhlmannActivity extends Activity implements OnClickListener {
private TextView logview;
private Button connect, deconnect;
private ImageView forwardArrow, backArrow, rightArrow, leftArrow, stop, topleftArrow, toprightArrow, backleftArrow, backrightArrow;
private BluetoothAdapter mBluetoothAdapter = null;
private String[] logArray = null;
private BtInterface bt = null;
static final String TAG = "Droid";
static final int REQUEST_ENABLE_BT = 3;
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String data = msg.getData().getString("receivedData");
addToLog(data);
}
};
final Handler handlerStatus = new Handler() {
public void handleMessage(Message msg) {
int status = msg.arg1;
if(status == BtInterface.CONNECTED) {
addToLog("Connected");
} else if(status == BtInterface.DISCONNECTED) {
addToLog("Disconnected");
}
}
};
private void addToLog(String message){
for (int i = 1; i < logArray.length; i++){
logArray[i-1] = logArray[i];
}
logArray[logArray.length - 1] = message;
logview.setText("");
for (int i = 0; i < logArray.length; i++){
if (logArray[i] != null){
logview.append(logArray[i] + "\n");
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_remote);
logview = (TextView)findViewById(R.id.logview);
logArray = new String[3];
connect = (Button)findViewById(R.id.connect);
connect.setOnClickListener(this);
deconnect = (Button)findViewById(R.id.deconnect);
deconnect.setOnClickListener(this);
forwardArrow = (ImageView)findViewById(R.id.forward_arrow);
forwardArrow.setOnClickListener(this);
backArrow = (ImageView)findViewById(R.id.back_arrow);
backArrow.setOnClickListener(this);
rightArrow = (ImageView)findViewById(R.id.right_arrow);
rightArrow.setOnClickListener(this);
leftArrow = (ImageView)findViewById(R.id.left_arrow);
leftArrow.setOnClickListener(this);
stop = (ImageView)findViewById(R.id.stop);
stop.setOnClickListener(this);
topleftArrow = (ImageView)findViewById(R.id.topleft_arrow);
topleftArrow.setOnClickListener(this);
toprightArrow = (ImageView)findViewById(R.id.topright_arrow);
toprightArrow.setOnClickListener(this);
backrightArrow = (ImageView)findViewById(R.id.backright_arrow);
backrightArrow.setOnClickListener(this);
backleftArrow = (ImageView)findViewById(R.id.backleft_arrow);
backrightArrow.setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.v(TAG, "Device does not support Bluetooth");
}
else{
if (!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
bt = new BtInterface(handlerStatus, handler);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent moreData){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
bt = new BtInterface(handlerStatus, handler);
}
else if (resultCode == Activity.RESULT_CANCELED)
Log.v(TAG, "BT pas active");
else
Log.v(TAG, "code n'est pas valide");
}
else{
Log.v(TAG, "code n'est pas reconnu");
}
}
#Override
public void onClick(View v) {
if(v == connect) {
addToLog("Appareillage en cours");
bt.connect();
}
else if(v == deconnect) {
addToLog("connexion en cours");
bt.close();
}
else if(v == forwardArrow) {
bt.sendData("F");
}
else if(v == backArrow) {
bt.sendData("B");
}
else if(v == rightArrow) {
bt.sendData("R");
}
else if(v == leftArrow) {
bt.sendData("L");
}
else if( v == topleftArrow){
bt.sendData("I");
}
else if(v == toprightArrow){``
bt.sendData("J");
}
else if(v == backleftArrow){
bt.sendData("G");
}
else if(v ==backrightArrow){
bt.sendData("H");
}
else if(v == stop) {
bt.sendData("S");
}
Error Log:
After that, I got some error like :
"Error:(156, 10) error: reached end of file while parsing"
or
"Error:Execution failed for task ':app:compileDebugJavaWithJavac'."
So now I don't now how to solve that.
If this is your full code then your onClick method has not ending curly bracket and also your main class is not ended with curly bracket.
so add two ending curly braces at end of your code
i already set google tts language to hindi.And in my code i am setting that hindi as a default language by tts.setLanguage(Locale.getDefault()),my code working fine.But when i am using Locale.getDefault().getDisplayLanguage() to get default language,logcat shows English.
I want to set language according to user.
package com.example.texttospeech;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("unused")
public class MainActivity extends Activity implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
EditText ed1,ed2;
Button b1,b2;
AudioManager audioManager;
static final int READ_BLOCK_SIZE = 100;
protected static final int PICKFILE_RESULT_CODE = 1;
protected static final int ACTIVITY_TTS_PASS=1;
#SuppressWarnings("static-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText1);
b1=(Button)findViewById(R.id.button1);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tts = new TextToSpeech(this, this);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int amStreamMusicMaxVol = audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC);
audioManager.setStreamVolume(audioManager.STREAM_MUSIC, amStreamMusicMaxVol, 0);
audioManager.setSpeakerphoneOn(true);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked",Toast.LENGTH_SHORT).show();
try {
if(ed1.getText().toString()==null || ed1.getText().toString().matches(""))
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file.txt/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}else
{
savefile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// openfile();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
Locale.getDefault().getDisplayLanguage();
Log.e("--f----f-----f-- ",""+Locale.getDefault().getDisplayLanguage());
if (status == TextToSpeech.SUCCESS)
{
int result = tts.setLanguage(Locale.getDefault());
Log.e("--g----g-----g--",""+result);
tts.setLanguage(new Locale("hi_IN"));
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED)
{
Log.e("TTS", "This Language is not supported");
}
else {
b1.setEnabled(true);
try {
savefile();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void savefile() throws IOException {
String text = ed1.getText().toString();
FileOutputStream fos = null;
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MynewText/" );
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, "newtest" + ".txt");
if (!myFile.exists())
{
myFile.createNewFile();
}
fos = new FileOutputStream(myFile);
fos.write(text.getBytes());
fos.close();
Toast.makeText(getBaseContext(), "File saved successfully!",Toast.LENGTH_SHORT).show();
tts.setSpeechRate(0);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
try {
// Read text from file
File sdcard = Environment.getExternalStorageDirectory();
File file1 = new File(sdcard,"MynewText/newtest.txt");
//Read text from file
StringBuilder text1 = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file1));
String line;
while ((line = br.readLine()) != null)
{
text1.append(line);
text1.append('\n');
}
ed2.setText(text1);
br.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case ACTIVITY_TTS_PASS:
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
tts = new TextToSpeech(getApplicationContext(), this);
int availability = tts.isLanguageAvailable(new Locale("hin-IND"));
switch(availability)
{
case TextToSpeech.LANG_AVAILABLE:
Log.d("TTS", "Language available");
break;
case TextToSpeech.LANG_NOT_SUPPORTED:
Log.d("TTS", "Language not supported");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
break;
case TextToSpeech.LANG_MISSING_DATA:
Log.d("TTS", "Language missing data");
break;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
Log.d("TTS", "Contry available");
break;
default:
Log.d("TTS", "default");
}
}
else {
Log.d("TTS", "fail");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
}
break;
default:
Log.d("TTS", "case default");
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
For getting Default language set in setting > Language and Input > Google-Text-To-Speech default language set , i used :
tts.getLanguage();
I am creating an android application that consists of printing document from android application. Here I connected android device and printer via usb. I want to set the page attributes such as new line after the end of the line and page heading and page borders.Please tell me how to do this.Big thanks in advance
This is what i had done for printing from android to printer via USB :
package com.developer.printer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
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 Printer extends Activity {
Button create_file;
PendingIntent mPermissionIntent;
UsbManager usbManager;
UsbDevice device;
EditText print_text;
UsbDevice printer = null;
private static final int PRINTER_VENDOR_ID = 1256;
private String filename = "MySampleFile.txt";
private String filepath = "PanelFilesstorage";
File myInternalFile;
String data= "This is a sample text";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_demo_printer);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory , filename);
print_text = (EditText)findViewById(R.id.editText_printer);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
if (deviceList.size() <= 0)
{
Toast.makeText(getApplicationContext(), "Info: No device found", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "No of devices"+deviceList.size(), Toast.LENGTH_SHORT).show();
((TextView) findViewById(R.id.textView_devices))
.setText("No of device : " + deviceList.size());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
int count = 0;
mPermissionIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent(ACTION_USB_PERMISSION), 0);
while (deviceIterator.hasNext()) {
count++;
device = deviceIterator.next();
Log.i("info", "Device No " + count + "........");
Log.i("info", "Vendor id : " + device.getVendorId());
Log.i("info", "Product id : " + device.getProductId());
Log.i("info", "Device name : " + device.getDeviceName());
Log.i("info", "Device class : " + device.getClass().getName());
Log.i("info", "Device protocol: " + device.getDeviceProtocol());
Log.i("info", "Device subclass : " + device.getDeviceSubclass());
if (device.getVendorId() == PRINTER_VENDOR_ID) {
printer = device;
break;
}
}
findViewById(R.id.button_print).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Info", "Print command given");
IntentFilter filter = new IntentFilter(
ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
if (printer != null) {
usbManager.requestPermission(printer,
mPermissionIntent);
} else {
Log.e("Exception", "Printer not found");
}
}
});
} catch (Exception e) {
Log.e("Exception", "Exception in onCreate " + e.getMessage());
e.printStackTrace();
}
findViewById(R.id.button_create_file).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
FileOutputStream fos = new FileOutputStream(myInternalFile+"\n");
fos.write(data.toString().getBytes());
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
try {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
final UsbDevice printerDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if (printerDevice != null) {
Log.i("Info", "Device permission granted");
startPrinting(printerDevice);
}
}
else
{
Log.d("Debug", "permission denied for device "
+ printerDevice);
}
}
}
} catch (Exception e)
{
Log.e("Exception", "Exception in onRecieve " + e.getMessage());
e.printStackTrace();
}
}
};
public void startPrinting(final UsbDevice printerDevice)
{
new Handler().post(new Runnable()
{
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run()
{
try
{
Log.i("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = usbManager.openDevice(printer);
conn.claimInterface(usbInterface, true);
String myStringData = print_text.getText().toString();
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request)
{
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
}
else
{
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint,
myStringData.getBytes(),
myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " +transfered);
} catch (Exception e)
{
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally
{
try
{
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
}
catch (Exception e)
{
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
}
Hi friendsIam doing an android application in that i want to select one video from my sd card and want to upload it to ftp server.While iam running the project in the emulator i got 04-28 18:22:00.810: ERROR/AndroidRuntime(1053): java.lang.NoClassDefFoundError: org.apache.commons.net.ftp.FTPClient.Is there any way to solve this problem.I included two jar files org.apache.commons.net.jar and commons-net-1.4.1.jar by right click my project->properties->java build path->add external jars.Even i added the jar files,the project did'nt gets runned.Please help me if anybody knows...
Iam using the below code:
package net.jeema.UploadFTP;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;
**import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;**
import org.w3c.dom.CharacterData;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class UploadFTPActivity extends Activity {
SQLiteDatabase myDataBase;
// public String[] gur = new String[4];
private static final int SELECT_VIDEO = 1;
String strXmlResponse, url = null;
String selectedPath, extension;
Button bnupload, bnbrowse = null;
String fname = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addnewvideo);
bnupload = (Button) findViewById(R.id.buttonUpload);
bnbrowse = (Button) findViewById(R.id.buttonBrowse);
addVIDEO();
}
public void addVIDEO {
bnbrowse.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Video"),
SELECT_VIDEO);
}
});
}
public void onActivityResult(int requestCode, int resultCode,
final Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO) {
System.out.println("SELECT VIDEO");
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
System.out.println("SELECT_VIDEO Path : " + selectedPath);
int pos = selectedPath.lastIndexOf(".");
if (pos > 0) {
extension = selectedPath.substring(pos + 1);
}
doFileUpload();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void doFileUpload() {
bnupload.setOnClickListener(new OnClickListener() {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
public void onClick(View arg0) {
UUID uniqueKey = UUID.randomUUID();
fname = uniqueKey.toString();
Log.e("UNIQUE NAME", fname);
// TODO Auto-generated method stub
String hostName = "MY HOST NAME";
String username = "****";
String password = "****";
String location = selectedPath;
FTPClient ftp = null;
InputStream in = null;
try {
ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/uploads");
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Success");
}
File f1 = new File(location);
in = new FileInputStream(f1);
ftp.storeFile(fname+"."+extension, in);
System.out.println("SUCCESS");
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
});
}
}
I got the output using simple java program with code below.But i want to do it in android actoivity:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpTest {
public static void main(String args[]) {
String hostName = "MY HOST NAME";
String username = "****";
String password = "****";
String location = "F:\\droid-samples\\VID-20120421-103134.3gp";
FTPClient ftp = null;
InputStream in = null;
try {
ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/uploads");
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Success");
}
File f1 = new File(location);
in = new FileInputStream(f1);
ftp.storeFile("VID-20120421-103134.3gp", in);
System.out.println("SUCCESS");
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You could try to solve the 0 bytes issue:
ftp.enterLocalPassiveMode();