CSV file to FTP android - android

here is m code for creating and uploading a csv file to ftp for acceleration data and time :
case R.id.button_csv:
start.setEnabled(true);
pause.setEnabled(false);
csv.setEnabled(false);
try {
String s;
FileWriter datei = new FileWriter("Fahrt1.csv");
BufferedWriter dateiFahrt = new BufferedWriter (datei);
dateiFahrt.write("Time"+","+"ax"+","+"ay"+","+"az"+"\n");
for (int i=0; i<sensorDataTime.size(); i++)
{
s=sensorDataTime.get(i)+","+sensorDataAx.get(i).toString()+","+sensorDataAy.get(i).toString()+","+sensorDataAz.get(i).toString()+"\n";
dateiFahrt.write(s);
}
dateiFahrt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
goforIt(); //write to given ftp client
break;
}
}
//method for uploading a file to ftp client
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("server");
if (con.login("userName", "password"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "Fahrt1.csv";
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/Fahrt1.csv", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
when i run my app on device evertyhin works fine but when i press the csv button then it throw me an excetption :
android.os.NetworkOnMainThreadExcetption. but eclipse says that my code is just fine. so what to do ?

In Android like in most mobile environments it isn't permited to run network code on the Main thread since the main Thread is in charge of drawing UI and other taks relevant to the user experience, that's what that exception is telling you you'll need to use wrap the network code (tour goForit() in an AsyncTask or in a Thread

Related

Calculate Speed and Bytes Transfer Rate in FTP download Android

I am planning to create an application for downloading a file from FTP server, Below code has working fine with the functionality, But I need to show current speed and transfer rate while downloading a file, Please help me to solve this problem,
private boolean downloadSingleFile(String remoteFilePath, File downloadFile) {
boolean status = false;
try {
con = new FTPClient();
con.setConnectTimeout(5000);
con.connect(host);
if (con.login(username, password)) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
File parentDir = downloadFile.getParentFile();
if (!parentDir.exists())
parentDir.mkdir();
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(
new FileOutputStream(downloadFile));
con.setFileType(FTP.BINARY_FILE_TYPE);
status = con.retrieveFile(remoteFilePath, outputStream);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
con.logout();
con.disconnect();
}
} else {
con.logout();
con.disconnect();
// delayWait(duration);
}
}
catch (UnknownHostException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
}
return status;
}
If i would like to download a more than 5Mb or 50 Mb file this requirement will be useful for the user to know about the current speed of the device , Please help me to finish this issues.
Regards
Priya

Android Core API Download File

I am trying firstly to download the file and its content from Dropbox in Android app using Dropbox Core API but when i execute the following code the app crushes.
EDIT: I have used two functions downloadDropboxFile and copy functions. The problem is that i am getting blank data when i read the local file which is supposed to contain the dropbox file data.
Here is the code where i call the function
downloadDropboxFile("/userandpass.txt");
if (mDBApi.getSession().isLinked())
{
InputStream instream = new FileInputStream(String.valueOf(getExternalCacheDir()) + "/userandpass.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
mTestOutput.setText(buffreader.readLine());
}
Here is the functions
private boolean downloadDropboxFile(String fileSelected) {
File dir = new File(String.valueOf(getExternalCacheDir()));
if (!dir.exists())
dir.mkdirs();
try {
File localFile = new File(dir + fileSelected);
if (!localFile.exists()) {
localFile.createNewFile();
copy(fileSelected, localFile);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private void copy(final String dbPath, final File localFile) {
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
DropboxAPI.DropboxInputStream fd = mDBApi.getFileStream(dbPath,null);
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}). start();
}
Dropbox Core API Implementation on Android Studio:
On app/libs i have the:
dropbox-android-sdk-1.6.3.jar
httpmime--4.0.3.jar
json_simple-1.1.jar
Your issue is here :
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
The exception is :
java.io.IOException: open failed: EROFS (Read-only file system)
This means you're trying to create a File on a location that is read only in the phone's memory, I'm guessing the internal storage. Have a look at this excellent answer by Mark Murphy on creating a File based on locations that can be written to.
Hoping this has been of some help, happy coding ;-)

Android File Uploading to Server Empty

Hi I have a xml file on my phone's disk. And I wanna upload it to server. I achieved it but the problem is xml file is empty when it is in server. The function below is running correctly , I mean the xml file is uploading to server correctly but it's empty. Why?
private void uploadXmlFile(int levelID){
String FTP_HOST= "181.50.149.1";
String FTP_USER = "kdirrrri";
String FTP_PASS ="123456";
File f = new File(Environment.getExternalStorageDirectory()+"/kadirgame/"+levelID+".xml");
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST,21);
client.login(FTP_USER, FTP_PASS);
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory("/levels/");
// client.upload(f);
client.upload(f, new MyTransferListener());
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}

