How to access files on a local server in android? - android

I need to access files on a local sever, and obtain their path for use in a File object.
I don't think I need to use HttpURLConnection for this purpose, do I?
Also, File file = new File(IPAddress) doesn't work.
Where IPAddress looks something like smb://192.168.1.xxx.
Will file:///192.168.1.xxx work for IPAddress?
I'm not able to find a solution on the internet where both accessing a local server and listing its files is achieved.
So, how do I get file paths from a local server for performing File operations?
Edit 1:
By local server I mean a computer on my network on which I have a shared folder.
And I'm building an app that can access that folder and contents in it and do something with them.
I am facing problems fetching file paths to that shared folder content.

Thanks everyone who helped...
My answer might help someone.
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", username, password);
// username and password which you use for logging into your Windows PC
SmbFile network;
try {
network = new SmbFile("smb://servername or IPAddress", auth);
for (SmbFile node : network.listFiles()) {
// network path is now contained in 'node'
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
}
You'll have to add<uses-permission android:name="android.permission.INTERNET" />in your AndroidManifest.xml before the <application> tagandActivityCompat.requestPermissions(this /*context*/, new String[]{Manifest.permission.INTERNET}, MY_PERMISSIONS); in your Activity.java for getting access to Internet on API target 23 (Android 6.0) and above.
Download and include in your project jcifs-x.x.xx.jar for SmbFile and NtlmPasswordAuthentication Class, from here.

Related

Android - unzip file during first app run

I have an apk file which contains zipped database (in asset folder). I want to unzip this database during first app run. For that case I am going to use zip4j like so:
public void unzipping() {
String source = "";//here source of zipped database
String destination = "";//here where database should be after installation
String password = "mypassword";
try {
ZipFile zipFile = new ZipFile(source);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
}
The problem is that I don't know what correct path to specify in "source" and "destination".
There is nothing wrong with using encryption to protect user data. But understand, that the attacker can always decompile/memory dump your app and grab the password you are using to read/write to the database.
I'd a SQLCipher , which makes it transparent to the other parts of the app.

where can I upload json file?

I have wrote a json file with data I will get it to recycleview in android but I don't know where can I upload this file to access it into android project
There are 2 ways you can do that:
Local Storage: You can save a JSON file in your project locally. (already answered by others)
Upload your JSON: You can upload your JSON at jsonbin.io and it will generate an API that you can use in your project.
You can store JSON file in your assets folder......
void saveStringToFile(String path, String content) {
try {
File newFile = new File(path);
newFile.createNewFile();
FileOutputStream fos = new FileOutputStream(newFile);
fos.write(content.getBytes());
fos.flush();
fos.close();
Constant.logD("File "+ newFile.getName()+ " is saved successfully at "+ newFile.getAbsolutePath());
} catch (Exception e) {
Constant.logE("Unable to save file", e);
}
}
Mention a path in a mobile sdcard like Environment.getExternalStorageDirectory().getAbsolutePath()+"/" + System.currentTimeMillis()+".jpg" as path
Based on your requirement:
Best option is to host it on a (web server if you have one)
If you don't, share the file on GDrive or Dropbox (or similar hosting services which provide free storage). Share it with read-only access for your app to read from.
You can put your json file in the assets folder and best option is host the json file on the server and use the data (API) in your project.

Android file writing

Having a problem writing out to a file, this code is taken directly from the android developer page and then tweaked a bit by me. Is there something i am missing? Quite new to Android development so sorry if it's something blatantly obvious.
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FileOutputStream outputStream;
String data = "hello";
File fileDir = new File("data.txt");
if (!fileDir.exists())
fileDir.mkdirs();
try {
outputStream = openFileOutput("data.txt",Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Basically, your problem is that you are trying to do it twice, once in a way that won't work, and once in a way that will, but hides the result.
File fileDir = new File("data.txt");
if (!fileDir.exists())
fileDir.mkdirs();
This would create a Java File object connected to a hypothetical file called "data.txt" located in the current working directory, which for an Android app is the root directory of the device - a place you most definitely are not allowed to write to. However, this may not obviously cause any errors, as the root directory exists so mkdirs() will do nothing, and you only create a File object, you don't actually try to create a file on "disk". Effectively this code does nothing for you - get rid of it.
Next you try something basically workable:
try {
outputStream = openFileOutput("data.txt",Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
openFileOutput() is a method of a Context (Activity or Service) which creates an output stream to write to an actual file located in the private internal storage area of your app. This is all fine and good, and normally a good choice for storing typical data. However, it is not a place that you will be able to examine when running a release app on a secured device, as neither ADB based tools nor Mass Storage or MTP access over USB have rights to it. So it's entirely possible that this code worked, but you had no way to discover that fact. If you are on an emulator, you can access this location with ADB or the DDMS browser, and if your apk is a debug one, you can use the run-as command line tool in the shell.
If you want to share the data, you might consider putting it on the External Storage instead.

Apache Ftp server integration with Android

I am working on integrating Apache FTP server to my Android app.
Follow the instructions here ( Embedding FtpServer in 5 minutes): http://mina.apache.org/ftpserver-project/embedding_ftpserver.html.
However, with all the codes included and the jar files imported to my android project, I got two major errors:
1. App crash upon ftp server start claiming class not found
2. Dalvik error 1
Tried every method by researching all related problems and the solution is to keep the minimal subset of the jar files that are listed in the (Embedding FtpServer in 5 minutes) instruction and make the code compile. Since there are not many jar files so I just did some try and error to get my minimal subset.
After that I use some new code to start the ftp server(here is the link): writing a java ftp server
However I couldn't connect because it says missing user.properties file. I download ftpserver-1.0.6-src source code and put the user.properties file into my android sdcard to make the ftp start. I put the user.properties file in the assets folder first, then copy it to the sdcard by using some code.
Now everything seems to work. However, I am not able to use anonymous login as my user name and password is set using:
BaseUser user = new BaseUser();
user.setName("test");
user.setPassword("test");
If I don't set it, the code won't compile.
Log in as anonymous user is the last part I have to do.
Another trivial thing is when I ftp to my android server, it won't allow me to download the files as it returns no permission error.
Any suggestions are welcome. Thank you
I've have had the same problem, so I've created my custom new users.properties file.
Here it is the code:
File files=new File(filepath + "/users.properties");
if (!files.exists()) {
try {
files.createNewFile();
} catch (IOException e) {
Log.e(TAG, "Errore nella creazione del file di log", e);
e.printStackTrace();
}
}
userManagerFactory.setFile(files);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
UserManager um = userManagerFactory.createUserManager();
BaseUser user = new BaseUser();
user.setName("xxx");
user.setPassword("yyy");
user.setHomeDirectory("/mnt/sdcard");
List<Authority> auths = new ArrayList<Authority>();
Authority auth = new WritePermission();
auths.add(auth);
user.setAuthorities(auths);
try {
um.save(user);
} catch (FtpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Convert HttpResponse to an .apk file

The problem is this:
I make an internet connection to some url and receive an HttpResponse with an app_example.apk.
Then I want to create a file (an .apk)
in the sdcard with this data so that this downloaded application
can be installed later.
How can I convert the HttpResponse to an .apk file?
Let's clear some details:
I have to get this apk file through an internet connection to my server
I don't want to install this applications I receive on the sdcard
All of this has to be done in my code, I cannot use android market
I am currently writing to that file.
What I'm doing is converting the HttpResponse to a byte[ ],
then that byte[ ] is written to a file (an .apk) using an ObjectOutputStream.
Like this:
// byte[] appByteArray - already has the internet response converted in bytes
try {
file = new File(Environment.getExternalStorageDirectory()+"/"+appName+".apk");
file.createNewFile();
FileOutputStream stream = null;
stream = new FileOutputStream(file, false);
ObjectOutputStream objectOut =
new ObjectOutputStream(new BufferedOutputStream(stream));
objectOut.writeObject(appByteArray);
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
In the end, the file is created
and has the received content.
When I try to install it,
through a VIEW intent (using the default installer)
I get a parse error saying that it could not find the AndroidManifest.xml.
I think that in some step along the way, the received data is being corrupted.
Do you have another method to solve this?
Many thanks
Don't use an ObjectOutputStream, byte array is serialized as Object, not written as raw data.
Are you sure that you have SD card write permission? android.permission.WRITE_EXTERNAL_STORAGE
Don't write into SD card root directory. Number of files in root dir can be limited. Instead create you app subdirectory on SD CARD.
This code works for me:
try {
String filePath = Environment.getExternalStorageDirectory()
+ "/myappdir/" + appName + ".apk";
File file = new File(filePath);
file.getParentFile().mkdirs();
file.createNewFile();
BufferedOutputStream objectOut = new BufferedOutputStream(
new FileOutputStream(file));
objectOut.write(appByteArray);
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
This may not be the core problem, but I don't think you want to wrap stream in an ObjectOutputStream, since that is used for object serialization. It could be that it is adding extra data to the file so it can be deserialized with ObjectInputStream.
I would try pulling the apk off of the emulator (or device) and check it's MD5 versus the file on the server to make sure that the bits are being written out correctly.
Take a look at Pavel P's answer.
Also, I would note that your idea of installing the APK using the VIEW intent action does work, as I have tested this technique in the past.
However, unless the user has explicitly gone into Settings → Applications and selected "Allow non-Market applications", your installation will fail and the user will just see a screen telling them that for security reasons the installation has been blocked.
Basically you really need to rely on having fairly tech-savvy users who are willing to overlook a scary security warning and go and disable that setting.

Categories

Resources