Parsing XML with Document Builder - android

In my application I'm trying to download a file from a FTP-server and convert the retrieved inputstream to a Document object, so I will be able to parse the XML.
I did this before and it worked just fine, but for some odd reason the conversion to a Document object keeps running and will not finish. This is really weird considering I didn't modify any of my code. Here is my code:
public Document download(Document document){
Log.d("Download", "Attempt to download file");
String remoteFile;
InputStream inputStream;
try{
String rootDirectory = ftpClient.printWorkingDirectory();
FTPFile[] locatedFiles = ftpClient.listFiles(rootDirectory);
int x = locatedFiles.length;
if(x != 0){
remoteFile = locatedFiles[0].getName();
Log.d("Download", "File detected");
try{
ftpClient.setBufferSize(1024*1024);
inputStream = ftpClient.retrieveFileStream(remoteFile);
Log.d("Download", "File retrieved");
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Log.d("Download", "Builder object made for converting file");
try{
document = builder.parse(inputStream); // This is the piece of code which keeps running and never finishes
Log.d("Download", "File converted");
try{
inputStream.close();
User.getInstance().setDownloadedDay(User.getInstance().getCurrentDay());
User.getInstance().setDownloadedMonth(User.getInstance().getCurrentMonth());
User.getInstance().setDownloadedYear(User.getInstance().getCurrentYear());
Log.d("Download", "Closed input stream");
}catch(IOException e){
Log.e("Download", e.getMessage());
}
}catch(SAXException e){
Log.e("Download", e.getMessage());
}catch(IOException e){
Log.e("Download", e.getMessage());
}
}catch(ParserConfigurationException e){
Log.e("Download", e.getMessage());
}
}catch(IOException e){
Log.e("Download", e.getMessage());
}
}else{
Log.w("Download", "No file detected");
}
}catch(IOException e){
Log.e("Download", e.getMessage());
}
return document;
}
The Log where it says "File converted" never pops up, which indicates the conversion is still in progress. I've tried multiple XML files to solve my problem (like smaller ones), but my application keeps failing this process.
Can someone tell me what's going on?

I checked my FTP-server and it didn't run well.
So I rebootet my laptop and tried to run it again.
My application runs fine at the moment, it wasn't the code, it was a problem with the server.

Related

Android OS - How to track Azure upload progress