Transfer data between 2 android devices

I'd like write an app to transfer data between 2 android devices on the same wifi network, like as there is a share folder.
How can i do this?
Thanks
EDIT (My solution):
My Server wait for request
private boolean startServer() {
try {
server = new ServerSocket(port);
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
return true;
}
public void runServer() {
while (this.go) {
try {
Log.d("BurgerClub", "Server in attesa di richieste");
Socket s1 = server.accept();
OutputStream s1out = s1.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
s1out));
BufferedReader br = new BufferedReader(new FileReader(this.path));
String counter = br.readLine();
counter = counter != null ? counter : "000";
br.close();
bw.write(counter);
bw.close();
s1.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
My Client (Runnable object)
public void run() {
try {
this.openConnection();
// Se il socket รจ connesso
if( !this.s1.isClosed() ) {
InputStream is = this.s1.getInputStream();
BufferedReader dis = new BufferedReader(new InputStreamReader(is));
line = dis.readLine();
if( !this.previousCounter.equals(line.trim()) ) {
((BurgerClub_MonitorActivity) counterContext).runOnUiThread(new Runnable() {
#Override
public void run() {
TextView edit = (TextView)(((BurgerClub_MonitorActivity) counterContext).findViewById(R.id.textActionCounter));
edit.setText(line);
}
});
this.previousCounter = line.trim();
}
dis.close();
}
} catch (ConnectException connExc) {
connExc.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Throwable ex) {
ex.printStackTrace();
}
One device needs to serve as a server and the other one will be the client.
The basic flow needs to be something of this sort:
Server device opens a socket and listens on it.
Server device broadcasts the local IP and port it's listening on.
Client device receives broadcast and initiates a connection.
Perform data transfer.
Read about NFC (Near field communication)
http://developer.android.com/guide/topics/connectivity/nfc/index.html

Using Dropbox API to upload a file with Android

How can I upload a File (graphic, audio and video file) with Android using the Dropbox API to Dropbox? I followed the tutorial on the Dropbox SDK Android page and could get the sample to work. But now instead of a String I want to upload an actual File object and am struggling.
The sample code works without any problems and looks like this:
String fileContents = "Hello World!";
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContents.getBytes());
try {
Entry newEntry = mDBApi.putFile("/testing_123456.txt", inputStream, fileContents.length(), null, null);
} catch (DropboxUnlinkedException e) {
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
}
But when I try to change it and upload an actual file with this code:
File tmpFile = new File(fullPath, "IMG_2012-03-12_10-22-09_thumb.jpg");
// convert File to byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(tmpFile);
bos.close();
oos.close();
byte[] bytes = bos.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
try {
Entry newEntry = mDBApi.putFile("/IMG_2012-03-12_10-22-09_thumb.jpg", inputStream, tmpFile.length(), null, null);
} catch (DropboxUnlinkedException e) {
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
}
I have no success getting a DropboxException error. I think something where I try to convert the File object to the byte-stream must be wrong but this is just an assumption.
Other than the String example there is nothing else documented on the Dropbox page for Android.
Thanks for any help.
I found the solution - if anyone is interested here is the working code:
private DropboxAPI<AndroidAuthSession> mDBApi;//global variable
File tmpFile = new File(fullPath, "IMG_2012-03-12_10-22-09_thumb.jpg");
FileInputStream fis = new FileInputStream(tmpFile);
try {
DropboxAPI.Entry newEntry = mDBApi.putFileOverwrite("IMG_2012-03-12_10-22-09_thumb.jpg", fis, tmpFile.length(), null);
} catch (DropboxUnlinkedException e) {
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
}
Here is another implementation of Dropbox API to upload and download a file.
This can be implemented for any type of file.
String file_name = "/my_file.txt";
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + file_name;
AndroidAuthSession session;
public void initDropBox() {
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
mDBApi.getSession().startOAuth2Authentication(MyActivity.this);
}
Entry response;
public void uploadFile() {
writeFileContent(file_path);
File file = new File(file_path);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
response = mDBApi.putFile("/my_file.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void downloadFile() {
File file = new File(file_path);
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DropboxFileInfo info = null;
try {
info = mDBApi.getFile("/my_file.txt", null, outputStream, null);
Log.i("DbExampleLog", "The file's rev is: "
+ info.getMetadata().rev);
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// Required to complete auth, sets the access token on the
// session
mDBApi.getSession().finishAuthentication();
String accessToken = mDBApi.getSession().getOAuth2AccessToken();
/**
* You'll need this token again after your app closes, so it's
* important to save it for future access (though it's not shown
* here). If you don't, the user will have to re-authenticate
* every time they use your app. A common way to implement
* storing keys is through Android's SharedPreferences API.
*/
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
->Call uploadFile() and downLoadFile() method in child thread otherwise it will give you exception
->For that use AsyncTask and call these above method in doInBackground method.
Hope this will be helpful...Thanks
Here is another example which uses the Dropbox v2 API but a 3rd party SDK. It works exactly the same for Google Drive, OneDrive and Box.com by the way.
// CloudStorage cs = new Box(context, "[clientIdentifier]", "[clientSecret]");
// CloudStorage cs = new OneDrive(context, "[clientIdentifier]", "[clientSecret]");
// CloudStorage cs = new GoogleDrive(context, "[clientIdentifier]", "[clientSecret]");
CloudStorage cs = new Dropbox(context, "[clientIdentifier]", "[clientSecret]");
new Thread() {
#Override
public void run() {
cs.createFolder("/TestFolder"); // <---
InputStream stream = null;
try {
AssetManager assetManager = getAssets();
stream = assetManager.open("UserData.csv");
long size = assetManager.openFd("UserData.csv").getLength();
cs.upload("/TestFolder/Data.csv", stream, size, false); // <---
} catch (Exception e) {
// TODO: handle error
} finally {
// TODO: close stream
}
}
}.start();
It uses the CloudRail Android SDK
#e-nature's answer is more than correct...just thought I'd point everyone to Dropbox's official site that shows how to upload a file and much more.
Also, #e-nature's answer overwrites files with the same name, so if you don't want that behaviour simply use .putFile instead of .putFileOverwrite. .putFile has an extra argument, you can simply add null to to the end. More info.
According to the latest documentation of dropbox API V2:
// Create Dropbox client
val config = DbxRequestConfig.newBuilder("dropbox/java-tutorial").build()
client = DbxClientV2(config, getString(R.string.token))
// Uploading file
FileInputStream(file).use { item ->
val metadata = client.files().uploadBuilder("/${file.absolutePath.substringAfterLast("/")}")
.uploadAndFinish(item)
}
And if you want to overwrite file then add this to client:
.withMode(WriteMode.OVERWRITE)
.uploadAndFinish(item)

Categories

Resources