I'm trying to connect my Android application to my company local network (Windows) using smb protocol. The problem is I'm kinda newbie on this matter and something is missing me.
The goal is download the file AREQA.txt from the network to the device. However I don't even can verify if the code can trace the file location because the application crashes when I compile it to the device (it loads fine but crashes when I call the DownLoadF001 procedure). Here's the code:
public void DownLoadF001(View v) {
jcifs.Config.registerSmbURLHandler();
String user;
String password;
String filename;
File localFile;
SmbFile path = null;
try {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null,"######", "********");
path = new SmbFile("smb:\\192.168.1.11/.../AREQA.txt", auth);
try {
if(path.exists()){
Toast.makeText(getApplicationContext(), "Sucesso!", Toast.LENGTH_LONG).show();
}
} catch (Exception e1) {
Toast.makeText(getApplicationContext(), e1.toString(), Toast.LENGTH_LONG).show();
}
} catch (MalformedURLException e2) {
Toast.makeText(getApplicationContext(), e2.toString(), Toast.LENGTH_LONG).show();
}
}
I already tried to remove the inside try from the main one (with all its associated code), and the application stops crashing. However, without it, I can't see if the connection is working.
EDIT: I managed to catch the error (Exception e1):
java.lang.NullPointerException: Attempt to invoke virtual method int java.lang.String.length()' on a null object reference. Any ideas to solve it?
Also, as pointed by #greenapps, I'm calling this procedure from a .xml button by onClick method.
Related
Is there a way to see Android logs that were logged before connecting to the Android Studio?
I have an app that tracks GPS location. The issue is that it terminates after some time and I get the Android system message that says "Application Terminated"
I want to see what went wrong and where. When I connect Android studio later, it shows logs that happened from time it is connected.
I want the logs from past.
There are couple of things you can try to resolve:
1) I generally write logs when I have such cases to test.
public static void writeToFile(String msg) {
Log.d("MyApp", msg);
try {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
FileOutputStream dio = null;
File file = new File(Environment.getExternalStorageDirectory(), "MyApp_File_Logs.txt");
if (file != null) {
try {
dio = new FileOutputStream(file, true);
dio.write((msg+"\n").getBytes());
dio.close();
dio = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
Log.e("MyApp", "Exception in writeToFile(): " + e.getMessage());
}
}
So instead of Log.d , Use this Utility method. You can add time in the message to be more precise.
Done forget to give write external storage permission to you app
2) Once you see crash , go to command prompt
and use the below commands:
adb shell
logcat -b crash
You might see something in this, if you connect within a minute or so
3) Increase the "Logger Buffer Size " in your developer options , but in this case you will see delay in getting logs when you connect your device to adb and open logcat.
you can add a log module into your app,let log module output your app's log into local file,like logger
I'm using usb-serial-for-android library and I am getting some strange results. After 2.5 hours of continuous communicating with the serial port and reading and writing successfully, I get this exception:
exception in UsbManager.openDevice
android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.hardware.usb.IUsbManager$Stub$Proxy.openDevice(IUsbManager.java:339)
at android.hardware.usb.UsbManager.openDevice(UsbManager.java:255)
at com.hoho.android.usbserial.driver.UsbSerialProber$1.probe(UsbSerialProber.java:63)
at com.hoho.android.usbserial.driver.UsbSerialProber.probeSingleDevice(UsbSerialProber.java:174)
But when i force close my app and then restart it, everything is fine and my app can communicate with the port again.
It maybe useful to mention that before the exception , I get this exception:
java.io.FileNotFoundException: /sdcard/log.txt: open failed: EMFILE (Too many open files)
at libcore.io.IoBridge.open(IoBridge.java:406)
at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
at java.io.FileWriter.<init>(FileWriter.java:58)
at org.example.myapp.util.L.log(L.java:32)
I use class L for logging purposes:
public class L {
public synchronized void log(String message){
File logFile = new File("sdcard/log.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(new Date(DateProvider.getInstance().getCurrentDateAsMillisecs()).toString()+": "+message);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It seems that some kind of buffer or cache is getting filled and prevents communicating with the device.
How can I get rid of the exception?
Update:
Writing to log file never fails even though I'm getting the exception. It only affects communicating with usb device.
You are opening too many files.
Problems I have found:
- You never close logFile
- You open the file in the log function, a static File would be better and could be initialized in a log_init(); function.
Or, make logFile an object variable and initialize it in the constructor.
I think solving these will solve your problem.
Can you not use getFilesDir() to pass the directory path while creating file
public class L {
public static File logFile = new File("sdcard/log.txt");
public synchronized void log(String message){
....
Everytime you call new File you request a file resource from the system. As you keep doing it the system will complain that you opened too many files. To avoid this, request the file only once.
I am constantly getting error reports (from users) such as:
Caused by: Status Code: 400, AWS Service: AmazonSimpleDB, AWS Request ID: c5cb109d-bbff-fcea-bc0d-0cb60ff8f6af, AWS Error Code: RequestExpired, AWS Error Message: Request has expired. Timestamp date is 2012-06-06T13:19:59.415Z. Current date is 2012-06-06T14:20:03Z
Apparently this is because the user has the wrong timezone or something set? Regardless, I would like to catch this particular error and post a message to the user asking them to check their timezone settings however I can't find a way to do it. If I catch AmazonServiceException, the error shows up as null.
How can I catch errors based on Status Code or even Error Code? The current code that I tried looks like this:
try {
dostuff()
} catch (IOException e) {
updateAWS("DownloadErrors");
return "filenotfound";
} catch (AmazonServiceException e) {
return "downloadfail";
}
However AmazonServiceException e is always null so I can't pull any information from it.
other code:
private void doStuff() throws IOException, AmazonServiceException{
//code here
}
Apparently this is what I needed. SDb tracks "RequestExpired" and S3 uses "RequestTimeTooSkewed"
Also, this appears to be occurring because the system time is >15 minutes different than the AWS server. I put a note to the user to check their time and use "Automatic" date/time if possible. Tested it myself and reproduced the error as well as the solution.
try {
result = doOperations();
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("RequestExpired") || e.getErrorCode().equals("RequestTimeTooSkewed")) {
result = "timestamp";
}
}
return result;
}
I am an amateur in android coding.
I am trying to setup an android app with the ability to download a file from an ftp server. While running the code on the android 2.2 emulator, i am able to connect to the ftp server but the downloading part is showing an error. LogCat gives "download failed".
package com.ftconnect.down;
import java.io.FileOutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import org.apache.commons.net.ftp.*;
public class FTPConnectActivity extends Activity {
/** Called when the activity is first created. */
public FTPClient mFTPClient = null;
public boolean mConnect;
public boolean mDownload;
public boolean mDisconnected;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mConnect = ftpConnect("xxx.xxx.xxx.xxx", "admin",
"123456", 21);
mDownload = ftpDownload("xxx.xxx.xxx.xxx/ftp.mp3", "/sdcard");
mDisconnected = ftpDisconnect();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
Log.d("ftpConnectApp", "Connecting to " + host);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
return status;
}
} catch (Exception e) {
Log.d("ftpConnectApp", "Error: could not connect to host " + host);
}
return false;
}
public boolean ftpDownload(String srcFilePath, String desFilePath) {
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);
;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d("ftpConnectApp", "download failed");
}
return status;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
Log.d("ftpConnectApp",
"Error occurred while disconnecting from ftp server.");
}
return false;
}
}
I have setup the internet and write external permission in the android manifest file. Should i include any other permissions?
Also, let me know if there is any changes to be made to the code above. Is the destination address as '/sdcard' correct?
Thanks in advance.
You need to add Exception variable in your log message. You may also want to print full stack trace of the problem using:
e.printStackTrace();
Generally /sdcard should work, however it is more reliable to request SD card location using Environment object. See more details about file storage on android in
link
Also, let me know if there is any changes to be made to the code above. Is the destination address as '/sdcard' correct?
At the very least you should use /sdcard/filename.ext although this would only be OK for testing purposes if you are sure that /sdcard is a valid root directory.
To do things correctly, use getExternalFilesDir to find the correct path to the external storage 'files' directory that can be used for 'private' files for your own app. See the example code in that link for how to use it. You'll need to provide a filename for the output stream not just a path to a directory.
This may not be the answer to your problem but simply using...
FileOutputStream desFileStream = new FileOutputStream(desFilePath);
...when desFilePath is a directory, i.e., /sdcard, and not a file is guaranteed to fail.
Use
mFTPClient.enterLocalActiveMode();
after login
I've got it wrapped in a try catch, but the exception still trips that ugly screen.
URL u = null;
try {
u = new URL(txturl.getText().toString());
}
catch (MalformedURLException e) {
ReportError(e,"Unable to connect to "+u);
}
calls this:
private void ReportError(Exception e, String message){
Display(message+" - "+ e.getMessage().toString());
System.out.println(">>>>>>>>>>>>>>>>>>>>> "+message+" - "+e.getMessage().toString());printStackTrace();
}
Any way around this. It happens on the Android 2.2 emulator with Eclipse and on my Sprint Hero.
Do I have to validate the form?
Thanks.
I just needed to return after these exceptions. duh. sorry.