I've been working with Azure on the Android OS and I managed to upload my video file (.mp4) to a Container I had already prepared for it.
I did this by getting a Shared Access Signature (SAS) first, which provided me with:
a temporary key
the name of the container to where I want to send the files
the server URI
Then, I started an AsyncTask to send the file to the container using the "upload".
I checked the container, and the file gets uploaded perfectly, no problems on that end.
My question is regarding the progress of the upload. Is it possible to track it? I would like to have an upload bar to give a better UX.
P.S - I'm using the Azure Mobile SDK
Here's my code:
private void uploadFile(String filename){
mFileTransferInProgress = true;
try {
Log.d("Funky Stuff", "Blob Azure Config");
final String gFilename = filename;
File file = new File(filename); // File path
String blobUri = blobServerURL + sharedAccessSignature.replaceAll("\"", "");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
//Container name here
CloudBlobContainer container = blobCLient.getContainerReference(blobContainer);
blob = container.getBlockBlobReference(file.getName());
//fileToByteConverter is a method to convert files to a byte[]
byte[] buffer = fileToByteConverter(file);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
if (blob != null) {
new UploadFileToAzure().execute(inputStream);
}
} catch (StorageException e) {
Log.d("Funky Stuff", "StorageException: " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("Funky Stuff", "IOException: " + e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.d("Funky Stuff", "Exception: " + e.toString());
e.printStackTrace();
}
mFileTransferInProgress = false;
//TODO: Missing ProgressChanged method from AWS
}
private class UploadFileToAzure extends
AsyncTask <ByteArrayInputStream, Void, Void>
{
#Override
protected Void doInBackground(ByteArrayInputStream... params) {
try {
Log.d("Funky Stuff", "Entered UploadFileToAzure Async" + uploadEvent.mFilename);
//Method to upload, takes an InputStream and a size
blob.upload(params[0], params[0].available());
params[0].close();
} catch (StorageException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Thanks!
You can split your file and send its part using Block, there is a good example of your case in this link but it used C# so you should find the corresponding function in the android library reference.
Basically instead of sending you file as one big file, you split it to multiple files (bytes) and send it to azure so you can track the progress on how many bytes that already sent to azure

Can not read text files

I am trying to write and read a text file which is full of words and add it to an ArrayList. The ArrayList later is used from another part of the program to display text in a TextView. But when i run the program and open the specific part of it, then there is nothing. The ArrayList is just empty. I don't get any exceptions but for some reason it doesn't work. Please help me.
I don't seem to have problems with the file writing:
TextView txt = (TextView)findViewById(R.id.testTxt);
safe = txt.getText().toString();
try {
FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(safe);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException ex){
Log.e("Exception", "File write failed: ");
}
} catch (IOException e) {
Log.e("Exception", "File write failed: ");
}
But I think the problem is in the file reading. I made some "Log.d" and found out that everything works fine till the InputStreamReader line:
public favHacks() {
testList = new ArrayList<String>();
try {
//Works fine till here
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput("test.txt"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null )
{
testList.add(receiveString);
}
bufferedReader.close();
}
catch (FileNotFoundException ex) {
Log.d("login activity", "File not found: ");
} catch (IOException ex) {
Log.d("login activity", "Can not read file: ");
}
}
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
http://developer.android.com/training/basics/data-storage/shared-preferences.html
also if you want to write/read files, or do any kind of operations that can block the Main Thread try to use another Thread like when you are trying to save the data in a file or use a Handler if you have multiple Threads (one for saving and one for reading).
https://developer.android.com/training/multiple-threads/index.html
In your code the method called favHacks can return an ArrayList with the list of all the strings Something like
//
public ArrayList<String> readFromFile(String file){
ArrayList<String> mArrayList= new ArrayList<String>();
//read from file here
return mArrayList;
}
but as I said before, you need to the operations that can block the UI thread in a new Thread.
https://developer.android.com/training/multiple-threads/communicate-ui.html
And also I think that the best way to do this is using Asynk task
Why and how to use asynctask

android not running on my phone, but on my emulator does

i wrote this ftp upload method...it works great on the emulator but doesnt on my phone...
can someone tell me why not?
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.atw.hu");
client.login("festivale", "festivale12");
Log.d("TravellerLog :: ", "Csatlakozva: ftp.atw.hu");
//
// Create an InputStream of the file to be uploaded
//
client.setFileType(FTP.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
String substr = globalconstant.path.substring(4, globalconstant.path.length());
String filename = substr + "/Festivale.db";
Log.e("TravellerLog :: ", substr + "/Festivale.db");
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile("Festivale.db", fis);
Log.d("TravellerLog :: ", "Feltöltve");
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
pls help i'm trying to do this ftp almost 3hours ago :S
On devices, you need to use a separate thread to handle the ftp connection.
"By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities."[android.developer.com/guide/components/services.html]

Android Uploading a file on ftp

Android file uploading issue
I am trying to upload image on my ftp server ,its not giving me any exception or error but image in nt deployed.Can anyone working on uploading image can identify problem.
FTPClient con = new FTPClient();
try{
con.connect("host",21);
con.login(username, pswd);
con.setFileType(FTP.BINARY_FILE_TYPE);
con.setFileTransferMode(FTP.ASCII_FILE_TYPE);
con.setSoTimeout(10000);
con.enterLocalPassiveMode();
if (con.login(username, pswd)) {
try {
File sFile = new File("mnt/sdcard/DCIM/download.jpg");
// connect.setText(sFile.toString());
BufferedInputStream buffIn = null;
buffIn = new BufferedInputStream(
new FileInputStream(sFile));
try {
String fileName = sFile.getName();
while (!dataUpResp) {
dataUpResp = con.storeFile(fileName,
buffIn);
// publishProgress("" + 10);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.getMessage();
}
}
} catch (IOException e) {
}
Isn't it an issue that there are 2 times logging in in your code?
con.login(username, pswd); // 1st time
con.setFileType(FTP.BINARY_FILE_TYPE);
con.setFileTransferMode(FTP.ASCII_FILE_TYPE);
con.setSoTimeout(10000);
con.enterLocalPassiveMode();
if (con.login(username, pswd)) // 2nd time
Also you didn't use logout/disconnect for FTPClient and there are no flush and close for streams.
Tried your code with commons-net-3.2.jar with conjunctions of FileZilla FTP Server and it works fine.

Android Internal Object Storage

I am trying to save ArrayLists(ArrayOne, ArrayTwo, and ArrayThree) of EditText's to the internal storage. As commented, it clearly shows that it attempts the save, but I never get another TOAST after that. Any help as of why it doesn't show "Save completed" or any error is appreciated.
public void save(Context c)
{
String fileName;
Toast.makeText(this, "Attempting Save", Toast.LENGTH_SHORT).show();//THIS SHOWS
if(semester.getText().toString().length() == 0)
{
Toast.makeText(c, "Please enter a filename", Toast.LENGTH_SHORT).show();
}
else
{
fileName = "test.dat";
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
fos = this.openFileOutput(fileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ArrayOne);
oos.writeObject(ArrayTwo);
oos.writeObject(ArrayThree);
Toast.makeText(c, "Save Completed", Toast.LENGTH_SHORT).show(); //THIS NEVER SHOWS
}
catch (FileNotFoundException e)
{
Toast.makeText(c, "Could not find " + fileName + " to save.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (oos != null)
oos.close();
if (fos != null)
fos.close();
}
catch (Exception e)
{ /* do nothing */ }
}
}
}
The problem is that the EditText class is not serializable
If you debug and put a break point at on the printStackTrace and examine the IOException it will tell you that
catch (IOException e
{
e.printStackTrace();
}
Classes have to use "implements Serializable" in order for them to be written out as objects, which EditText does not have.
You can not extend the class and add the serializable tag either because the underlying class will still throw the exception.
I suggest you either serialize the data via your own class or save whatever you are trying to do with some other method.
I think the error is beings swallowed in your first Try block because you're only catching FileNotFound and IOException - just for debugging purposes you could catch the generic Exception and printout the stacktrace.
If it also helps this is what I do:
java.io.File file = new java.io.File("/sdcard/mystorage/ArrayOne.bin");
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
out.writeObject(obj);
out.close();
Best
-serkan
If nothing shows after the "Attempting save" you´re getting some exception in this block
catch (IOException e)
{
e.printStackTrace();
}
And you´re not viewing it in any Toast. Also you can be here in this way doing nothing with your exception:
catch (Exception e)
{ /* do nothing */ }
Instead of toasting your messages.. try to use LogCat for debbugging, is easy to use and also you don't need to put toast code in your code. Tell me how is going.

Categories

Resources