I am creating Xmpp application using SMACK api and Spark for test.
I am able to send from Spark but I cannot see Any Directory and File created in android gallery.
I log the method incoming.getAmountWritten() and it is giving me
07-27 21:00:58.789: V/Receiving Status ...(17652): 208861
It means I have got the file and now I have to write on physical storage. May be there is problem with my android code.
Please find Android Code
#Override
public void fileTransferRequest(final FileTransferRequest fileRequest) {
final File dir = Environment.getExternalStorageDirectory();
final File folder = new File(dir+ "/illuxplain/");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Thread receiving = new Thread(new Runnable() {
#Override
public void run() {
IncomingFileTransfer incoming = fileRequest.accept();
Log.v("Receiving File Name", incoming.getFileName());
File file = new File(folder, incoming.getFileName());
try {
incoming.recieveFile(file);
while (!incoming.isDone()) {
try {
Thread.sleep(1000L);
} catch (Exception e) {
Log.e("", e.getMessage());
}
if (incoming.getStatus().equals(Status.error)) {
Log.e("ERROR!!! ", incoming.getError() + "");
}
if (incoming.getException() != null) {
incoming.getException().printStackTrace();
}
}
Log.v("Receiving Status ... ",""+incoming.getAmountWritten());
} catch (Exception e) {
e.printStackTrace();
Log.e("", e.getMessage());
}
}
});
receiving.start();
}else{
System.out.println("Directory Not Created");
}
}
}
When I go to gallery and see if I got the file. I see no directory created and of course no file.
You need to write the data into the file. Here is an example to code to write the data in to the file
File file = new File(folder, incoming.getFileName());
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
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
I am trying to write some json data to the file, below is what i have tried.
JSONObject obj = new JSONObject();
try {
obj.put("name", "mkyong.com");
} catch (JSONException e2) {
e2.printStackTrace();
}
try {
obj.put("age", new Integer(100));
} catch (JSONException e2) {
e2.printStackTrace();
}
ArrayList list = new ArrayList();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
try {
obj.put("messages", list);
} catch (JSONException e1) {
e1.printStackTrace();
}
FileOutputStream fs;
String filename = "Sample.json";
try {
fs = openFileOutput(filename, Context.MODE_APPEND);
fs.write(obj.toString().getBytes());
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I dont get any errors though, but the file created is not visible. Should i have to read it to verify its written properly?? It would be of great help if i can see the created file in the src folder since i write many stuff, its easy to validate.
Probably lame, but we can locate the file in the DDMS perspective and pull out tag will will be visible!! From there, we can pull it out and view it from the local computer!!
Try to change
String filename = "Sample.txt";
instead of
String filename = "Sample.json";
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)
I used following code for downloading XML file from ftp to android phone memory using that i able to connect ftp but while retrieving XML to local memory it is giving following exception 07-19 15:01:03.721: DEBUG/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
please help somebody thank you,
Java class
private void fnfileDownloadBuf()
{
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
//client.connect("ftp://ftp.qualityinaction.net/QIA/Questions/Airlines/");
client.connect("ftp.qualityinaction.net");
client.login("qualityinaction.net","password");
client.setFileType(FTP.BINARY_FILE_TYPE);
//
// The remote filename to be downloaded.
//
// String filename = "/QIA/Questions/Airlines/index.xml";
String filename = getFilesDir().getAbsolutePath()+ File.separator + "/index.xml";
// String filename = "/QIA/Questions/Airlines/index.xml";
File file = new File(filename);
fos = new FileOutputStream(file);
//
// Download file from FTP server
//
//client.retrieveFile("/" + filename, fos);
client.retrieveFile("/QIA/Questions/Airlines/index.xml;type=i", fos);
// client.retrieveFile( getFilesDir().getAbsolutePath()+ File.separator + "/index.xml", fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
manifest XML file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Exception
exception 07-19 15:01:03.721: DEBUG/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
for that you have to use passive mode corrected code as shown below..
** Java Code **
FTPClient ObjFtpCon = new FTPClient();
try
{
ObjFtpCon.connect(strIp);
if (ObjFtpCon.login(strFtpUser, strFtpPwd))
{
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/QIA/Questions/Hotel/");
String[] strArrQuesFiles=ObjFtpCon.listNames();
int intcnt=0;
boolean blnresult = false;
File objfile=new File(getFilesDir().getAbsolutePath()+ "/Questions");
if(!objfile.exists())objfile.mkdirs();
objfile=null;
for(intcnt=0;intcnt<strArrQuesFiles.length;intcnt++)
{
objfile=new File(getFilesDir().getAbsolutePath()+ File.separator + "/Questions/" + strArrQuesFiles[intcnt]);
objfile.createNewFile();
//ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
FileOutputStream objFos=new FileOutputStream(objfile);
blnresult=ObjFtpCon.retrieveFile(strArrQuesFiles[intcnt] , objFos);
objFos.close();
}
// boolean result = con.storeFile("/QIA/Response/test/Responses.xml", in);
if (blnresult) dlgAlert.setMessage("Questions Are Successfully Downloaded").create().show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
}
}